Senin, 26 Oktober 2015

Senin, 17 Agustus 2015

C#/CSharp Upload file to FTP server with progress bar


Introduction

This is a simple code to upload file with progress status. This is just a code snippet for me because it's hard to find a similar one. I will be happy if you find this code useful. Any suggestion for my traditional style code will be happily accepted.

Link to Working code

Using the code

Net 3.5 framework

Minimum framework is net 3.5 (See next section for net 4.5 framework)
Create new windows Form Application project targeted for net 3.5 or later.
Add button1, progressBar1 and label1 to Form1:
Set progressbar1.Maximum to 100
Component required
System.IOSystem.Net.
To avoid UI including progressBar1 from freezing use BackgroundWorker.
Form1.cs Complete code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Simple_FTP_Upload
{
    public partial class Form1 : Form
    {
        string filePath = @"C:\fileFolder\";
        string filetoUpload = "filetoupload.7z";
        string ftpDir = "ftpDir/";
        string ftpAddress = "ftp://ftp.ftpserver.net/";
        string ftpUser = "user";
        string ftpPassword = "password";

        BackgroundWorker backgroundWorker1 = new BackgroundWorker();//look at ref 5

        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);//look at ref 5
            backgroundWorker1.ProgressChanged +=
                new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);//look at ref 5
            backgroundWorker1.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);//look at ref 5
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            progressBar1.Visible = true;

            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }               
        }

        string processFtp(BackgroundWorker worker)
        {
            string result = "";
            try
            {
                // Get the object used to communicate with the server.
                FtpWebRequest request =
                    (FtpWebRequest)WebRequest.Create(ftpAddress + ftpDir + filetoUpload);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);

                request.KeepAlive = false;//look at ref 4
                request.ReadWriteTimeout = 1000000000;//look at  4
                request.Timeout = 1000000000;//look at  4

                using (Stream requestStream = request.GetRequestStream())
                {

                    using (FileStream fs = File.OpenRead(filePath + filetoUpload))
                    {
                        byte[] b = new byte[10 * 1024];
                        int readLength = 0;
                        int sentLength = 0;
                        while ((readLength = fs.Read(b, 0, b.Length)) > 0)
                        {
                            requestStream.Write(b, 0, b.Length);
                            int percentComplete = (int)((float)(sentLength+=readLength) / 
                                                                        (float)fs.Length * 100);
                            //Update progress bar according to b.length
                            worker.ReportProgress(percentComplete);
                        }
                    }
                }

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();

                //Successfull sent information
                result = "Kirim Data selesai, status :" + response.StatusDescription;
            }
            catch (WebException e)
            {
                //Fail sent information
                result = "Kirim Data Gagal." +
                                    "\n Status :" + e.Message;
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    result = result + "Status Code : " +
                        ((FtpWebResponse)e.Response).StatusCode;
                    result = result + "\nStatus Description : " +
                        ((FtpWebResponse)e.Response).StatusDescription;
                }
            }
            catch (Exception e)
            {
                result = e.Message;
            }
            return result;
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            e.Result = processFtp(worker);
        }

        // This event handler updates the progress bar. 
        private void backgroundWorker1_ProgressChanged(object sender,
            ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.label1.Text = e.Result.ToString();
            this.button1.Enabled = true;
        }

    }
}

Net 4.5 framework

Create new windows Form Application project targeted for net 4.5 or later;
Add button1, progressBar1 and label1 to Form1:
Set progressbar1.Maximum to 100
Component required
System.IO, System.Net.
Update progress bar is more simpler in net 4.5 than net 3.5 use async task so UI thread will not blocked. For more detailed you can chek this https://msdn.microsoft.com/en-us/library/hh191443.aspx
Complete code for Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Simple_Upload_to_FTP_net_4._5
{
    public partial class Form1 : Form
    {
        string filePath = @"C:\fileFolder\";
        string filetoUpload = "filetoupload.7z";
        string ftpDir = "ftpDir/";
        string ftpAddress = "ftp://ftp.ftpserver.net/";
        string ftpUser = "user";
        string ftpPassword = "password";

        public Form1()
        {
            InitializeComponent();
        }

        // Mark the event handler with async so you can use await in it. 
        private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Uploading";
            button1.Enabled = false;
            await processFtp();
        }

        async Task processFtp()
        {
            string result = "";
            try
            {
                // Get the object used to communicate with the server.
                FtpWebRequest request =
                    (FtpWebRequest)WebRequest.Create(ftpAddress + ftpDir + filetoUpload);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);

                request.KeepAlive = false;//look at ref 4
                request.ReadWriteTimeout = 1000000000;//look at ref 4
                request.Timeout = 1000000000;//look at ref 4

                using (Stream requestStream = request.GetRequestStream())
                {

                    using (FileStream fs = File.OpenRead(filePath + filetoUpload))
                    {
                        byte[] b = new byte[10 * 1024];
                        int readLength = 0;
                        int sentLength = 0;
                        while ((readLength = fs.Read(b, 0, b.Length)) > 0)
                        {
                            await requestStream.WriteAsync(b, 0, b.Length);
                            int percentComplete = (int)((float)(sentLength += readLength) / 
                                                                         (float)fs.Length * 100);
                            progressBar1.Value = percentComplete;
                        }
                    }
                }

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();

                //Successfull sent information
                result = "Kirim Data selesai, status :" + response.StatusDescription;
            }
            catch (WebException e)
            {
                //Fail sent information
                result = "Kirim Data Gagal." +
                                    "\n Status :" + e.Message;
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    result = result + "Status Code : " +
                        ((FtpWebResponse)e.Response).StatusCode;
                    result = result + "\nStatus Description : " +
                        ((FtpWebResponse)e.Response).StatusDescription;
                }
            }
            catch (Exception e)
            {
                result = e.Message;
            }
            label1.Text = result;
            button1.Enabled = true;
        }

    }
}

