Thursday, October 21, 2010

Some Triggers in Oracle

This series explains simple Triggers in Oracle.
This trigger will add Passbook entries to a Table Passbook based on modifications done to an Accounts Table.
The Bank Table

----------------------------------------- -------- ----------------------------
ACCNO NOT NULL NUMBER(38) Primary Key
BALANCE NOT NULLNUMBER(38)



The Passbook Table
----------------------------------------- -------- ----------------------------
ACCNO NUMBER(38) Foreign Key references Bank/(AccNo)
TRANSACTIONTYPENOT NULL VARCHAR2(10)
BALANCEBEFORE NUMBER(38)
BALANCEAFTER NUMBER(38)
TRANSACTIONAMOUNT NUMBER(38)
DATEOFTRANSACTIONDATE 

The Trigger
 
create or replace Trigger BankUpdateTrigger 
before update on Bank 
for each row
begin
if(:new.Balance<1000) then
RAISE_APPLICATION_ERROR(-20100,`Minimum Balance Violated. Cannot be less than 1000 ` | :new.Balance);
end if;
if(:new.Balance<:old.Balance) then
insert into Passbook values(:old.AccNo,`Withdraw`,:old.Balanc
e,:new.Balance,:new.balance-:old.Balance,sysdate);
else
insert into Passbook values(:old.AccNo,`Deposit`,:old.Balance
,:new.Balance,:new.balance-:old.Balance,sysdate);
end if;
end;



Database Triggers

This article creates a logon Trigger which stores the logins record in a table called Logins Table.


The Trigger
create or  replace trigger logintrigger 
after logon on database
begin

insert into LoginsTable values(ora_login_user,sysdate);
end;

The Table

create table
LoginsTable(username varchar(30),logintime date)
Instead of Triggers
The table --- create table scientists(name varchar(50) primary key,subject varchar(50))
//*************************************

The View
create view vv as select name from scientists
//****************************************
The Trigger ---
create or replace Trigger ITrigger
instead of insert on vv
for each row
begin
insert into scientists values(:New.name,'Physics');
end;

//**********************************************
The Insert statement --- insert into vv values('Einstein');
//**********************************************
The select statement --- select * from scientists
//***********************************************
The Result ---
NAME    SUBJECT

Einstein    Physics

Encrypted File Transfer using .NET Remoting --- A complete C# Application.

This is an Application that implements an encrypted File Transfer using .NET Remoting.
  • This application contains 3 parts:-
    • The Interface Classes --- This is a Class Library that contains an interface. A reference to this is to be included both on the Client and the Server.
    • The Server which implements the interface from the above and maintains a list of available files.
    • The Client which contacts the Server to download a list of files, also has facilities for uploading and downloading.

The Interface --- FileTransferInterface.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace File_Transfer_Classes
{
    public interface  FileTransferInterface
    {
        long getFileLength(string filename);
        byte[] getBytes(string filename, long startposition, int noofbytes);
        string[] getFilesList();
        void startfileupload(string filename, long  filelength);
        void  Sendbytes(string filename, byte[] b);


    }
}





 



The Server --- FileTransferImplementation.cs, FileUploading.cs, frmServer.cs, GlobalData.cs, Program.cs
frmServer.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace File_Transfer_Server
{
    public partial class frmServer : Form
    {

        System.Runtime.Remoting.Channels.Tcp.TcpServerChannel ServerChannel = new System.Runtime.Remoting.Channels.Tcp.TcpServerChannel(7654);
       
        public frmServer()
        {
            InitializeComponent();
        }

        private void frmServer_Load(object sender, EventArgs e)
        {
            FileTransferImplementation.basefilepath = Application.StartupPath + "\\DownloadedFiles";
            if (!System.IO.Directory.Exists(FileTransferImplementation.basefilepath))
            {
                System.IO.Directory.CreateDirectory(FileTransferImplementation.basefilepath);
            }
             System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(ServerChannel, false);
            System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(typeof(FileTransferImplementation ), "GetFile", System.Runtime.Remoting.WellKnownObjectMode.SingleCall);
            timer1_Tick(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
             listBox1 .DataSource =   System.IO.Directory.GetFiles(FileTransferImplementation.basefilepath);
            }
            catch (Exception)
            {
            }
        }
    }
}




frmServer.Designer.cs



