Thursday, July 7, 2011

get last inserted id from database table in Java, .NET , PHP

When we tried to retrieve a new record ID immediately after insertion,We did face bit trouble in getting that.

Different languages have different syntax/process of doing this.

Here is, How did I manage to get this done, in required projects:
For Java & PHP , we are using MySql dtabase, while in .NET we have used SQL server.

Java



//DBHelper , written for Database handling
DBHelper dbHelper = new DBHelper();
       Connection con = null;
       
String querySave = "";

       querySave = "INSERT INTO `DATABASE_NAME`.`TABLE_NAME` (`FIELD`) VALUES ( '"
               + VALUE_TO_BE_INSERTED + "');";
       Statement stmt = null;
       ResultSet rs = null;
       try {
//con is connection to database
           this.con = dbHelper.openDB(); //Here dbHelper is an instance of class,
           stmt = con.createStatement();
           int insertedRow = stmt.executeUpdate(querySave,
                   Statement.RETURN_GENERATED_KEYS);
           rs = stmt.getGeneratedKeys();
           int key = 0;
           if (rs.next()) {
               // Retrieve the auto generated key(s).
               key = rs.getInt(1);
               System.out.println("last inserted key is : " + key);

           }
catch (SQLException e) {
           e.printStackTrace();
       }
finally {
           dbHelper.closeDB();
           if (stmt != null) {
               stmt.close();
               stmt = null;
           }
           if (rs != null) {
               rs = null;
           }
           if (this.con != null) {
               this.con = null;
           }
       }


.NET



//dbManager - an object of one of the class from DATA Access Layer
  string sql = "INSERT INTO tgc_user_profile(firstName,emailId, password) VALUES(@firstName,@emailId,@password);" + "SELECT uid FROM tgc_user_profile WHERE uid = @@IDENTITY";

           try
           {
               dbManager.OpenConnection();

               dbManager.AddParameter("@firstName", name);
               dbManager.AddParameter("@emailId", email);
               dbManager.AddParameter("@password", password);

                ID = (int)dbManager.ExecuteScalar(sql, CommandType.Text);
               
       
           }

           catch (Exception ex)
           {
             
           }

           finally
           {
               dbManager.CloseConnection();
           }


PHP




$fName=mysql_real_escape_string($fName);
$email=mysql_real_escape_string($email);
$password=mysql_real_escape_string($password);
//mysql_real_escape_string to avoid sql injection attacks ,as we are using dynamic SQL query
$query_save = "INSERT INTO tgc_user_profile(firstName,emailId, password)
               VALUES ('".$fName."', '" .$email."', '" .$password ."')";
                             
             $_result = mysql_query($query_save);
            $ID = mysql_insert_id();


Hope this helps :)

Your valuable comments are appreciated !

Monday, July 4, 2011

ADO.NET : Preventing SQL injection attacks

Use Sqlparameter data-related class to help in preventing SQL injection attacks.

We should avoid Dynamic SQL like this

string strQry = "SELECT Count(*) FROM Users WHERE UserName='" +
txtUser.Text + "' AND Password='" + txtPassword.Text + "'";

because if user enter Username name value likely ' Or 1=1 -- then it return true what ever the value we have in password.

Sunday, July 3, 2011

Detect Client Operating System using javascript

Add this javascript code snippet:

<script>

alert(window.navigator.appVersion);

</script>

Tuesday, June 28, 2011

My amazing app on App store : iFindMyWine

One of my amazing app, Which I have developed , during my association with Ebizon Netinfo.Application owner is InfiniteSky Development, LLC.

I loved to develop ,design this iPhone app and helping in writing the web service in C#.NET.. SQL server ... Enjoyed it a lot !!!!!!!

http://itunes.apple.com/us/app/ifindmywine/id441508094?mt=8


Idea & description:

At the press of a button, it will find any retail outlet that offers wine, beer or liquor in your area, no matter where you are in Canada.

Find All Store Types - iFindMyWine is not limited to finding only liquor stores or wineries. Find any type of licenced liquor store in your area.

Receive News and Updates - One of the most important and unique features of iFindMyWine is its ability to broadcast special messages issued by specialty wine stores or wineries to notify users of new arrivals, availability of a rare vintage or monthly specials and promotional offers.

Get Clear Directions - Get clear maps of the area where you are and clear step by step instructions on how to get to your destination.

Look for a different store type quickly and easily from anywhere within the application.

You can not only look for what's available in your immediate surrounding, but you can also choose to search by province or by city, anywhere in Canada.

iFindMyWine will use the GPS capabilities built into your SmartPhone and will display all stores starting with the ones that are closest to your location and going to the farthest ones.

If you have selected "Stores Near Me" from the main menu, then the list of stores will automatically indicate with a colour dot, to the left of each listing, whether each store is currently open or closed, or even whether it will be closing in the next 30 minutes.

Once you have identified which wine or liquor store meets your criteria, get the complete details including complete address and phone number, map and directions and even store business hours.

Click on the store's phone number and your SmartPhone will automatically dial the number and put you in contact with the store directly so that you can find out if they have the particular vintage that you are looking for.


