// Author - Sandeep Khurana // Date Created - August 02, 2001 using System; using System.Windows.Forms; using System.Drawing; using System.Net; using System.IO; using System.Text; using System.Net.Sockets; //************************************************************************** // GUI Class // STARTS // Purpose - This class creates the User Interface (Windows Forms). The user // is supposed to enter the Mainframe user id , password. //************************************************************************** public class userEntry : Form { private string[] options = { "FILE FTP" , "SUBMIT JCL" , "DB2 QUERY"} ; private Label heading, useridL, passwordL; private TextBox useridTb, passworTb; private Button okButton ; private CheckedListBox clb ; public userEntry() { //************************************************************* // Labels -->> userid , password // Heading - Mainframe Interface - BOLD //************************************************************* heading = new Label(); useridL = new Label(); passwordL = new Label(); heading.Text = "Mainframe Interface"; useridL.Text = "User Id" ; passwordL.Text = "Password" ; addCntlL(heading,30,10, "BLUE", "Bold"); // <<<-- 30 lines addCntlL(useridL,15,50, "BLACK", "NoBold"); addCntlL(passwordL,15,80, "BLACK", "NoBold"); //************************************************************* // Text Boxes -->> userid , password // Password Char = '$' // NOT Bold // Maximunm Length = 8 //************************************************************* useridTb = new TextBox(); useridTb.MaxLength = 8 ; passworTb = new TextBox(); passworTb.MaxLength = 8 ; passworTb.PasswordChar = '$' ; addCntlTb(useridTb, 170, 50, "NoBold"); addCntlTb(passworTb, 170, 80, "NoBold"); //************************************************************* // Buttons -->> OK Button // //************************************************************* okButton = new Button(); addCntlBt(okButton, "OK" , 130, 220); //************************************************************* // CheckBoxes -->> FTP, // JCL JOB, // DB2 SQL //************************************************************* clb = new CheckedListBox(); clb.BeginUpdate(); for(int i = 0 ; i<=(options.Length - 1); i++) clb.Items.Add(options[i]); clb.CheckOnClick = true ; addCntlCb(clb, 05, 120); } // <<<<-- 75 lines //*********************************************************************** // Label Control -->> Will set the properties of the labels ..like location // ,font types etc // //*********************************************************************** public void addCntlL(Label Lb, Int32 xLoc, Int32 yLoc, string colorC, string fnt) { Lb.AutoSize = true; Lb.Location = new Point(xLoc, yLoc); if (colorC == "BLACK") { Lb.ForeColor = Color.Black; } else { if (colorC == "BLUE") Lb.ForeColor = Color.Blue; else Lb.ForeColor = Color.Black; } if (fnt == "Bold") Lb.Font = new Font("Microsoft Sans Serif" , 16f , FontStyle.Bold); else Lb.Font = new Font("Microsoft Sans Serif" , 16f , FontStyle.Regular); this.Controls.Add(Lb); } //*********************************************************************** // <<<-- 105 lines // Text box control -->> Will set the properties of the TextBox // //*********************************************************************** public void addCntlTb(TextBox tb, Int32 xLoc, Int32 yLoc, string fnt) { tb.Location = new Point(xLoc, yLoc); if (fnt == "Bold") tb.Font = new Font("Microsoft Sans Serif" , 12f , FontStyle.Bold); else tb.Font = new Font("Microsoft Sans Serif" , 12f , FontStyle.Regular); this.Controls.Add(tb); } //*********************************************************************** // Button Control // //*********************************************************************** public void addCntlBt(Button bt, string nm, Int32 xLoc, Int32 yLoc) { bt.Text = nm ; bt.Location = new Point(xLoc, yLoc); this.Controls.Add(bt); bt.Click += new EventHandler(onClickB); } //*********************************************************************** // CheckBoxes Control -->> ftp, Jcl Job, Db2 Sql // //*********************************************************************** public void addCntlCb(CheckedListBox cb, Int32 xLoc, Int32 yLoc) { cb.Location = new Point(xLoc, yLoc); this.Controls.Add(cb); cb.SelectionMode = SelectionMode.One ; cb.Click += new EventHandler(onClickcb) ; } //*********************************************************************** // Event Handler for the Button "OK" // //*********************************************************************** protected void onClickB(Object mySender , EventArgs myArgs) { String uId, pWd ; uId = takeUserid(); pWd = takePasswor(); MessageBox.Show ("Password is {0} " , pWd); FTP4 ft = new FTP4(uId, pWd) ; } //*********************************************************************** // Event Handler for Checkedlistbox where the user will click on FTP file // or JCL JOB or DB2 QUERY //*********************************************************************** protected void onClickcb(Object ob1, EventArgs myArgs) { CheckedListBox cb1 = (CheckedListBox)ob1 ; // if (cb1.Checked == true) // MessageBox.Show ("You Checked me "); // else // MessageBox.Show ("You UnChecked me"); } //*********************************************************************** // Getting Userid and password //*********************************************************************** public string takeUserid() { // <<<-- 120 lines return useridTb.Text; } public string takePasswor() { return passworTb.Text; } } class MyEntry { public static void Main() { Application.Run(new userEntry()); } } //************************************************************************** // GUI Class // ENDS //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** //************************************************************************** // Mainframe section // ENDS //************************************************************************** public class FTPFactory { private string remoteHost,remotePath,remoteUser,remotePass,mes; private int remotePort,bytes; private Socket clientSocket; private long retValue; private Boolean debug; private Boolean logined; private string reply; private static int BLOCK_SIZE = 512; Byte[] buffer = new Byte[BLOCK_SIZE]; Encoding ASCII = Encoding.ASCII; public FTPFactory() { remoteHost = "localhost"; remotePath = "."; remoteUser = "anonymous"; remotePass = "ftpclient@ospreyindia.com"; remotePort = 23; debug = false; logined = false; } //*************************************************************** public void setRemoteHost(string remoteHost) { this.remoteHost = remoteHost; } public string getRemoteHost() { return remoteHost; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } public int getRemotePort() { return remotePort; } public void setRemotePath(string remotePath) { this.remotePath = remotePath; } public string getRemotePath() { return remotePath; } public void setRemoteUser(string remoteUser) { this.remoteUser = remoteUser; } public void setRemotePass(string remotePass) { this.remotePass = remotePass; } //*************************************************************************************** public string[] getFileList(string mask) { if(!logined) { login(); } Socket cSocket = createDataSocket(); sendCommand("NLST " + mask); if(!(retValue == 150 || retValue == 125)) { throw new IOException(reply.Substring(4)); } mes = ""; try { while(true) { int bytes = cSocket.Receive(buffer, buffer.Length, 0); mes += ASCII.GetString(buffer, 0, bytes); if(bytes < buffer.Length) { break; } } } catch(ArgumentOutOfRangeException e) { Console.WriteLine(" No Message Received from Host"); } char[] seperator = {'\n'}; string[] mess = mes.Split(seperator); cSocket.Close(); // 100 lines readReply(); if(retValue != 226) { throw new IOException(reply.Substring(4)); } return mess; } //************************************************************************************ public long getFileSize(string fileName) { if(!logined) { login(); } sendCommand("SIZE " + fileName); long size=0; if(retValue == 213) { size = Int64.Parse(reply.Substring(4)); }else { throw new IOException(reply.Substring(4)); } return size; } //********************************************************************************** public void upload(string fileName) { upload(fileName,false); } //***************************************************************** public void upload(string fileName,Boolean resume) { if(!logined) { login(); } Socket cSocket = createDataSocket(); long offset=0; if(resume) { try { setBinaryMode(false); offset = getFileSize(fileName); }catch(Exception) { offset = 0; } } if(offset > 0 ) { sendCommand("REST " + offset); if(retValue != 350) { //throw new IOException(reply.Substring(4)); //Remote server may not support resuming. offset = 0; } } sendCommand("STOR "+fileName); if( !(retValue == 125 || retValue == 150) ) { throw new IOException(reply.Substring(4)); } // open input stream to read source file FileStream input = new FileStream(fileName,FileMode.Open); if(offset != 0){ if(debug) { Console.WriteLine("seeking to " + offset); } input.Seek(offset,SeekOrigin.Begin); } //for progress bar long totalSize = input.Length - offset; float iCnt = 0; int per = 0, oldPer = 1; // 300 lines Console.WriteLine("Uploading file "+fileName+" to "+remotePath); while ((bytes = input.Read(buffer,0,buffer.Length)) > 0) { cSocket.Send(buffer, bytes, 0); // Showing the progress. 1..50 iCnt += bytes; per = (int) ( (iCnt / totalSize) * 100 ); if( per != oldPer && per % 2 == 0 ) { Console.Write("."); oldPer = per; } } input.Close(); Console.WriteLine(""); cSocket.Close(); readReply(); if( !(retValue == 226 || retValue == 250) ) { throw new IOException(reply.Substring(4)); } } //***************************************************************** public void uploadJCL(string fileName,Boolean resume) { if(!logined) { login(); } Socket cSocket = createDataSocket(); long offset=0; if(resume) { try { setBinaryMode(false); offset = getFileSize(fileName); }catch(Exception) { offset = 0; } } if(offset > 0 ) { sendCommand("REST " + offset); if(retValue != 350) { //throw new IOException(reply.Substring(4)); //Remote server may not support resuming. offset = 0; } } sendCommand("SITE FILETYPE=JES"); sendCommand("STOR " + fileName); if( !(retValue == 200 || retValue == 125) ) { throw new IOException(reply.Substring(4)); } // open input stream to read source file FileStream input = new FileStream(fileName,FileMode.Open); if(offset != 0){ if(debug) { Console.WriteLine("seeking to " + offset); } input.Seek(offset,SeekOrigin.Begin); } //for progress bar long totalSize = input.Length - offset; float iCnt = 0; int per = 0, oldPer = 1; Console.WriteLine("Uploading file "+fileName+" to "+remotePath); try { while ((bytes = input.Read(buffer,0,buffer.Length)) > 0) { Console.WriteLine(" Buffer is {0}", bytes); cSocket.Send(buffer, bytes, 0); // Showing the progress. 1..50 iCnt += bytes; per = (int) ( (iCnt / totalSize) * 100 ); if( per != oldPer && per % 2 == 0 ) { Console.Write("."); oldPer = per; } } } catch(Exception e) { Console.WriteLine(" An Exception is thrown {0} ", e); } //input.Close(); Console.WriteLine(""); cSocket.Close(); Console.WriteLine("Socket is closed"); readReply(); Console.WriteLine("The return value is {0}", retValue); if( !(retValue == 226 || retValue == 250) ) { throw new IOException(reply.Substring(4)); } } //******************************************************************** public void deleteRemoteFile(string fileName) { if(!logined) { login(); } sendCommand("DELE "+fileName); if(retValue != 250) { throw new IOException(reply.Substring(4)); } } //********************************************************** public void renameRemoteFile(string oldFileName,string newFileName) { if(!logined) { login(); } sendCommand("RNFR "+oldFileName); if(retValue != 350) { throw new IOException(reply.Substring(4)); } // known problem // rnto will not take care of existing file. // i.e. It will overwrite if newFileName exist sendCommand("RNTO "+newFileName); if(retValue != 250) { throw new IOException(reply.Substring(4)); } } //*************************************************************** public void mkdir(string dirName) { if(!logined) { login(); } sendCommand("MKD "+dirName); if(retValue != 250) { throw new IOException(reply.Substring(4)); } } //*************************************************************** public void rmdir(string dirName) { if(!logined) { login(); } sendCommand("RMD "+dirName); if(retValue != 250) { throw new IOException(reply.Substring(4)); } } //*************************************************************** public void chdir(string dirName) { if(dirName.Equals(".")) { return; } if(!logined) { login(); } sendCommand("CWD "+dirName); if(retValue != 250) { throw new IOException(reply.Substring(4)); } this.remotePath = dirName; Console.WriteLine("Current directory is "+remotePath); } //*************************************************************** public void close() { if( clientSocket != null ) { sendCommand("QUIT"); } cleanup(); Console.WriteLine("Closing..."); } //*************************************************************** public void setDebug(Boolean debug) { this.debug = debug; } //*************************************************************** public void setBinaryMode(Boolean mode) { if(mode) { sendCommand("TYPE I"); }else { sendCommand("TYPE A"); } if (retValue != 200) { cleanup(); throw new IOException(reply.Substring(4)); } } //****************************************************************** private void sendCommand(String command) { try { Byte[] cmdBytes = Encoding.ASCII.GetBytes((command+"\\r\\n").ToCharArray()); clientSocket.Send(cmdBytes, cmdBytes.Length, 0); readReply(); } catch(Exception e) { cleanup(); Console.WriteLine(" Exception Occurred in sendCommand method...Exiting {0}", e); } } //************************************************************************* private void readReply() { mes = ""; reply = readLine(); retValue = Int32.Parse(reply.Substring(0,3)); } //*************************************************************** private string readLine() { int i = 1; bool ite = true; while(ite == true) { i = i +1 ; bytes = clientSocket.Receive(buffer, buffer.Length , 0); mes += ASCII.GetString(buffer, 0, bytes); if(bytes <= buffer.Length) { ite = false ; break; } } Console.WriteLine ("Mes is " + mes); char[] seperator = {'\n'}; string[] mess = mes.Split(seperator); if(mess.Length > 2) { mes = mess[mess.Length-2]; ite = true ; }else { mes = mess[0]; ite = false; } if (ite == true) { if(!mes.Substring(3,1).Equals(" ")) { Console.WriteLine(" In return Line"); return readLine(); } } if(debug) { Console.WriteLine(" In return mess"); for(int k=0;k < mess.Length-1;k++) { Console.WriteLine(mess[k]); } } return mes; } //********************************************************************* public void cleanup() { if(clientSocket!=null) { Console.WriteLine("Closing the Socket "); clientSocket.Close(); clientSocket = null; } logined = false; } //************************************************************************** public void download(string fileName) { download(fileName,false); } //************************************************************************** public void download(string fileName,Boolean resume) { try { if(!logined) { login(); } setBinaryMode(false); long totalSize=0; //**** /* try{ totalSize = getFileSize(fileName); }catch(Exception) { throw new Exception("File Not Found "+fileName); } */ // Console.WriteLine("Downloading file "+fileName+" from "+remoteHost + "/"+remotePath); Console.WriteLine("Downloading file "+fileName+" from "+remoteHost + remotePath); if(!File.Exists(fileName)) { Stream st = File.Create(fileName); st.Close(); } FileStream output = new FileStream(fileName,FileMode.Open); Socket cSocket = createDataSocket(); long offset = 0; if(resume) { offset = output.Length; if(offset > 0 ) { sendCommand("REST "+offset); if(retValue != 350) { //throw new IOException(reply.Substring(4)); //Server may not support resuming. offset = 0; } } if(offset > 0) { if(debug) { Console.WriteLine("seeking to " + offset); } long npos = output.Seek(offset,SeekOrigin.Begin); Console.WriteLine("new pos="+npos); } } sendCommand("RETR " + fileName); if(!(retValue == 150 || retValue == 125)) { throw new IOException(reply.Substring(4)); } float iCnt = 0; float per = 0, oldPer = 1; while(true) { bytes = cSocket.Receive(buffer, buffer.Length, 0); output.Write(buffer,0,bytes); // Showing the progress. 1..50 iCnt += bytes; per = (int) ( (iCnt / totalSize) * 100 ); if( per != oldPer && per % 2 == 0 ) { Console.Write("."); oldPer = per; } if(bytes < buffer.Length) { break; } } output.Close(); cSocket.Close(); Console.WriteLine(""); readReply(); if( !(retValue == 226 || retValue == 250) ) { throw new IOException(reply.Substring(4)); } } catch(ArgumentOutOfRangeException e) { Console.WriteLine("No Message Received from the Host"); } } //********************************************************************* private Socket createDataSocket() { sendCommand("PASV"); if(retValue != 227) { Console.WriteLine(" Data Socket PROBLEM"); throw new IOException(reply.Substring(4)); } int index1 = reply.IndexOf('('); int index2 = reply.IndexOf(')'); string ipData = reply.Substring(index1+1,index2-index1-1); int[] parts = new int[6]; int len = ipData.Length; int partCount = 0; string buf=""; for (int i = 0; i < len && partCount <= 6; i++) { char ch = Char.Parse(ipData.Substring(i,1)); if (Char.IsDigit(ch)) buf+=ch; else if (ch != ',') { throw new IOException("Malformed PASV reply: " + reply); } if (ch == ',' || i+1 == len) { try { // 500 lines parts[partCount++] = Int32.Parse(buf); buf=""; } catch (Exception) { throw new IOException("Malformed PASV reply: " + reply); } } } /*Int64 ipAddress = parts[0] + "." parts[1] + "." + parts[2] + "." parts[3] ; */ string ipAddress = parts[0] + "." + parts[1]+ "." + parts[2] + "." + parts[3]; int port = (parts[4] << 8) + parts[5]; Console.WriteLine("ip address is {0}, port is {0}", ipAddress, port); Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPAddress ipa = IPAddress.Parse(ipAddress); IPEndPoint ep = new IPEndPoint(ipa, port); try { s.Connect(ep); } catch(Exception e) { s.Shutdown(SocketShutdown.Both); throw new IOException("Can't connect to remote server"); } return s; } //************************************************************************************** public void login() { try { clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //Int64 rh = Int64.Parse(remoteHost); IPAddress ipa = IPAddress.Parse(remoteHost); IPEndPoint ep = new IPEndPoint(ipa, remotePort); Console.WriteLine ( " I am in the Login method ") ; try { clientSocket.Connect(ep); } catch(Exception e) { throw new IOException("Couldn't connect to remote server"); } readReply(); if(retValue != 220) { Console.WriteLine(" Clsong ..."); close(); throw new IOException(reply.Substring(4)); } if(debug) Console.WriteLine("USER "+remoteUser); Console.WriteLine("Sending the user name {0}", remoteUser); do { sendCommand("USER "+remoteUser); } while(retValue==220); if( !(retValue == 331 || retValue == 230) ) { cleanup(); throw new IOException(reply.Substring(4)); } while( retValue == 220 ) { sendCommand("USER "+remoteUser); } if( retValue != 230 ) { if(debug) Console.WriteLine("PASS xxx"); sendCommand("PASS "+remotePass); if( !(retValue == 230 || retValue == 202) ) { cleanup(); throw new IOException(reply.Substring(4)); } } logined = true; Console.WriteLine("Connected to "+remoteHost); // chdir(remotePath); } catch(Exception e) { cleanup(); Console.WriteLine(" My exception thrown "); Console.WriteLine(e); } } } //************************************************************************ public class FTP4 { public FTP4 (string usrId , string pWd) { Console.WriteLine( " In the FTP4 program "); string uId, passW ; uId = usrId ; passW = pWd ; FTPFactory fc = new FTPFactory(); fc.setRemoteHost("205.246.169.2"); fc.setRemotePort(21); fc.setRemoteUser(uId); fc.setRemotePass(pWd); fc.login(); fc.upload("sql2.txt"); fc.cleanup(); } }