namespace File_Transfer_Server
{
    partial class frmServer
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.label1 = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // listBox1
            //
            this.listBox1.FormattingEnabled = true;
            this.listBox1.HorizontalScrollbar = true;
            this.listBox1.Location = new System.Drawing.Point(72, 100);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(669, 290);
            this.listBox1.TabIndex = 0;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(69, 61);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(72, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "uploaded files";
            //
            // timer1
            //
            this.timer1.Interval = 10000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(178, 463);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "Start";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // frmServer
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(790, 622);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.listBox1);
            this.Name = "frmServer";
            this.Text = "File Transfer Server";
            this.Load += new System.EventHandler(this.frmServer_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Button button1;
    }
}




FileTransferImplementation.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace File_Transfer_Server
{
   public  class FileTransferImplementation:MarshalByRefObject ,File_Transfer_Classes.FileTransferInterface
    {
      
       public static string basefilepath;

       public void Sendbytes(string filename, byte[] bytes)
       {
           FileUploading f;
           bool b = GlobalData.files.TryGetValue(filename,out f);
           if (!b)
               return;
           f.StoreBytes(bytes);
       }

       public string[] getFilesList()
       {
          string [] temp= System.IO.Directory.GetFiles(basefilepath);
          return temp;
       }
       public void startfileupload(string filename, long filelength)
       {
           GlobalData.files.Add(filename, new FileUploading(basefilepath + "\\" +  filename, filelength));
       }

       public byte[] getBytes(string filename, long startposition, int noofbytes)
       {
           BinaryReader bw = null;
           FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
           try
           {
               bw=new BinaryReader (fs);
               fs.Seek (startposition ,SeekOrigin.Begin );
             
               byte [] bytes=bw.ReadBytes (noofbytes );
               return bytes ;
           }
           catch (Exception ex)
           {
               System.Windows.Forms.MessageBox.Show(ex.Message);
               return null;
           }
           finally
           {
               if(bw!=null )
               {
                   fs.Dispose();
                   //bw.BaseStream.Dispose();
                   bw.Close ();

               }
           }
       }




       public long getFileLength(string filename)
       {
           FileStream fs = null;
           try
           {
               fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
               return fs.Length;
           }
           catch (Exception)
           {
               return -1;
           }

           finally
           {
               if (fs != null)
                   fs.Dispose();
           }
       }


    }
}
 

FileUploading.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace File_Transfer_Server
{
  public   class FileUploading
    {
      string filename;
      BinaryWriter bw;
      long downloadedsofar;
      long totalsize;

      public FileUploading(string filename, long totalsize)
      {
          this.filename = filename;
          this.totalsize = totalsize;
          this.downloadedsofar = 0;
          this.bw = new BinaryWriter(new FileStream ( filename,FileMode.OpenOrCreate, FileAccess.Write));
      }
      public override string ToString()
      {
          return "File Name = " + filename + " ,Total Size = " + totalsize + " ,Downloaded so far = " + downloadedsofar ;
      }
      public void StoreBytes(byte[] b)
      {
          bw.Write(b);
          downloadedsofar += b.Length;
          if (downloadedsofar >= totalsize)
          {
              bw.Flush();
              bw.Close();
          }
      }
    }
}



GlobalData.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections .Generic ;
namespace File_Transfer_Server
{
   public static  class GlobalData
    {
       public static Dictionary<string, FileUploading> files = new Dictionary<string, FileUploading>();
    }
}










Program.cs


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace File_Transfer_Server
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmServer());
        }
    }
}









The Client --- File Encrypter.cs, FileUploader.cs, frmFileEncrypterandDecrypter.cs, frmFileHandler.cs, frmMain.cs, GlobalData.cs, Program.cs.




File Encrypter.cs