That's AMAZING!!!!!!!!!

Thursday, June 2, 2011

XMLParsers : SAX & DOM Parser

XML Parsing can be broken down into two logical components: a parser and a scanner.

The scanner reads the text and classifies it as "tokens". A token is a catagory that is recognized by the parser.

e.g. a scanner for the Java programming language might return the tokens that include: identifier, integer, for (a reserved word).

Before we begin, I wanted to make sure everyone is aware of the most important difference between XML parsers: whether the parser is a SAX or a DOM parser.


SAX vs. DOM

A SAX parser is one where your code is notified as the parser walks through the XML tree, and you are responsible for keeping track of state and constructing any objects you might want to keep track of the data as the parser marches through.

A DOM parser reads the entire document and builds up an in-memory representation that you can query for different elements. Often, you can even construct XPath queries to pull out particular pieces.

An important point, relative to SAX, is that the parser calls the scanner. As the parser processes the tokens returned by the scanner it performs operations, like building a syntax tree.

In the case of SAX, the scanner (the SAXParser object) calls the parser. This makes parsing with SAX needlessly awkward and complicates the architecture of the software. For this reason, the DOMParser is frequently used for parsing complicated XML documents.

The SAXParser does have two notable advantages over the DOMParser: the SAXParser is faster and it uses less memory. While the SAXParser is difficult to use for processing complex XML documents, perhaps it is appropriate for processing simple XML documents.....

in iPhone : NSXMLParser is a SAX parser included by default with the iPhone SDK. It’s written in Objective-C and is quite straightforward to use, but perhaps not quite as easy as the DOM model.

Tuesday, May 17, 2011

Installing Ruby, Rubygems, Rails on Mac OS X 10.5 (Leopard)

let’s get started. Unlike previous versions of Mac OS X, Leopard has everything you’ll need to compile Ruby. You don’t need to install any anything else. Take these commands and type or paste them into Terminal:


Paths
Don’t skip this step!

The path is actually an environment variable, set by a special file that’s automatically executed when you open a new Terminal window.

We need to make sure that our path is set to look for files in /usr/local (the place where we’ll be installing the tools) before looking anywhere else. This is important.

To see if the path has been set properly, we can check the contents of the .profile file (the special file hidden in our home folder) for a PATH line using a text editor(I am using TextWrangler ...).

edit ~/.profile
This will open the file if it already exists, or open a blank file if it doesn’t. Add the following line at the very end of the file:

export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"
Now save and close the file.

It doesn’t matter how many other lines there are in the file, or what they say or do. Just make sure that this line comes last and you should be fine.

To make sure the changes are picked up correctly, we now need to execute the file with the following command:

. ~/.profile
It’s likely there will be no response from the shell here, just the prompt, but that’s OK, the changes have been picked up and we’re ready to move on.

You can also close your Terminal and open a new one instead if you’d like.

Now :
Go to root and move to path
/usr/local/bin

Download

We’re going to create a folder to contain the files we’re about to download and compile. If you want, you can delete this folder when you’re done, but keeping it around makes it easier to re-install (or uninstall) these apps later.

Make the new folder:

mkdir ~/src cd ~/src

Download Ruby and Rubygems:

curl -O ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p174.tar.gz curl -O http://files.rubyforge.vm.bytemark.co.uk/rubygems/rubygems-1.3.5.tgz

Compile and Install

First, Ruby:

tar xzvf ruby-1.8.7-p174.tar.gz cd ruby-1.8.7-p174 ./configure --enable-shared --enable-pthread CFLAGS=-D_XOPEN_SOURCE=1 make sudo make install cd ..

To verify that Ruby is installed and in your path, just type:

which ruby

You should see:

/usr/local/bin/ruby

If you do, this means you now have a super-fast, 64-bit version of Ruby ready to go. If you saw something different, you haven’t set your path correctly. Go back and try again.

Compile and install RubyGems:

tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5 sudo /usr/local/bin/ruby setup.rb cd ..

Install Rails:

sudo gem install rails

sudo gem install rails

To start with, gem might complain that bundler requires a higher version. Something like this might happen, when you run “sudo gem install rails”:

ERROR:  Error installing bundler:
bundler requires RubyGems version >= 1.3.6
ERROR: Error installing bundler: bundler requires RubyGems version >= 1.3.6


If you run into that, you need to ask gem to update itself:

sudo gem update --system

Then rails’ installation should work.

If you use MySQL, you can now install the MySQL gem. You’ll need to know the location of your MySQL installation, which is typically/usr/local/mysql. Install the gem like this:

sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql

Congratulations, you now have a custom-built Ruby, RubyGems, and Rails configuration.





Sunday, March 27, 2011

apple script to delete selected line numbers from text editor

I was having a huge sql script, From which I need to extract a small portion..... Cut / Paste seems to be a tough task this time... then I tried to write a small but powerful script & YES! this worked and made this task very easy & quick.... :)

tell application "TextWrangler"
tell window 1
set a to 1
set b to 4330
select (lines a through b)
delete the selection
end tell
end tell