Thursday 17 December 2015

Creating your own http server using python script.


This lesson is about creating your own web server without using apache. To do this we are using two libraries.
BaseHTTPServer and SimpleHTTPServer.  BaseHTTPServer creates the http daemon and SimpleHTTPServer
creates the http handler. The program takes one argument which is the port number to which server will be running.
If no port number is mentioned server will run on port 8000.







So here is the code for your Web Server.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

Handler = SimpleHTTPRequestHandler
Server = BaseHTTPServer.HTTPServer

Protocol = "HTTP/1.1"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000

server_address = ("127.0.0.1", port)
# if you are opt to use this on your local machine 127.0.0.1, but you want to use it as web server in a network
# with various sub net then use 0.0.0.0 instead.

Handler.protocol_version = Protocol
httpd = Server(server_address, Handler)
print("HTTP Server started...")
httpd.serve_forever()

After saving this files (i.e. PythonWebServer.py), goto the command line and type
python PythonWebServer.py 8000 (8000 port number is optional.)

The directory where you executed PythonWebServer.py is the root directory of your web server.
Create a html file on the root, named say firstPage.html

Now open your browser and type localhost:8000/firstPage.html
And your html page will be parsed and displayed.

This type of web server can be used on your local desktop or small home network.

Sunday 13 December 2015

Executing python script from Web Browser without using Apache.


 In one of our last blog we have demonstrated that how to execute python script on web browser using Apache Web
Server. In this tutorial we will you how to execute python script in browser without using apache web server.. Python has one of it's own library CGIHTTPServer.py which creates a web server capable of performing as web server. For creating this web server all you need is python application version 2.7. 
Download link of python 2.7
1. For 32bit version 
2. For 64 bit version.

After downloading and installing, goto the python root directory.(i.e. c:\python27)
You have to run this command here.

C:\Python27>python -m CGIHTTPServer 

When you run this command it will start the server at default port 8000.
If you want to run it in a different port just add a port number after the command given above

C:\Python27>python -m CGIHTTPServer 9000

Now check whether you have a folder named cgi-bin on the python root directory.If not create one
using md or mkdir cgi-bin and changed to cgi-bin directory.
Put all your executable python script on this folder.

Now go to the browser and type localhost:9000/cgi-bin/sample.py

Though the server will run by typing localhost:9000 but python code will  only parsed by browser when executing script from cgi-bin folder.

Example sample.py
#D!\Python27\python

print "Content-type: text/html\n"


print "<html><head><title>Hello CGI</title></head>"

print "<body><h2>Hello from CGIHTTPServer<h2>r</body></html>"

Executing this script will show

Hello from CGIHTTPServer

Tuesday 8 December 2015

Server Client socket programming in Java

This tutorial is made with a purpose of understanding the basic concepts of socket programming with Java. For socket programming you need a package java.net which is within J2SE API's, which consists of classes and interface for low level communications. java.net supports communication with 2 types of protocols,
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). In this tutorial we are dealing with to application, one Server and another Client. When the Server program starts it listens for client request on the host address given and on a given port number. Ports already in use cannot be used, server is also set to a timeout after 10 seconds. Then the client program which whenever connects to the server, server accepts connection and sends a reply to the client.

1. SocketServer.java.

/*Import these 2 packages, first one is for socket programming and the second one is for input output streaming. */
import java.net.*;
import java.io.*;

public class SocketServer extends Thread
{
   private ServerSocket serverSocket;