using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace File_Transfer_Client
{
    class File_Encrypter
    {
        byte[] testHeader = null;//used to verify if decryption succeeded

        string testHeaderString = null;
        public File_Encrypter()
        {
            testHeader = System.Text.Encoding.ASCII.GetBytes("testing header");

            testHeaderString = BitConverter.ToString(testHeader);
        }
        public bool DecryptData(String inName, String outName, byte[] rijnKey, byte[] rijnIV)
        { 
            FileStream fin = null;
            FileStream fout = null;
            CryptoStream decStream = null;
            try
            {
                fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
                byte[] bin = new byte[bufLen];
                long rdlen = 0;
                long totlen = fin.Length;
                int len;
                RijndaelManaged rijn = new RijndaelManaged();
                decStream = new CryptoStream(fin, rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read);
                byte[] test = new byte[testHeader.Length];
                decStream.Read(test, 0, testHeader.Length);
                if (BitConverter.ToString(test) != testHeaderString)
                {
                   decStream.Clear();
                    decStream = null;
                    return false;
                }
                fout = new FileStream(outName, FileMode.Create, FileAccess.Write);
                while (true)
                {
                    len = decStream.Read(bin, 0, bufLen);
                    if (len == 0)
                        break;
                    fout.Write(bin, 0, len);
                    rdlen += len;
                }
                return true;
            }
            finally
            {
                if (decStream != null)
                    decStream.Close();
                if (fout != null)
                    fout.Close();
                if (fin != null)
                    fin.Close();
            }

        }

       const int bufLen = 4096;
        public void EncryptData(String inName, String outName, byte[] rijnKey, byte[] rijnIV)
        {
            FileStream fin = null;

            FileStream fout = null;

            CryptoStream encStream = null;

            try
            {
                fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
                fout = new FileStream(outName, FileMode.Create, FileAccess.Write);
                byte[] bin = new byte[bufLen];
                long rdlen = 0;
                long totlen = fin.Length;
                int len;
                RijndaelManaged rijn = new RijndaelManaged();
                encStream = new CryptoStream(fout, rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write);
                encStream.Write(testHeader, 0, testHeader.Length);
                while (true)
                {
                    len = fin.Read(bin, 0, bufLen);
                    if (len == 0)
                        break;

                    encStream.Write(bin, 0, len);

                    rdlen += len;


                }


            }

            finally
            {

                if (encStream != null)

                    encStream.Close();

                if (fout != null)

                    fout.Close();

                if (fin != null)

                    fin.Close();

            }

        }









        public void getKeysFromPassword(string pass, out byte[] rijnKey, out byte[] rijnIV)
        {

            byte[] salt = System.Text.Encoding.ASCII.GetBytes("System.Text.Encoding.ASCII.GetBytes");

            PasswordDeriveBytes pb = new PasswordDeriveBytes(pass, salt);

            rijnKey = pb.GetBytes(32);

            rijnIV = pb.GetBytes(16);

        }

    }
    public enum CryptoEventType
    {
        Message, FileProgress
    }
    public delegate void cryptoEventHandler(object sender, CryptoEventArgs e);

    //*************************

    public class CryptoEventArgs : EventArgs
    {

        CryptoEventType type;

        string message;

        int fileLength;

        int filePosition;

        public CryptoEventArgs(string message)
        {

            type = CryptoEventType.Message;

            this.message = message;

        }

        public CryptoEventArgs(string fileName, int fileLength, int filePosition)
        {

            type = CryptoEventType.FileProgress;

            this.fileLength = fileLength;

            this.filePosition = filePosition;

            message = fileName;

        }

        public CryptoEventType Type
        {

            get { return type; }

        }

        public string Message
        {

            get { return message; }

        }

        public string FileName
        {

            get { return message; }

        }

        public int FileLength
        {

            get { return fileLength; }

        }

        public int FilePosition
        {

            get { return filePosition; }

        }

    }
    //***************************
}










