Transfer Data Across FTP Server

Project Review

     Berikut ini merupakan aplikasi transfer data dari ftp(file transfer protocol) ke local disk secara otomatis. manfaatnya user tak lagi harus mengecek data update ftp nya karena file data yang ada di ftp dengan format .zip .rar .7z .txt sudah ditransfer ke local disk (Branch / Head Office) melalui aplikasi ini, dan data yang telah diterima itu pun sudah otomatis diprosses ke database. Cukup menghemat pekerjaan bukan :) 

How To Use

     Pada dasarnya ada dua 2 aplikasi untuk menjalankan program ini, Configuration Application dan Transfer File Ftp Server. 

a). Configuration application. yaitu berfungsi untuk menyetting local database, ftp password, mereview log data. configuration application adalah aplikasi untuk menyetting "menjembatani" hak akses dari ftp ke local folder maupun sebaliknya. aplikasi ini juga berfungsi untuk membaca file configuration dalam bentuk text(.txt) yang ada di local disk C yang terdiri dari beberapa property seperti encrypted password dll. Aplikasi akan membaca config file tersebut dan mendisplay kedalam form seperti gambar form dibawah ini, disini user bisa mengisi property sumber data berdasarkan directory di ftp yang akan diprosses, yang terdiri dari property IP ftp, ftp username, ftp password, ftp directory dan ftp archive directory sedangkan disisi database user mengisikan server name, login, password, database"database name" dan output file yang terdiri dari property directory dan archive directory(local). User juga bisa melihat log data dengan rentan waktu yang bisa ditentukan. log data ini terbentuk ketika ada data yang tak bisa diprosses baik itu karena format data yang salah, existed data, maupun karena error lainnya. Log data dalam bentuk text(.txt) ini juga bisa dilihat di root aplikasi ini. berikut snapshoot and source code view log.

setconfig

 private void logbtn_Click(object sender, EventArgs e)
        {
            try
                {
            
                    dateTimePicker1.Format = DateTimePickerFormat.Custom;
                    dateTimePicker1.CustomFormat = "yyyy-MM-dd";
                    string startdate = dateTimePicker1.Text;

                    dateTimePicker2.Format = DateTimePickerFormat.Custom;
                    dateTimePicker2.CustomFormat = "yyyy-MM-dd";
                    string enddate = dateTimePicker2.Text;

                    SqlConnection con = new SqlConnection("server=" + ServerNameTxt.Text + "; database=" + DatabaseTxt.Text + ";user id=" + LoginTxt.Text + "; password=" + PasswordTxt.Text + "");
                    string selectCommandText = "DECLARE @startdate datetime,@enddate datetime SET @startdate ='" + startdate + "' SET @enddate='" + enddate + "' SELECT * FROM templog where entrydate BETWEEN @startdate AND (@enddate + 1) ORDER BY EntryDate";
                    using (SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, con))
                    {
                        using (DataTable table = new DataTable("templog"))
                        {
                            adapter.Fill(table);
                            StringBuilder commaDelimitedText = new StringBuilder();
                            commaDelimitedText.AppendLine("SourceFileName, ErrorNumber, ErrorMessage, ErrorLine, EntryDate, TotalRow");
                            foreach (DataRow row in table.Rows)
                            {
                                string value = string.Format("{0}, {1}, {2}, {3}, {4}, {5}", row[0], row[1], row[2], row[3], row[4], row[5]);
                                commaDelimitedText.AppendLine(value);
                            }
                            File.WriteAllText("c:\\Dtsms\\logftxt.txt", commaDelimitedText.ToString());
                        }
                    } Process.Start("c:\\Dtsms\\logftxt.txt");
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }            
        }
b). Transfer File Ftp Server, ini aplikasi utama yang berfungsi untuk mentransfer data dari ftp ke local disk secara otomatis. Nantinya form ini tak akan terlihat di bar windows karena akan dijalankan melalui task scheduller dan hanya akan terlihat di task manager ketika aplikasi ini berjalan. 

ftp server

WorkFlow