   public SocketServer(int port) throws IOException
   {
     
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);    
    }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "....");
                Socket server = serverSocket.accept();
                System.out.println("Connected to " + server.getRemoteSocketAddress());
                DataInputStream in  = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thanks for connecting to " + server.getLocalSocketAddress());
                server.close();          
            }
            catch(SocketTimeoutException s)
            {
                System.out.println("\nSocket time out..");
                break;
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
                break;
            }
        }
    }

    public static void main(String[] args)
    {
        int port = Integer.parseInt(args[0]);
        try
        {
            Thread t = new SocketServer(port);
            t.start();          
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

2. SocketClient.java

import java.net.*;
import java.io.*;

public class SocketClient
{
    public static void main(String[] args)
    {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try
        {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, port);
            //client.connect();
            System.out.println("Connected to " + client.getRemoteSocketAddress());
            OutputStream outServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outServer);
            out.writeUTF("\nHello from " + client.getLocalSocketAddress());
            InputStream inServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inServer);
            System.out.println("Server says..." + in.readUTF());
            client.close();           
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Tuesday 24 November 2015

How to enable python code execute in browser using Wamp.


This becomes a head scratching job and bit confusing too to configure web server to execute Python code. It's not rocket science but seems we get confused on googling and getting different  suggestions. So we will provide here the perfect configuration to execute .py files in browser. 
First of all open httpd.conf file from the \wamp\bin\apache\apachex.x.x\conf\ directory of your wamp directory. Search for the line <Directory "c:/wamp/www/"> (assuming that wamp is installed in C drive and your root directory is c:\wamp\www, you may also use any other root directory). 

Uncomment these line if commented.

LoadModule cgi_module modules/mod_cgi.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

Add this line if not exists.

Options +ExecCGI, if you are not sure what else to add, because by default all options are added if you do not mention them and adding any options restrict it to added options, unless you add one + sign before the option.

If "Options" line exists uncomment it if commented. 

Add ExecCGI at the end.

Options Indexes FollowSymLinks ExecCGI.

Also add this line if does not exists 

AddHandler cgi-script .cgi .py

Now put you python script in the root folder or some sub directory of root folder.

Do not forget to add this line at the begining of the script.

#!c:\pythonPath (i.e. #!c:\python34\python)

If you do not add this line script will not execute as browser will not know where is the python program to compile your script.

Now say your wamp base url is http://localhost:8090/ and your python script is in root directory. c:\wamp\www, then type http://localhost:8090/programName.py

Here is a sample program. This program will connect to the wamp server and display the welcome page.

#!D:/Python34/python

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server = 'localhost'

port = 8090

request = "GET / HTTP/1.1\r\nHost:" + server + ":" + str(port) + "\r\n\r\n"

s.connect((server, port))

s.send(request.encode('UTF-8'))

print("Content-Type: text/html\n\n")

result = "."

while len(result)>0:
    result = s.recv(4096)
    chunk = result.decode('UTF-8')
    print(chunk)

 #python #pythonprogramming #wamp #pythonscript

Wednesday 28 October 2015

Python dictionary



In  python dictionary Values each key is separated from it's values by a colon {:},
each items in dictionary is separated by commas, and all items are enclosed in braces {}.
Keys of a dictionary should be unique. No duplicate. Values can be of any type but keys
should be immutable.




#!/usr/bin/python

dic = {'Code': '001', 'Name': 'Alex', 'Age': 27}
dic1 = {'Code': '001', 'Name': 'Peter', 'Age': 21}


print "dic['Code']: ", dic['Code'] # prints dic['Code']: 001
print "dic['Name']: ", dic['Name'] # prints dic['Name']: Alex
print "dic['Age']: ", dic['Age']   # prints dic['Age']: 27

#example functions and methods used with python dictionary

#compare function compares 2 dictionaries
# cmp returns 1 on mismatch and 0 on match
if cmp(dic,dic1)==1:
  print "Both dictionaries are not equal"
else:
  print "Both dictionaries are equal"

# len function prints the length of dictionaries

print "Length of dic : ",len(dic)

# Removing entry with key 'Code'
del dic['Code']

# Deleting all entries in dic
dic.clear()

# Deleting entire dictionary
del dic

# fromkeys copy keys to another dictionary.
# It has 2 parameters
# 1. seq - the list of values used for the key preparation
# 2. value - optional, if provided then entire element values will be set to this value

dic2 = dic1.fromkeys(dic1,10)

print "dic2['Code']: ", dic2.get('Code') # prints dic2['Code']: 002

# has_keys returns true if the  key exists in the dictionary

if dic1.has_keys('Name'):
 print "The kay name exits'


# keys() Returns list of dictionary keys.

print dic1.keys()

Thursday 8 October 2015

Download Microsoft Visual Studio 2015 Torrent Download.

Visual Studio 2015 Enterprise ISO - Core-X

Torrent Download Link

Magnet Link

Hash : 845B06793CAC0A6B6AF535694467BDCA04ABDF37

Using ngView in AngularJS to create multiple page view.

AngularJS is one of the leading JavaScript framework which is doing something simply awesome. Whenever we talk about ngView we have to think about routeConfig which is actually making multiple page views possible. So with routeConfig we can embed a whole website into a single webpage. In this example we have not used multiple html page but rather used template to embed html document object into div block using ngView. So you can try this code to embed as many template you like based on the key parameter you provide on your url. Route Config use a angular function config which embed html block provided in the template with .when and if any of the parameter key does not match then goes to .otherwise where it automatically redirects it to a error page which displays an error message. Template of error key is also defined in .when.

<html ng-app="app">
<head>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script>
app = angular.module('app',['ngRoute']);
app.controller('MyCtrl',function($scope) {
});
app.config(function($routeProvider) {
  $routeProvider
  .when('/', {
     template: '<h2>You are at the Welcome page</h2>',
     controller: 'MyCtrl' }
  )
  .when('/Documents',{
     template: '<h2>Read online tutorials</h2>',
     controller: 'MyCtrl' }
  )
  .when('/Downloads',{
     template: '<h2>Download utility software</h2>',
     controller: 'MyCtrl' }
  )
  .when('/error',{
     template : '<h2>Oops you have entered a wrong url',
     controller: 'MyCtrl' }
  )
  .otherwise( {
     redirectTo: '/error'
      }
  );
});
</script>
</head>
<body ng-controller="MyCtrl">
<div ng-view></div>
</body>
</html>

Installing Apache Tomcat on MAC OSx


Apache Tomcat is one of the most used web server.
Installing Apache Tomcat on MAC is as simple at it can be.
All you need is to download it from Apache Website.
Here we are downloading Apache Tomcat 8.0 version link to 
the tar.gz is provided here.









http://www.us.apache.org/dist/tomcat/tomcat-8/v8.0.27/bin/apache-tomcat-8.0.27.tar.gz
download this and extract it. The best place to extract is /opt/.

Create a directory called Tomcat8.0 on /opt/ and extract it there. You are all ready.

To start the service manually navigate to this directory. /opt/Tomcat8.0/bin/startup.sh
and to shutdown manually /opt/Tomcat8.0/bin/shutdown.sh

To configure Tomcat to automatically start service at boot, configure launchd_wrapper.sh
or org.apache.tomcat.plist. Here is the github link for configuration of both the script.
https://gist.github.com/mystix/661713.

Remember the default port is 8080. You can change server.xml to change port number for 
both normal and SSL (https) connection. BY default for http it is 8080 and for https it 
is 8443.

Installing skype on Mac OSx Mavericks



Installing Skype in MAC OS x Mavericks.
Skype is perhaps one of the best VOIP interface
used by millions of people around the globe. Easy to
use, easily importable contact lists from facebook or
google. Making voice / video calls from Skype to skype,
from skype to phone which is actually cost you. Send
message or attach files
.



We will be installing skype in MAC OSX Mavericks.
First thing you need to do is to download disk image
from official skype website.

Here is the link to download skype for MAC OSx
http://www.skype.com/en/download-skype/skype-for-mac/downloading/


After download is complete file name will be something like this
Skype_MajorVersion.MinorVersion.MinorVersion.SubVersion.dmg
(i.e. Skype_7.13.428.dmg)
Open the file from the download location and you will find 2
icons shows side by side. One is the skype installer to be installed and another is the Application icon. Hold down and drag the skype icon
to the application icon and your installation starts. After installation completes go to the application folder and drag the skype program icon to the launcher toolbar.

Skype is ready to use.


Thursday 1 October 2015

Universal Oracle data exporter using Visual Basic.





 As soon as you click on connect the to section Export Tables  is enabled. If you select Sql from Export data for combo then right section will be enabled for custom sql. If you select Tables then list of tables for the user schema will be populated on the Combo. You can either select a single table or if you do not select any table then all tables will be exported when you click on Export, but if you select one table then that particular table will be exported.


This is the interface from where data will be exported. The project is uploaded in google drive and code is provided in tis article.

Download the Code from -  Google Drive

Option Explicit
Private con As Object
Private rs As Object
Private rs1 As Object
Private table_name As String, fieldName As String, _
recordString As String, fieldValue As String
Private Sub cmdExportType_Click()
    If cmdExportType.Text = "Tables" Then
        customExportFrame.Enabled = False
        If cmbTableList.ListCount = 0 Then
            Call populateListofTables
        End If
        cmbTableList.Enabled = True
    Else
        customExportFrame.Enabled = True
        cmbTableList.Enabled = False
    End If
End Sub

Private Sub Command1_Click()
    If cmdExportType.Text = "Tables" Then
        Call getListofTablesAndData
    Else
        Call GetSqlData
    End If
End Sub

Private Sub cmdConnect_Click()
    Call OpenConnection(txtUser.Text, txtPasswd.Text, txtHostName.Text)
    tableListFrame.Enabled = True
End Sub

Private Sub Form_Load()
    cmdExportType.Clear
    cmdExportType.AddItem "Tables"
    cmdExportType.AddItem "Sql"
    tableListFrame.Enabled = False
    customExportFrame.Enabled = False
End Sub

Private Sub populateListofTables()
    Set rs1 = CreateObject("ADODB.Recordset")
    rs1.Open "select table_name from cat where table_type = 'TABLE' order by table_name", con
    cmbTableList.Clear
    While Not rs1.EOF
        cmbTableList.AddItem VBA.IIf(IsNull(rs1(0)), "", rs1(0))
        rs1.MoveNext
        DoEvents
    Wend
    rs1.Close
    Set rs1 = Nothing
End Sub

Private Sub getListofTablesAndData()
   Call GenerateTableData(cmbTableList.Text)
End Sub

Private Sub GetSqlData()
    Dim SqlStr As String, fieldString As String
    Dim rs1 As Object
    Dim i As Integer
    SqlStr = txtSql.Text
    Set rs1 = CreateObject("ADODB.RecordSet")
    rs1.Open SqlStr, con, 2
    Open App.Path & "\csv_data\" & tblName.Text & ".csv" For Output As #1
    fieldString = ""
    For i = 0 To rs1.Fields.Count - 1
        fieldString = fieldString & rs1(i).Name & ","
        DoEvents
    Next i
    fieldString = VBA.Left(fieldString, VBA.Len(fieldString) - 1)
    Print #1, fieldString
    recordString = ""
    PBRecords.Value = 0
    If rs1.RecordCount > 0 Then
        PBRecords.Max = rs1.RecordCount
        While Not rs1.EOF
            recordString = ""
            For i = 0 To rs1.Fields.Count - 1
                fieldValue = VBA.IIf(IsNull(rs1(i)), "", rs1(i))
                fieldValue = VBA.Replace(fieldValue, ",", " ")
                recordString = recordString & fieldValue & ","
                DoEvents
            Next i
            recordString = VBA.Left$(recordString, VBA.Len(recordString) - 1)
            Print #1, recordString
            DoEvents
            rs1.MoveNext
            PBRecords.Value = PBRecords.Value + 1
            lblRecords.Caption = Round((PBRecords.Value / PBRecords.Max) * 100, 2) & "%"
        Wend
    End If
    Close #1
    rs1.Close
End Sub

Private Sub OpenConnection(user As String, pass As String, serviceName As String)
   On Error GoTo OpenConnection_Error

    If con Is Nothing Then
        Set con = CreateObject("ADODB.Connection")
        con.CursorLocation = adUseClient
        con.ConnectionString = "Provider=MSDAORA.1;User ID=" & user & ";Password=" & pass & ";Data Source=" & serviceName & ";Persist Security Info=False"
        con.Open
    End If

   On Error GoTo 0
   Exit Sub

OpenConnection_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure OpenConnection of Form Form1"
End Sub

Private Sub OpenConnections(userName As String, passwd As String, dataSource As String)
    If con Is Nothing Then
        Set con = CreateObject("ADODB.Connection")
        con.CursorLocation = adUseClient
        con.ConnectionString = "Provider=MSDAORA.1;User ID=" & userName & ";Password=" & passwd & _
        ";Data Source=" & dataSource & ";Persist Security Info=False"
        con.Open
    End If
End Sub


Private Sub GenerateTableData(Optional singleTable As String)
    Dim i As Integer
    If rs Is Nothing Then
        Set rs = CreateObject("ADODB.Recordset")
        Set rs1 = CreateObject("ADODB.Recordset")
        rs.Open "select * from cat where table_type = 'TABLE'" & VBA.IIf(singleTable <> "", _
        " and table_name = '" & singleTable & "'", ""), con
        PBTables.Value = 0
        PBTables.Max = rs.RecordCount
        While Not rs.EOF
           
            table_name = VBA.IIf(IsNull(rs(0)), "", rs(0))
            Form1.Caption = "Exporting data for " & table_name & " table "
            If VBA.Trim$(table_name) <> "" Then
                Open App.Path & "\csv_data\" & table_name & ".csv" For Output As #1
                rs1.Open "select * from " & table_name, con, 1
                fieldName = ""
                For i = 0 To rs1.Fields.Count - 1
                    fieldName = fieldName & rs1(i).Name & ","
                    DoEvents
                Next i
                fieldName = VBA.Left$(fieldName, VBA.Len(fieldName) - 1)
                Print #1, fieldName
                PBRecords.Value = 0
                If rs1.RecordCount > 0 Then
                    PBRecords.Max = rs1.RecordCount
                    While Not rs1.EOF
                        recordString = ""
                        For i = 0 To rs1.Fields.Count - 1
               '             On Error Resume Next
                            fieldValue = getValue(rs1, i, table_name, PBTables.Value + 1)
                            fieldValue = VBA.Replace(fieldValue, ",", " ")
                            recordString = recordString & fieldValue & ","
                            DoEvents
                        Next i
                        recordString = VBA.Left$(recordString, VBA.Len(recordString) - 1)
                        Print #1, recordString
                        DoEvents
                        rs1.MoveNext
                        PBRecords.Value = PBRecords.Value + 1
                        lblRecords.Caption = Round((PBRecords.Value / PBRecords.Max) * 100, 2) & "%"
                        lblRecords.Refresh
                    Wend
                    PBTables.Value = PBTables.Value + 1
                    lblTables.Caption = Round((PBTables.Value / PBTables.Max) * 100, 2) & "%"
                    lblTables.Refresh
                End If
                Close #1
                rs1.Close
            End If
            DoEvents
            rs.MoveNext
        Wend
        Set rs = Nothing
        Set rs1 = Nothing
    End If
End Sub

Private Function getValue(r As Object, ByVal idx As Long, ByVal tbl_name As String, recNo As Long) As String
    On Error GoTo Err1
    getValue = VBA.IIf(IsNull(r(idx).Value), "", r(idx).Value)
    Exit Function
Err1:
    Open App.Path & "\errLog.log" For Append As #2
    Print #2, "Error on " & tbl_name & " table on column " & VBA.IIf(IsNull(r(idx).Name), "", r(idx).Name) & ", index " & idx & " on record number " & recNo & " whose column " & VBA.IIf(IsNull(r(0).Name), "", r(0).Name) & " value is " & VBA.IIf(IsNull(r(0).Value), "", r(0).Value)
    Close #2
End Function

Private Sub GetLatLongData()
    Call OpenConnections("bckv", "bckv", "ORCL")
    Open App.Path & "\lat_long.csv" For Input As #1
    Dim newLine As String
    Dim var
    Line Input #1, newLine
    While Not EOF(1)
        Line Input #1, newLine
        var = VBA.Split(newLine, ",")
        Call con.Execute("insert into citieslatlong (City,ProvinceState,Country,Latitude,Longitude) " & _
        "values('" & VBA.Replace(var(0), "'", "''") & "','" & VBA.Replace(var(1), "'", "''") & "','" & VBA.Replace(var(2), "'", "''") & "','" & VBA.Replace(var(3), "'", "''") & "','" & VBA.Replace(var(4), "'", "''") & "')")
    Wend
    Close #1
End Sub

Private Sub txtHostName_Change()
    cmdConnect.Enabled = (txtUser.Text <> "" And txtPasswd.Text <> "" And txtHostName.Text <> "")
End Sub

Private Sub txtPasswd_Change()
    cmdConnect.Enabled = (txtUser.Text <> "" And txtPasswd.Text <> "" And txtHostName.Text <> "")
End Sub

Private Sub txtUser_Change()
    cmdConnect.Enabled = (txtUser.Text <> "" And txtPasswd.Text <> "" And txtHostName.Text <> "")
End Sub

Wednesday 30 September 2015

Universal MySql Data exporter in Visual Basic.

http://www.hybridmindset.com/images/mysql_logo_small.jpg Microsoft provides a wonderfull tool called ActiveX Data Object which
is able to connect to any type of database through connection string.
All you need is proper driver for connectivity.
When we started developing this application we though to make it absolute
dynamic. That means you only provide database url, user name and password.
And when you connect you get all the schemas within the database. You select
any of the schema and click export, you are done. All the tables within the
schema will be exported in csv format to a folder located at the root of the
application. I am providing you the code. To make it simple I have put everything
within one form.




This the the form where you need to provide the ipaddress or url for MySql database server.
Then provide User Name, Password and click on connect. Combobox will be enabled and all 
the shcemas will be populated into the combobox. Select your schema and click on export. 
A folder will be created in the root of you application path and all tables will be exported as 
CSV files.




The code is given below.
MySql ODBC driver 3.51 is required to connect to MySql database with this application.
If you haven't installed mysql odbc driver get it from here .
https://dev.mysql.com/downloads/connector/odbc/3.51.html

   Also download the source code  from Google Drive.

'------------------------------------------------------------------------------------------------------------
Option Explicit
Dim con As Object
Dim rs As Object, rs1 As Object
Private Sub ExportData()
    Dim i As Integer
    Dim table_name As String
    Dim fld As String, rec As String
    Dim cnt As Double, totcnt As Double
    i = 0
    Command1.Enabled = False
    cnt = 0
    Set rs = VBA.CreateObject("ADODB.Recordset")
    Set rs1 = VBA.CreateObject("ADODB.Recordset")
    If con.state = 1 Then con.Close
    con.ConnectionString = "driver={MySQL ODBC 3.51 Driver};server=" & txtHostName.Text & ";" & _
    "database=" & cmbDB.Text & ";Uid=" & txtUser.Text & ";Pwd=" & txtPasswd.Text & ";OPTION=3;"
    con.Open
    rs.Open "select count(distinct table_name) from information_schema.tables where table_schema = '" & cmbDB.Text & "'", con
    totcnt = VBA.IIf(IsNull(rs(0)), 1, rs(0))
    rs.Close
    rs.Open "select distinct table_name from information_schema.tables where table_schema = '" & cmbDB.Text & "'", con
    If Not rs.EOF Then List1.Clear
   ' totcnt = rs.RecordCount
    While Not rs.EOF
        Dim s As String
        s = ""
        table_name = VBA.IIf(IsNull(rs("TABLE_NAME")), "", rs("TABLE_NAME"))
        If table_name <> "" Then
            Call CreateFolder(cmbDB.Text)
            Open App.Path & "\" & cmbDB.Text & "\" & table_name & ".csv" For Output As #1
            If rs1.state = 1 Then rs1.Close
            rs1.Open "select * from " & table_name & " order by 1", con, 2
            fld = ""
            For i = 0 To rs1.fields.Count - 1
                fld = fld & rs1.fields(i).Name & ","
            Next i
            fld = VBA.Left$(fld, VBA.Len(fld) - 1)
            Print #1, fld
            While Not rs1.EOF
                rec = ""
                For i = 0 To rs1.fields.Count - 1
                    rec = rec & GetColumnValue(rs1, i, table_name) & ","
                Next i
                rec = VBA.Left$(rec, VBA.Len(rec) - 1)
                Print #1, rec
                rs1.MoveNext
                DoEvents
            Wend
            Close #1
        End If
        rs.MoveNext
        cnt = cnt + 1
        lblPct.Caption = (cnt / totcnt) * 100 & "% Complete..."
        lbl_progress.Caption = "Exporting table " & table_name & "...."
        DoEvents
    Wend
    rs.Close
    con.Close
    Command1.Enabled = True
End Sub


Private Sub Command1_Click()
    Call ExportData
End Sub

Private Sub Command2_Click()
    con.ConnectionString = "driver={MySQL ODBC 3.51 Driver};server=" & txtHostName.Text & ";" & _
    "database=mysql;Uid=" & txtUser.Text & ";Pwd=" & txtPasswd.Text & ";OPTION=3;"
    con.Open
    rs.Open "select distinct TABLE_SCHEMA from information_schema.tables order by 1", con, 2
    cmbDB.Clear
    While Not rs.EOF
        cmbDB.AddItem GetColumnValue(rs, 0, "information_schema.tables")
        rs.MoveNext
    Wend
    rs.Close
    Command2.Enabled = False
    Command1.Enabled = True
    cmbDB.Enabled = True
End Sub

Private Sub Form_Load()
    Set con = VBA.CreateObject("ADODB.Connection")
    Set rs = VBA.CreateObject("ADODB.Recordset")
    Set rs1 = VBA.CreateObject("ADODB.Recordset")
End Sub

Private Sub List1_Click()
    Dim i As Integer
    List2.Clear
    rs.Open "select * from " & List1.List(List1.ListIndex), con, 2
    For i = 0 To rs.fields.Count - 1
        List2.AddItem rs.fields(i).Name
    Next i
    rs.Close
End Sub

Private Function GetColumnValue(r As Object, colIndex As Integer, tble_name As String) As String   ', rowNum As Long) As String
On Error GoTo errs
    GetColumnValue = VBA.IIf(IsNull(r(colIndex)), "", r(colIndex))
    Exit Function
errs:
End Function

Private Sub CreateFolder(folderName As String)
    Dim fs As Object
    Set fs = VBA.CreateObject("Scripting.FileSystemObject")
    If Not fs.FolderExists(App.Path & "\" & folderName) Then
        Call fs.CreateFolder(App.Path & "\" & folderName)
    End If
    Set fs = Nothing
End Sub

Monday 7 September 2015

Connecting to Oracle Database using Hibernate Framework

A basic hibernate mvc tutorial which connect to Oracle database 12c and do some DDL and DML operation using hibernate framework. I have used Oracle database 12c release 1 on Red Hat Linux 6.4 64 bit and used Eclipse Helios 64 bit and Hibernate Framework 3.6.4. I am uploading the project and sharing the link. 


The main contents of the project is 
1. hibernate.cfg.xml, 2. UserDetails.java and 3. OracleTest.java.

It is not possible to  show the details steps of creating the project for that you need to see the video on youtube.

Download Hibernate 3.6.4-final  

Goto project properties, select Java build path, Click on Add library, Select Add user library, Click on New, Give name to the library, click on add jar files. and select these jars.



Now download ojdbc6.jar.zip and extract it to your desired location. Click on Add external jars and select ojdbc.jar. This jar is required for the jdbc driver for oracle connection.


Hibernate.cfg.xml is required to setup the connection to the database, configuration which initiates the connection, build the session, transactional savepoint and commit DDL and DML operation.
Create this three files inside src folder. Put Hibernate.cfg.xml in src root and 2 java files into the package you create.

Sample Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@192.168.0.109:1521:orcl</property>
        <property name="connection.username">hrd</property>
        <property name="connection.password">hrd</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

           <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.use_outer_join">false</property>
<!--          <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property> -->
        <mapping class="org.subhro.hibernate.UserDetails"/>       
    </session-factory>
</hibernate-configuration>

UserDetails.java

package org.subhro.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int UserId;
    private String UserName;
    /**
     * @param userId the userId to set
     */
    public void setUserId(int userId) {
        UserId = userId;
    }
    /**
     * @return the userId
     */
    public int getUserId() {
        return UserId;
    }
    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        UserName = userName;
    }
    /**
     * @return the userName
     */
    public String getUserName() {
        return UserName;
    }   
}



OracleTest.java

package org.subhro.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class OracleTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        UserDetails usr = new UserDetails();
        usr.setUserId(5);
        usr.setUserName("Fourth Record");
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(usr);
        session.getTransaction().commit();
    }
}