FileUploader.cs




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace File_Transfer_Client
{
    public partial class FileUploader : Form
    {
       // private File_Transfer_Classes.FileTransferInterface Server;
        public FileUploader()
        {
            InitializeComponent();
        }

        private void FileUploader_Load(object sender, EventArgs e)
        {
          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ofd.ShowDialog(this);
        }

        private void ofd_FileOk(object sender, CancelEventArgs e)
        {
            txtFileName.Text = ofd.FileName;
            t1.Text = txtFileName.Text.Substring(txtFileName.Text.LastIndexOf("\\")).Trim();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(txtFileName.Text, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            long totalfilesize = fs.Length;
            long uploadedsofar = 0;
            int noofbytes = 2000;
            GlobalData.Server.startfileupload(t1.Text, fs.Length);
            progressBar1.Minimum = 0;
            progressBar1.Maximum = (int)totalfilesize;
            while (uploadedsofar < totalfilesize)
            {
                Application.DoEvents();
                Application.DoEvents();
                Application.DoEvents();
                int currentsize = noofbytes;
                if (currentsize > (totalfilesize - uploadedsofar))
                
                    currentsize = (int)(totalfilesize - uploadedsofar);
                    fs.Seek(uploadedsofar, SeekOrigin.Begin);
                   byte [] bytes= br.ReadBytes(currentsize);
                   GlobalData.Server.Sendbytes(t1.Text, bytes);
                   uploadedsofar += currentsize;
                   progressBar1.Value =(int) uploadedsofar;
                   Application.DoEvents();
                   Application.DoEvents();
                   Application.DoEvents();
            }
            br.Close();
            fs.Dispose();

        }
    }
}





frmFileEncrypterandDecrypter.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
namespace File_Transfer_Client
{
    public partial class frmFileEncrypterandDecrypter : Form
    {
        string pwd;
        byte[] cryptoKey, cryptoIV;
        File_Encrypter  crm = new File_Encrypter ();
        public frmFileEncrypterandDecrypter()
        {
            InitializeComponent();
        }

        private void ofd_FileOk(object sender, CancelEventArgs e)
        {
            if (ofd.Tag.Equals("Original"))
                txtOriginalFile.Text = ofd.FileName;
            if (ofd.Tag.Equals("Encrypted"))
               txtEncryptedFile .Text  = ofd.FileName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ofd.Tag = "Original";
            ofd.ShowDialog(this);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sfd.Tag = "Encrypted";
            sfd.ShowDialog(this);
        }

        private void sfd_FileOk(object sender, CancelEventArgs e)
        {
 if (sfd.Tag.Equals("Encrypted"))
               txtEncryptedFile .Text  = sfd.FileName;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                getPassword();
                Encrypter(txtOriginalFile.Text, txtEncryptedFile.Text);
                MessageBox.Show(this, "File Encrypted");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }


        private void getPassword()
        {
            try
            {
                pwd = "hmstfnns";
                //get keys from password
                byte[] dk = null;
                byte[] div = null;
                crm.getKeysFromPassword(pwd, out dk, out div);
                cryptoKey = dk;
                cryptoIV = div;
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message);
                this.Close();
                return;
            }
        }




















        private void Encrypter(string filePath, string encName)
        {
            try
            {
                DateTime current = DateTime.Now;
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                byte[] keyToEncrypt;
                byte[] encryptedKey;
                string origName = filePath;
                //string encName = origName + ".enc";
                //txtFile2.Text = encName;
                try
                {
                    crm.EncryptData(origName, encName, cryptoKey, cryptoIV);
                    FileInfo fi = new FileInfo(origName);
                    FileInfo fi2 = new FileInfo(encName);
                    //remove readonly attribute
                    if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        fi.Attributes &= ~FileAttributes.ReadOnly;
                    }
                    //copy creation and modification time
                    fi2.CreationTime = fi.CreationTime;
                    fi2.LastWriteTime = fi.LastWriteTime;
                    fi2.Attributes = FileAttributes.Normal | FileAttributes.Archive;
                    byte[] data = File.ReadAllBytes(encName);
                 
                    File.Delete(encName);

                  
                    StreamWriter writer = new StreamWriter("PublicPrivateKey.xml");
                    string publicprivatexml = RSA.ToXmlString(true);
                    writer.Write(publicprivatexml);
                    writer.Close();
                 

                    keyToEncrypt = System.Text.ASCIIEncoding.Unicode.GetBytes(pwd);
                    encryptedKey = RSA.Encrypt(keyToEncrypt, false);
                    //using (BinaryWriter bw = new BinaryWriter(File.Create(current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc")))
                    using (BinaryWriter bw = new BinaryWriter(File.Create(encName )))
                    {
                       
                        bw.Seek(0, SeekOrigin.Begin);
                        bw.Write(data);
                        bw.Write(encryptedKey);
                        bw.Close();
                    }
                    MessageBox.Show("File Encrypted");
                }
                catch (CryptographicException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                catch (UnauthorizedAccessException ex)
                {
                
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Decryption(txtOutDecryptedFile.Text ,txtOutEncryptedFile.Text );
        }

        //********************************************


        private void Decryption(string filePath,string encName)
        {
            try
            {
              
                DateTime current = DateTime.Now;
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                byte[] alldata = File.ReadAllBytes(encName );
                byte[] getencryptedkey = new byte[128];
                byte[] data = new byte[alldata.Length - 128];
                for (int i = 0; i < alldata.Length - 128; i++)
                { data[i] = alldata[i]; }
                for (int i = alldata.Length - 128, j = 0; i < alldata.Length; i++, j++)
                { getencryptedkey[j] = alldata[i]; }
                using (BinaryWriter bw = new BinaryWriter(File.Create(encName)))
                {
                    bw.Write(data);
                    bw.Close();
                }
             
                StreamReader reader = new StreamReader("PublicPrivateKey.xml");
                string publicprivatekeyxml = reader.ReadToEnd();
                RSA.FromXmlString(publicprivatekeyxml);
                reader.Close();
                byte[] decryptedKey = RSA.Decrypt(getencryptedkey, false);
                pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey);
                byte[] dk = null;
                byte[] div = null;
                crm.getKeysFromPassword(pwd, out dk, out div);
                cryptoKey = dk;
                cryptoIV = div;
             
                string dncName = filePath;
               
                try
                {
                    if (crm.DecryptData(encName, dncName, cryptoKey, cryptoIV))
                    {
                        FileInfo fi = new FileInfo(encName);
                        FileInfo fi2 = new FileInfo(dncName);
                        if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        { fi.Attributes &= ~FileAttributes.ReadOnly; }
                       
                        fi2.CreationTime = fi.CreationTime;
                        fi2.LastWriteTime = fi.LastWriteTime;
                        MessageBox.Show("File Decrypted");
                    }
                    else
                    {
                        MessageBox.Show("The file can't be decrypted - probably wrong password");
                    }
                }

                catch (CryptographicException ex)
                { MessageBox.Show(ex.Message); }
                catch (IOException ex)
                { MessageBox.Show(ex.Message); }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            oofd.ShowDialog(this);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ssfd.ShowDialog(this);
        }

        private void oofd_FileOk(object sender, CancelEventArgs e)
        {
            txtOutEncryptedFile.Text = oofd.FileName;
        }

        private void ssfd_FileOk(object sender, CancelEventArgs e)
        {
            txtOutDecryptedFile.Text = ssfd.FileName;
        }

    }
}

frmFileHandler.cs


 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace File_Transfer_Client
{
    public partial class frmFileHandler : Form
    {
      
     
        public frmFileHandler()
        {
            InitializeComponent();
        }

        private void frmFileHandler_Load(object sender, EventArgs e)
        {
        
        }

      

        private void button1_Click(object sender, EventArgs e)
        {
            string[] files =GlobalData.Server.getFilesList();
            lstfiles.Items.Clear();
            foreach (string file in files)
                lstfiles.Items.Add(file);
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void GetFileLength(object sender, EventArgs e)
        {
            if (lstfiles.SelectedIndex < 0)
                return;
            txtFileLength.Text ="" + GlobalData.Server.getFileLength(lstfiles.Text);
        }

        private void btBrowse_Click(object sender, EventArgs e)
        {
            sfd.ShowDialog(this);
        }

        private void sfd_FileOk(object sender, CancelEventArgs e)
        {
            txtoutputfile.Text = sfd.FileName;
        }

        private void btStartDownLoad_Click(object sender, EventArgs e)
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = Convert.ToInt32(txtFileLength.Text);
            int noofbytes = 2000;
            BinaryWriter bw = null;
            long downloaded = 0;
            long bytestodownload = Convert.ToInt64(txtFileLength.Text);
            try
            {
                bw = new BinaryWriter(new FileStream(txtoutputfile.Text, FileMode.OpenOrCreate, FileAccess.Write));
                while (downloaded < bytestodownload)
                {
                    Application.DoEvents();
                    Application.DoEvents();
                    Application.DoEvents();
                    int currentsize=noofbytes ;
                    if(currentsize  >(bytestodownload -downloaded ))
                        currentsize  =(int)(bytestodownload  -downloaded) ;
                    byte[] b = GlobalData.Server.getBytes(lstfiles.Text, downloaded, currentsize);
                    bw.Write(b);
                    downloaded += currentsize;
                    progressBar1.Value =(int) downloaded;
                    Application.DoEvents();
                    Application.DoEvents();
                    Application.DoEvents();
                }
                MessageBox.Show(this, "File Downloaded");



            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
            finally
            {
                if (bw != null)
                {
                    bw.Flush();
                    bw.Close();
                }
            }
         
        }
    }
}


frmMain.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace File_Transfer_Client
{
    public partial class frmMain : Form
    {
      
        public frmMain()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GlobalData.ServerName = txtServerName.Text;
            new frmFileEncrypterandDecrypter().ShowDialog(this);
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GlobalData.ServerName = txtServerName.Text;
            new frmFileHandler().ShowDialog(this);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GlobalData.ServerName = txtServerName.Text;
            new FileUploader().ShowDialog(this);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                GlobalData.ServerName = txtServerName.Text;
                try
                {
                    System.Runtime.Remoting.Channels.Tcp.TcpClientChannel ClientChannel = new System.Runtime.Remoting.Channels.Tcp.TcpClientChannel();
                    System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(ClientChannel, false);
                }
                catch (Exception)
                {
                }
             GlobalData .Server= (File_Transfer_Classes.FileTransferInterface)Activator.GetObject(typeof(File_Transfer_Classes.FileTransferInterface), "tcp://" + GlobalData.ServerName + ":7654/GetFile");
             button1.Enabled = true;
             button2.Enabled = true;
             button3.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }
    }
}





GlobalData.cs


using System;
using System.Collections.Generic;
using System.Text;

namespace File_Transfer_Client
{
   public static  class GlobalData
    {
       public static string ServerName;
       public static File_Transfer_Classes.FileTransferInterface Server;
    }
}



Program.cs


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace File_Transfer_Client
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain ());
        }
    }
}