Cara kerja aplikasi : Terdapat beberapa file data di ftp folder, diantaranya data file .txt, zipped file .txt dalam format .zip, .rar, .7z. Aplikasi akan mendownload data dari sumber data yang ada dalam directory ftp tersebut baik itu format .rar .zip .7z .txt, sebelum didownload aplikasi ini akan terlebih dahulu meng Archive semua file tersebut dalam bentuk .7z, hal ini berfungsi untuk mengecilkan ukuran file tersebut sehingga prosses download akan lebih cepat. nahh setelah didownload ke local folder/local directory maka aplikasi akan meng extract .7z tersebut dan jika ada zipped file .rar .zip .7z didalamnya maka aplikasi akan otomatis mengextract di local directory. setelah di extract data dalam bentuk file text itu akan di execute ke database. dan yang terakhir jika prosses execute kedalam database selesai maka aplikasi akan mengArchive data yang ada dilocal folder ke Archive directory dan akan mengArchive sumber data di ftp directory ke Ftp Archive Directory. Done! Berikut intipan source code nya(:
 private void btnProsses_Click(object sender, EventArgs e)
        {
            //this.Hide();

            bool CheckConnection = Windtsms.ConnectionClass.IsConnectedToInternet();
            if (CheckConnection == true)
            {
            
            //download text
            string[] filetxts = GetFileList("*.txt");
            if (GetFileList("*.txt") != null)
            {
                foreach (string filetexts in filetxts)
                {
                    Download(filetexts);
                }
            }

            //download zip
            string[] files = GetFileList("*.zip");
            if (GetFileList("*.zip") != null)
            {
                foreach (string file in files)
                {
                    Download(file);
                }
            }

            //download 7z
            string[] filesevenz = GetFileList("*.7z");
            if (GetFileList("*.7z") != null)
            {
                foreach (string file7 in filesevenz)
                {
                    Download(file7);
                }
            }

            //download rar
            string[] filerars = GetFileList("*.rar");
            if (GetFileList("*.rar") != null)
            {
                foreach (string filerar in filerars)
                {
                    Download(filerar);
                }
            }

            //extract rar 
            if (GetFileList("*.rar") != null)
            {
                    string pwd = "123";
                    string des = FileDirectoryTxt.Text;
                    foreach (string rareach in filerars)
                    {
                        string src = FileDirectoryTxt.Text + rareach;
                        System.Diagnostics.Process proc = new System.Diagnostics.Process();
                        proc.StartInfo.FileName = @"C:\Dtsms\unrar.exe";
                        proc.StartInfo.CreateNoWindow = true;
                        proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        proc.EnableRaisingEvents = true;
                        proc.StartInfo.Arguments = String.Format("x -or -p{0} {1} {2}", pwd, src, des);
                        proc.Start();
                        proc.WaitForExit();
                    }
            }


            //extrac 7z 
            if (GetFileList("*.7z") != null)
            {
                string path7 = FileDirectoryTxt.Text;
                foreach (string sevenzip in filesevenz)
                {
                    string source = FileDirectoryTxt.Text + sevenzip;
                    ProcessStartInfo zipper = new ProcessStartInfo(@"C:\Dtsms\7za.exe");
                    zipper.Arguments = string.Format("x " + source + " -o" + path7 + " -aot");
                    zipper.WindowStyle = ProcessWindowStyle.Hidden;
                    Process process = Process.Start(zipper);
                    process.WaitForExit();
                }
            }

            //extract zip
            if (GetFileList("*.zip") != null)
            {
                string pathzipn = FileDirectoryTxt.Text;
                foreach (string zipp in files)
                {
                    string sourcez = FileDirectoryTxt.Text + zipp;
                    ProcessStartInfo zipper = new ProcessStartInfo(@"C:\Dtsms\7za.exe");
                    zipper.Arguments = string.Format("x " + sourcez + " -o" + pathzipn + " -aot");
                    zipper.WindowStyle = ProcessWindowStyle.Hidden;
                    Process process = Process.Start(zipper);
                    process.WaitForExit();
                }
            }

            //exec text
            SqlConnection constring = new SqlConnection("server=" + ServerNameTxt.Text + "; database=" + DatabaseTxt.Text + ";user id=" + LoginTxt.Text + "; password=" + PasswordTxt.Text + "");
            if ((filetxts != null) || (files != null) || (filesevenz != null) || (filerars!=null))
            {  
                try
                {
                    SqlDataReader rdr = null;
                    constring.Open();
                    SqlCommand SqlComm = new SqlCommand("ImportFiles", constring);
                    SqlComm.CommandType = CommandType.StoredProcedure;
                    SqlComm.Parameters.Add(new SqlParameter("@FilePath", this.FileDirectoryTxt.Text));
                    SqlComm.Parameters.Add(new SqlParameter("@ArchivePath", this.ArchiveDirectoryTxt.Text));
                    rdr = SqlComm.ExecuteReader();
                    SqlComm.CommandTimeout = 0;

                    constring.Close();

                    if (filetxts != null) {
                    foreach (string movetxttoarchive in filetxts)
                    {
                        movefilemethod(movetxttoarchive);
                    }}
                    if(files != null){
                    foreach (string movefile in files)
                    {
                        movefilemethod(movefile);
                    }}

                    if (filesevenz != null)
                    {
                        foreach (string movesevenz in filesevenz)
                        {
                            movefilemethod(movesevenz);
                        }
                    }
                    if (filerars != null)
                    {
                        foreach (string filerarg in filerars)
                        {
                            movefilemethod(filerarg);
                        }
                    }

                    string[] filesx = Directory.GetFiles(FileDirectoryTxt.Text, "*.zip", SearchOption.AllDirectories);
                    foreach (string file in filesx)
                        try { File.Delete(file); }
                        catch { };

                    string[] fileszz = Directory.GetFiles(FileDirectoryTxt.Text, "*.7z", SearchOption.AllDirectories);
                    foreach (string file7 in fileszz)
                        try { File.Delete(file7); }
                        catch { };

                    string[] filesrar = Directory.GetFiles(FileDirectoryTxt.Text, "*.rar", SearchOption.AllDirectories);
                    foreach (string filer in filesrar)
                        try { File.Delete(filer); }
                        catch { };

                    
                    string pathdel = ArchiveDirectoryTxt.Text; //"
                    DirectoryInfo dirInfo = new DirectoryInfo(pathdel);
                    FileInfo[] fileInfos = dirInfo.GetFiles();

                    foreach (FileInfo fileInfo in fileInfos)
                    {
                        if (fileInfo.LastWriteTime < DateTime.Now.AddDays(-7))
                            fileInfo.Delete();
                    }

                   
                    DirectoryInfo dirt = new DirectoryInfo(FileDirectoryTxt.Text);
                    foreach (FileInfo filet in dirt.GetFiles("*.txt"))
                    {
                        string date = DateTime.Now.ToString("yyyyMMddhhmms_");
                        System.IO.File.Move(FileDirectoryTxt.Text + filet.Name, ArchiveDirectoryTxt.Text + date + filet.Name);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("No file update in ftp directory found or cannot connect to ftp server or check your query and database ", ex.Message);
                }
            }
            else
            {
                MessageBox.Show("internet connection not available");
                this.Dispose();
            }

            //compare between aprop and bprop
            string connetionString = null;
            SqlConnection connection;
            SqlCommand command;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            string sql = null;

            

            try
            {
                connetionString = "server=" + ServerNameTxt.Text + "; database=" + DatabaseTxt.Text + ";user id=" + LoginTxt.Text + "; password=" + PasswordTxt.Text + "";
                sql = "SELECT * FROM templog ";
                connection = new SqlConnection(connetionString);

                connection.Open();
                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;
                adapter.Fill(ds, "templog");
                adapter.Dispose();
                command.Dispose();
                connection.Close();
                bprop = ds.Tables[0].Rows.Count;
                
                cprop = bprop - aprop;
                if (cprop != 0)
                {
                    MessageBox.Show("Failed to proccess " + Convert.ToString(cprop) + " Row(s)","Error Message");
                }
            }

            catch (Exception iex) { }//MessageBox.Show(iex.Message); }
            
        }
      
       public void movefilemethod(string movefilename)
        {
            try
            {
                string date = DateTime.Now.ToString("yyyyMMddhhmms_");
                NetworkCredential User = new NetworkCredential(usernametxt.Text, passwordftp.Text);
                FtpWebRequest Wr = (FtpWebRequest)FtpWebRequest.Create(("ftp://" + usernametxt.Text + "@" + Ftpservertxt.Text + "/" + directoryftp.Text + movefilename).Trim());

                Wr.Method = WebRequestMethods.Ftp.Rename;
                Wr.Credentials = new NetworkCredential(usernametxt.Text, passwordftp.Text);
                Wr.UseBinary = false;
                Wr.UsePassive = true;
                //Wr.Proxy = null; 
                Wr.KeepAlive = true;
                Wr.Timeout = 600000;
                Wr.Credentials = User;
                Wr.RenameTo = ("/" + archieveftp.Text + date + movefilename).Trim();
                Wr.GetResponse().Close();
                //MessageBox.Show("Move File Successfully");
            }
            catch (WebException e) { String status = ((FtpWebResponse)e.Response).StatusDescription; }
            catch (Exception abcs) { MessageBox.Show(abcs.Message); }
        }

        //download method
        public void Download(string file)
        {
            //MessageBox.Show("try download");
            try
            {
              
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Ftpservertxt.Text + "/" + directoryftp.Text + "/" + file));
                reqFTP.Credentials = new NetworkCredential(usernametxt.Text, passwordftp.Text);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream writeStream = new FileStream(FileDirectoryTxt.Text + "\\" + file, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }
                writeStream.Close();
                response.Close();
            }
            catch (WebException wEx)
            {
                MessageBox.Show(wEx.Message, "Download Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Download Error");
            }
        }

  

Summary

     Aplikasi ini memang tidak terlihat, tetapi akan sangat bermanfaat., apalagi ketika aktivitas data penting di ftp folder sangat banyak dan perlu diolah secara cepat. tentu akan merepotkan untuk memindahkan data satu persatu selain membutuhkan waktu juga dibutuhkan ketelitian. Dengan adanya aplikasi ini semoga bisa membantu karyawan sehingga waktunya tidak akan terbuang kepada hal yang sebenarnya sudah bisa dilakukan secara otomatis oleh komputer. Hubungi Contact jika membutuhkan informasi lebih lanjut, sekian. Wassalam..

0 comments:

Post a Comment