References

  1. FTP example: https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
  2. Additional FTP example: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class
  3. Handling HttpWebRequest error: https://msdn.microsoft.com/en-us/library/system.net.webexception.response(v=vs.110).aspx
  4. Resolve big file upload: http://stackoverflow.com/questions/1060966/big-files-uploading-webexception-the-connection-was-closed-unexpectedly
  5. Update progressbar with backgroundworker: https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Minggu, 04 April 2010

vb mouse wheel

http://www.xtremevbtalk.com/showthread.php?t=304609


Private Const WM_VSCROLL As Long = &H115
Private Const WM_HSCROLL As Long = &H114
Private Const WM_MOUSEWHEEL As Long = &H20A

Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Const SB_LINEUP As Long = 0
Private Const SB_LINEDOWN As Long = 1

Private Function NewWindowProc(ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Select Case Msg
Case Is = WM_MOUSEWHEEL
If (wParam > 0) Then
SendMessage Scroll.hWnd, WM_VSCROLL, SB_LINEUP, 0&
Else
SendMessage Scroll.hWnd, WM_VSCROLL, SB_LINEDOWN, 0&
End If
End Select

NewWindowProc = CallWindowProc(OldWindowProc, hWnd, Msg, wParam, lParam)
End Function

Rabu, 23 Desember 2009

Memulihkan registry setting akibat serangan virus pada windos xp

Munculkan folder option pada windows xp Klik disini untuk download perbaikannya. (Restore Folder Option. click here)

Mengembalikan registry yang di-disable Klik disini untuk download perbaikannya.(Re enable Disabled Registry. click here)

Daptar printer tidak muncul Klik disini untuk download perbaikannya.(Restore Printer list. Click here)

File ini berguna untuk mencegah virus yang berjalan menggunakan windows scripting host plus mamatikan autorun

Ada virus yang mengelabui pengguna dengan menghilangkan panah pada shortcut/link ke folder sehingga link-nya sendiri kelihatan seperti folder. Klik disini untuk download perbaikannya

Menu Run dan Find/Search di Start Menu Hilang. Klik disini untuk download perbaikannya (Click here to restore Run and Find/search menu)

Selasa, 31 Maret 2009

Daftar beberapa penyedia Widget Polls atau Voting untuk Blog atau website

http://www.toluna.com
  • harus daftar dulu
  • satu poll berlaku untuk 6 bulan maksimum
  • ada program untuk dapat hadiah tapi saat ini untuk indonesia belum termasuk
  • disainnya tidak bisa dikostumisasi
  • widget bebas iklan
  • bisa beberapa poll
  • harus daftar dulu
  • satu poll akan aktif terus sebelum kita menonaktifkannya
  • disain ada empat pilihan
  • bebas iklan, hanya ada logo Bravenet saja
  • versi free hanya dapat mengaktifkan satu poll saja
  • dibawah adalah contoh poll dari bravenet.com




yang ini adalah vote dari bravenet

Selasa, 10 Maret 2009

Convert week number to month (VB 6)

Private Sub WeektoMonth_01() 'Start with week in which January 1 occurs
Dim FirstDate As Date ' Declare variables.
Dim IntervalType As String
Dim WeekNumber As Integer
Dim Msg
IntervalType = "ww" ' "ww" specifies weeks as interval.
FirstDate = DateSerial(Year(Now), 1, 1)
WeekNumber = InputBox("Enter number of weeks to add")
Msg = "Month of week " & WeekNumber & " is " & Month(DateAdd(IntervalType, WeekNumber - 1, FirstDate))
MsgBox Msg

End Sub