Tuesday, October 19, 2010

A Java Beans Example that uses JDBC

/*
* BookWorldBean.java
*
* Created on November 7, 2007, 10:13 AM
*/
package BookWorldPackage;
import java.beans.*;
import java.io.Serializable;
/**
* @author Champak Roy
*/
public class BookWorldBean extends Object implements Serializable {

private java.sql.Connection con;

public void openConnection() throws Exception
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=java.sql.DriverManager.getConnection("jdbc:odbc:BookWorld","Uname", "Pass");
}
catch(Exception ex)
{
throw ex;
}
}

private int getNoOfResults(java.sql.PreparedStatement ps)
{java.sql.ResultSet rs=null;
int count=0;
try
{
rs =ps.executeQuery();
while(rs.next())
count+=1;
rs.close();
return(count);
}
catch(Exception ex)
{
return(0);
}

}
//********************Get books by BookName********************
public String getBooksByBook(String BookName)
{
try
{
BookName=BookName.replaceAll("`", "`");
BookName ="`%" + BookName+ "%`";
//******************************BookName Formatting***************************

java.sql.PreparedStatement ps=con.prepareStatement("select * from books where Bookname like " + BookName);

String s="<table width=100% border=2 bgcolor=yellow><tr><td><font color=blue>Serial No</font></td><td><font color=blue>Book Name</td></font><td><fontcolor=blue>Book Price</td></font><td><font color=blue>Book Contents</td></font><td><font color=blue>Orders</font> </td></tr>";
java.sql.ResultSet rs=ps.executeQuery();
int count=0;
while(rs.next())
{
count+=1;
s=s + "<tr bgcolor=green><td>" + count + "</td><td>" + rs.getString("BookName") + "</td><td>" + rs.getInt("BookPrice") + "</td><td>" + rs.getString("BookContents") + "</td><TD><a href=Orders.jsp?BookNo=" + rs.getInt("BookNo") + ">Order thisBook</a></td></tr>";
}
s=s + "</table>";
return(s);

}
//*********************************BookName Formatting***************************





catch(Exception ex)
{

String s="No Book found";
return(s);
}
}
//********************Get books by BookName********************




//********************Get books by SubjectName********************
public String getBooksBySubject(String SubjectName)
{
try
{
SubjectName=SubjectName.replaceAll("`", "`");
SubjectName ="`%" + SubjectName + "%`";
//******************************SubjectName Formatting***************************

java.sql.PreparedStatement ps=con.prepareStatement("select books.*,SubjectName from Books_Subjects,books where SubjectName like " + SubjectName + " and books.bookname=Books_Subjects.bookname");

String s="<table width=100% border=2 bgcolor=yellow><tr><td><font color=blue>Serial No</font></td><td><font color=blue>Book Name</td></font><td><font color=blue>Book Price</td></font><td><font color=blue>Book Contents</td></font><td><font color=blue>SubjectName</td></font></td><td>Orders </td></tr>";
java.sql.ResultSet rs=ps.executeQuery();
int count=0;
while(rs.next())
{
String BookName=rs.getString("BookName");
int BookPrice=rs.getInt("BookPrice");
String BookContents=rs.getString("BookContents");

int BookNo=rs.getInt("BookNo");
SubjectName=rs.getString("SubjectName");
count+=1;
s=s + "<tr bgcolor=green><td>" + count + "</td><td>" + BookName + "</td><td>" + BookPrice + "</td><td>" + BookContents + "</td><td>" + SubjectName + "</td><TD><a href=Orders.jsp?BookNo=" + BookNo + ">Order this Book</a></td></tr>";
}
s=s + "</table>";
return(s);

}
//*********************************SubjectName Formatting***************************






catch(Exception ex)
{

String s="No Book found" + ex;
return(s);
}
}
//********************Get books by SubjectName********************






//*********************Get book by AuthorName******************
publicString getBooksByAuthor(String AuthorName)
{
try
{
AuthorName=AuthorName.replaceAll("`", "`");
AuthorName ="`%" + AuthorName + "%`";
//**********************************************AuthorName Formatting***************************

java.sql.PreparedStatement ps=con.prepareStatement("select books.*,AuthorName from Books_Authors,books where Authorname like " + AuthorName + " and books.bookname=books_authors.bookname");

String s="<table width=100% border=2 bgcolor=yellow><tr><td><font color=blue>Serial No</font></td><td><font color=blue>Book Name</td></font><td><font color=blue>Book Price</td></font><td><font color=blue>Book Contents</td></font><td><font color=blue>AuthorName</td></font></td><td>Orders </td></tr>";
java.sql.ResultSet rs=ps.executeQuery();
int count=0;
while(rs.next())
{

String BookName=rs.getString("BookName");
int BookPrice=rs.getInt("BookPrice");
String BookContents=rs.getString("BookContents");

int BookNo=rs.getInt("BookNo");
AuthorName=rs.getString("AuthorName");


count+=1;
s=s + "<tr bgcolor=green><td>" + count + "</td><td>" + BookName + "</td><td>" + BookPrice + "</td><td>" + BookContents + "</td><td>" + AuthorName + "</td><TD><a href=Orders.jsp?BookNo=" + BookNo + ">Order this Book</a></td></tr>";
}

s=s + "</table>";
return(s);


//*********************************AuthorName Formatting***************************



}

catch(Exception ex)
{

String s="No Book found";
return(s);
}
}

//***********************************************************************************************
public String getBooksByBookNo(int BookNo)
{
try
{

//**********************************************AuthorName Formatting***************************

java.sql.PreparedStatement ps=con.prepareStatement("select BookName from Books where BookNo=?");
ps.setInt(1, BookNo) ;

java.sql.ResultSet rs=ps.executeQuery();

if(rs.next())
{

String BookName=rs.getString("BookName");
return(BookName);
}


return("Invalid Book");


//*********************************AuthorName Formatting***************************



}

catch(Exception ex)
{

String s="No Book found";
return(s);
}
}

//********************************************************************************************

//*********************Get book by AuthorName******************




//*********************Get book by ISBN no************************
public String getBooksByISBN(String ISBN)
{
try
{
ISBN=ISBN.replaceAll("`", "`");
ISBN ="`%" + ISBN + "%`";
//**************************************ISBN Formatting***************************

java.sql.PreparedStatement ps=con.prepareStatement("select * from Books where BookISBN like" + ISBN);

String s="<table width=100% border=2 bgcolor=yellow><tr><td><font color=blue>Serial No</font></td><td><font color=blue>Book Name</td></font><td><font color=blue>Book Price</td></font><td><font color=blue>Book Contents</td></font><td><font color=blue>ISBN</font></td><td>Orders </td></tr>";
java.sql.ResultSet rs=ps.executeQuery();
int count=0;
while(rs.next())
{
count+=1;
String BookName=rs.getString("BookName");
s=s + "<tr bgcolor=green><td>" + count + "</td><td>" + BookName + "</td><td>" + rs.getInt("BookPrice") + "</td><td>" + rs.getString("BookContents") + "</td><td>" + rs.getString("BookISBN") + "</td><TD><a href=Orders.jsp?BookNo=" + rs.getInt("BookNo") + ">Order this Book</a></td></tr>";
}
s=s + "</table>";
return(s);
}
//**************************************ISBN Formatting***************************
catch(Exception ex)
{

String s="No Book found" + ex;
return(s);
}
}


}
//*********************Get book by ISBN no************************