For Developers

StringTokenizer in JAVA

The StringTokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.


The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.


An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims having the value True or False :

  • If the flag is Flase , delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
  • If the flag is True , delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

Example without Delimiter:-


StringTokenizer st = new StringTokenizer("Example Of String Tokenizer");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}


Output
=====
Example
of
String
Tokenizer

Example with Delimiter:-


StringTokenizer st = new StringTokenizer("1$2$3$4","$");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}


Output
=====
1
2
3
4

What is IBATIS?

The iBATIS Data Mapper makes it easier to use a database with Java and .NET applications. iBATIS couples objects with stored procedures or SQL statements using a XML descriptor. Simplicity is the biggest advantage of the iBATIS Data Mapper over object relational mapping tools.

The iBatis framework is a lightweight data mapping framework and persistence API that can be used to quickly leverage a legacy database schema to generate a database persistence layer for your Java application. A set of XML encoded SQL Map files–one for each database table–holds SQL templates that are executed as prepared statements and map the expected results to Java domain classes. From application code, a layer of iBatis Data Access Objects (DAO) acts as the API that executes the SQL Map templates and assigns the results to the corresponding Java domain classes.

To enable communication among DAO layers and Sql Map layers, an XML configuration file describes each DAO interface and implementation class, as well as the location of a second XML configuration file that in turn points to each SQL Map file and contains the database connection information.

Create Database,Table and Procedure in Sql Server - Beginners

Database Creation :


CREATE DATABASE EMPLOYEE

Table Creation :

CREATE TABLE EMPINFO
(
ROWID INT IDENTITY(1,1) NOT NULL,
EMPID INT NOT NULL,
EMPNAME VARCHAR(50) NOT NULL,
EMPDEPT VARCHAR(3) NOT NULL,
EMPSAL INT NOT NULL,
EMPADDRESS VARCHAR(100) NOT NULL,
ACTIVE CHAR(1) NOT NULL DEFAULT ‘T’
)

Procedure Creation :

CREATE PROC EMPINFO_ADD_EDIT
(
@iEMPID INT,
@vEMPNAME VARCHAR(50),
@vEMPDEPT VARCHAR(3),
@iEMPSAL INT ,
@vEMPADDRESS VARCHAR(100),
@cACTIVE CHAR(1)
)
AS
DECLARE @CNT INT;
BEGIN
SET @CNT = 0;
SELECT @CNT = COUNT(*) FROM EMPINFO WHERE EMPID = @iEMPID;
IF(@CNT = 0)
BEGIN

INSERT INTO EMPINFO(EMPID,EMPNAME,EMPDEPT,EMPSAL,EMPADDRESS,ACTIVE)VALUES @iEMPID,@vEMPNAME,@vEMPDEPT,@iEMPSAL,@vEMPADDRESS,@cACTIVE)

END
ELSE
BEGIN

UPDATE EMPINFO SET EMPNAME = @vEMPNAME,EMPDEPT = @vEMPDEPT,EMPSAL = @iEMPSAL, EMPADDRESS = @vEMPADDRESS,ACTIVE = @cACTIVE WHERE EMPID = @iEMPID

END

END

What is Linked List ?

Linked list is one of the fundamental concepts in the data structure. It consists of a set of nodes, each containing a 'data' field and one or two references (pointing to adjacent nodes). It is a self referential datatype since it contains reference(s) of the adjacent (next or previous) datum of the same type.

Advantage :
Advantage of linked list compared to conventional array are

  • Insertions and deletions of nodes can be done at anywhere in the list.
  • List size can be increased and decreased in runtime.
  • Order of the linked items can be different from how it is stored in memory or disk, thus allowing the list of items to be traversed in different order.
Types of linked lists exist are Singly linked list, Doubly linked list and Circular linked list.

Swapping a Number

SWAPPING WITHOUT TEMP:


#include <stdio.h>

void main()

{

int a=20,b=30;

a=a+b;

b=a-b;

a=a-b;

printf("a=%d",a);

printf("b=%d",b);

}


SWAPPING WITH TEMP:


#include <stdio.h>

void main()

{

int a=20,b=30,temp;

temp=a;

a=b;

b=temp;

printf("a=%d",a);

printf("b=%d",b);

}


PALINDROME FOR STRING AND NUMBERS

PALINDROME FOR STRING AND NUMBERS:

Palindrome Checking Using C:


#include <stdio.h>

#include <conio.h>

#include <string.h>

#define size 26

void main()

{

char strsrc[size];

char strtmp[size];

printf("\n Enter String:= ");

gets(strsrc);

strcpy(strtmp,strsrc);

strrev(strtmp);

if(strcmp(strsrc,strtmp)==0)

printf("\n Entered string \"%s\" ispalindrome",strsrc);

else

printf("\n Entered string \"%s\" is not palindrome",strsrc);

getch();

}


Encrypting string value using MD5 in PHP

The md5 method is used to convert the string value into md5 value.
The syntax is,


string md5 ( string $str [, bool $raw_output ] )

Parameters

str : The string.
raw_output : If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16. Defaults to FALSE.


For Example,

echo "The MD5 value of 'ForDevelopers' is " . md5("ForDevelopers");

Check Sql Server database is Case Sensitive or Insensitive (Collation)

If the collation property of a data base is

1.Latin1_General_BIN its case-sensitive
2.SQL_Latin1_General_CP1_CI_AS or Latin1_General_CI_AI its case-insensitive

There are two ways to find out the SQL Server Database Collation

1. Using DATABASEPROPERTYEX

DATABASEPROPERTYEX gets the current setting of the specified database option or property for the specified database.


Syntax :-
DATABASEPROPERTYEX ( database , property )

SELECT DATABASEPROPERTYEX('testdb', 'Collation')


This returns the testdb Database Collation property value say if this testdb is a case-sensitive database then it returns

Latin1_General_BIN




2.Using Sql Server Management Studio

Step 1 : Open Sql Server Management Studio.

Step 2 : Right Click on database and click its properties


After clicking the properties you get a database properties modal box such as

The red box shows the collation property value of that database.

All in one search - Yahoo Glue

Yahoo! Glue is a new beta search engine which was initially launched in india as Yahoo Glue India and tested.Yahoo! Glue gets the best content around the web by a single search term in one page that is it displays web pages,news headlines,images,youtube videos,yahoo answer,blog search,flicker photos,wikipedia ect.. cool is'nt it.



Here i have made a search about barack obama which displays information about obama from various corners of the web.Yahoo! Glue home page diaplays top 10 pages from there system.The search keyword 'barack obama' is one of the top 10 pages in glue.

Glue does not give the web search result normally instead it provides the specialized information best on web. By this users will receive more relevant, visually appealing search results from across the Web in one page.

Yahoo! Glue now(Nov 19 2008) comes for US relevance and would be available world across soon.

Encrypting text value using MD5 in Dot Net

For example we will have two textboxes such as 'TextBox1' and 'TextBox2'.Now we will encrypt 'TextBox1' value using MD5 in Dot Net and display the encrypted value in 'TextBox2'.


string pwd = “”;

pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, “MD5″);

TextBox2.Text = pwd;

Disable Right Mouse Click Using JavaScript

Disable Right Mouse Click Using JavaScript:

Description:

This script will prevent the default right menu from popping up when the right mouse is clicked on the web page. Works well in IE4+ and NS4+.

To use this script, paste the following code in the <body> section of your HTML document.


Disable right click on mouse


Function to handle right click if the browser is IE

<script language="JavaScript">

var message=”Right Click is Disabled”;

function ExeForIE()
{
if (event.button==2)
{
alert(message);
return false;
}
}

</script>


Function to handle right click if the browser is FireFox

<script language=JavaScript>

var message=”Right Click is Disabled”;

function ExeForFFox(evt)
{
if (document.layersdocument.getElementById&&!document.all )
{
if (evt.which==2evt.which==3)
{
alert(message);
return false;
}
}
}

if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = ExeForFFox;
}
else if (document.all&&!document.getElementById)
{
document.onmousedown = ExeForIE;
}

document.oncontextmenu=new Function(”alert(message);return false”)

</script>


Block JavaScript Errors

We can have a function with return true and use it on window.onerror.Thus when the browser encounters a JavaScript error it returns true and block the error begin displayed.


function blkError()
{
return true;
}

window.onerror = blkError;

Open a File in Runtime in Java

Open a File in Runtime in Java:

1.Create a Object For Process

2.exec is a method to open a File in Runtime

3.In the exec Method, we can give all the command which can be give in the Run Window


Process process=Runtime.getRuntime().exec("notepad d:\demo.txt");


4.If it cannot Work,Copy Exe File and Paste it in C:\Windows\System32

Conditional Tags in JSP

The if tag allows the conditional execution of its body according to the value of the test attribute


<c:if test="${not empty details.add}">
It is Not a Empty ArrayList
</c:if>

<c:if test="${empty details.add}">
It is a Empty ArrayList
</c:if>


The choose tag performs conditional block execution by the embedded when subtags. It renders the body of the first when tag whose test condition evaluates to true. If none of the test conditions of nested when tags evaluates to true, then the body of an otherwise tag is evaluated, if present.

<c:choose>
<c:when test="${bank.account== 'saving'}">
Saving Account
</c:when>
<c:when test="${bank.account == 'RD'}">
RD Account
</c:when>
<c:when test="${bank.account == 'salary'}">
Salary Account
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>

Function To Generate Random Password using C#

usually you would send a random generated password while user does the registration process through your application.You can use the following code to achieve that.


public string Generate_Password()
{
string Password = “”;
byte Cnt, Idx;
string values = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
Random rnd = new Random();
for (Cnt = 1; Cnt <= 6; Cnt++)
{
Idx = (byte)rnd.Next(0, values.Length);
Password += values.Substring(Idx, 1);
}
return Password.Trim().ToUpper();
}

To Generate Random Password we have used the Random Class(Namespace:-System).To learn more about Random Class have a look at this MSDN LINK.

SQL Server Connection Using Integrated Security

When we are connecting sql server using windows authentication then we do not need to give the user name and pwd in the connection string. We have to provide the Integrated Security property to true.


SqlConnection con = new SqlConnection(“Server=servername;Integrated Security=true; Database=emp”);


Note : If your sql server is of windows authentication and if you dont provide Integrated Security you may get an error such as follows
Login failed for user ‘(null)’. Reason: Not associated with a trusted SQL Server connection.

What is Delegate?

A delegate is a type that references a method.Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method,with parameters and a return value.


Any method that matches the delegate’s signature,which consists of the return type and parameters,can be assigned to the delegate.


Delegates allow methods to be passed as parameters.It can be used to define callback methods.

Data Source Object

What is Data Source Object?

A data source object (DSO) is a Microsoft ActiveX object embedded within a Web page. It employs a process called data binding, in which an ActiveXControl communicates directly with another Web page, or with an external XML source.


In order to take advantage of DSOs, it is necessary to have Internet Explorer version 4.0 or later. Web developers commonly create their own DSOs. For example, an animated weather radar image from the National Hurricane Center can be displayed continuously on the home page of a municipal civil defense department, without the need for clicking on a link to get to the National Hurricane Center site.


Data source objects are sometimes used for the purpose of implementing This type of intrusion shows up on spyware detection programs as a DSO exploit. Such spyware can be difficult to eradicate, and if it is successfully removed, it often returns.

What is ViewState ?

ASP.NET view state is the technique used by an ASP.NET Web page to persist
changes to the state of a Web Form across postbacks.That is when a form is submitted in ASP .NET, the form reappears in the browser window together with all form values.

The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat=”server”> control.

Hidden field placed on each page would be something as this
<input type=”hidden” name=”__VIEWSTATE” value=”CEbzzzEnmmz+Bc8IDFlnpgCLJ/HB00.>

Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive l%@ Page EnableViewState=”false” %> at the top of an .aspx page or add the attribute EnableViewState=”false” to any control.

Java with Sql Server

How to Connect Java with Sql Server :

1.import sql package

2.Give all the Supporting class in class.forName

3.Give Ipaddress or Computer Name in dburl or in getConnection

4.Use 1433 port Number as Default Port.

5.Give Username and Password in getConnection

6.Open the Connection using createStatement

7.Execute the query String using executeQuery Statement

8.Fetch the Record one by one Using ResultSet

9.Close the Connection



import java.io.*;
import java.sql.*;
public class sqlserverConnection
{
public static String dburl=”jdbc:mysql://localhost:1433”;
public static String username=”admin”;
public static String pwd=”pass”;
public static Connection con=null;
public static Statement stmt=null;
public static ResultSet rs=null;

public static void main(String[] args)
{
try {

Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
con=DriverManager.getConnection(dburl,username,pwd);
stmt=con.createStatement();
rs=stmt.executeQuery(”SELECT * FROM demo”);
while(rs.next())
{
String name=rs.getString(1);
}
}
catch(SQLException sqlExcp)
{
sqlExcp.printStackTrace();
}
}
}

Java with Mysql

How to Connect Java with Mysql:

1.import sql package

2.Give all the Supporting class in class.forName

3.Give Ipaddress or Computer Name in dburl or in getConnection

4.Give Username and Password in getConnection

5.Open the Connection using createStatement

6.Execute the query String using executeQuery Statement

7.Fetch the Record one by one Using ResultSet

8..mysqldemo is a schema name

9.Close the Connection



import java.io.*;
import java.sql.*;
public class MysqlConnection
{
public static String dburl=”jdbc:mysql://localhost/mysqldemo”;
public static String username=”root”;
public static String pwd=”root”;
public static Connection con=null;
public static Statement stmt=null;
public static ResultSet rs=null;

public static void main(String[] args)
{
try {

Class.forName(”org.gjt.mm.mysql.Driver”);
(or)
Class.forName(”com.mysql.jdbc.Driver”);//use this

con=DriverManager.getConnection(dburl,username,pwd);
stmt=con.createStatement();
rs=stmt.executeQuery(”SELECT * FROM demo”);
while(rs.next())
{
String name=rs.getString(1);
}
}
catch(SQLException sqlExcp)
{
sqlExcp.printStackTrace();
}
}
}

Database Configuration in CakePHP

Step 1: Open the directory "/root/app/config/"
Step 2: Rename the "database.php.default" into "database.php"
Step 3: Open the file, that contain the default variable as shown below. Change the array variable values


var $default = array('driver' => 'mysql',
'connect' => 'mysql_connect',
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'project_name',
'prefix' => '');

driver : This can be mysql, postgres, sqlite, adodb or pear-drivername
connect : should use persistent database connections. For mysql this options are 'mysql_pconnect' or 'mysql_connect'
host : name of your database server, such as localhost / mysql.domainname.com
login : user name for your database login
password : password for your database login
database : name of the database
prefix : The string that prefixes every table name in the database. If your tables don’t have prefixes, this to an empty string.
Step 4: Save and close the file.

Add a Row Dynamically using JavaScript

How to Add a Row Dynamically Using JavaScript:

  • We can see how button,textbox,textarea can be added Dynamically
  • All the tag which can be given in the input tag has to be given in setAttribute as shown in below coding
  • if u call a function then call as but1.onclick = function () {show(this)};
  • If u delete the Row,then reorder all the other row
1.If u Add a Button to a Table,then use this


var cell1 = row.insertCell(0);
but1 = document.createElement('input');
but1.setAttribute('type', 'button');
but1.setAttribute('className', 'button');
but1.setAttribute('value', '');
but1.onclick = function () {show(this)};
cell1.appendChild(but1);


2.If u Add a Textbox to a Table,then use this


var cell2 = row.insertCell(1);
var txt = document.createElement('input');
txt.setAttribute('type', 'text');
txt.setAttribute('name', 'firsttextbox');
txt.setAttribute('className', 'text_box');
txt.setAttribute('id', 'firsttextbox' + iteration);
txt.setAttribute('size', '21');
cell2.appendChild(txt);


3.If u Add a Textarea to a Table,then use this


cell1 = row.insertCell(1);
var e1 = document.createElement('textarea');
e1.name = 'text2' + iteration;
e1.id = 'text2' + iteration;
e1.column= '50';
cell1.appendChild(e1);


4.Row can be Re-Order by using


var tbl = delRow.parentNode.parentNode;
tbl.tBodies[0].rows[i].myRow.two.id = 'firsttextbox' + count;


If u Delete 3 Row the Reorder as
4th Row as----3th Row
5th Row as----4th Row
6th Row as----5th Row

5.If u want to Delete the Third Row,then use this coding


var delRow = obj.parentNode.parentNode;
var rowArray = new Array(delRow);
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}


  • We have to pass all the id in the row as deleterow(this)
  • this can be get in the obj variable
  • Using the For Loop we have to Delete the Particular Row




Demo Link

Taglibs in JSP

Different Taglibs and its Usuage in JSP:

1.Core:http://java.sun.com/jsp/jstl/core
This Taglibs is used for Looping,Variable Support,Flow control,URL Management and miscellaneous


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


2.XML:http://java.sun.com/jsp/jstl/xml
This Taglibs is Used for Core,Flow Control and Transformation

<%@taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="xl"%>


3.Internationalization:http://java.sun.com/jsp/jstl/fmt
This Taglibs is Used For Locale, Message formatting and Number & date formatting

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>


4.SQL:http://java.sun.com/jsp/jstl/sql
This Taglibs is Used For Sql Query Purpose

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>


5.Functions:http://java.sun.com/jsp/jstl/functions
This Taglibs is Used For Collection length and String manipulation

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

Javascript compare two numbers

How to compare two Value in JavaScipts:

1.Get the Value From Html Page using getElementById

2.Compare by Using parseInt For Interger Value and parseFloat For Float Value

3.compare two value as


var first=document.getElementById('first').value;
var second=document.getElementById('second').value;

if(parseInt(first)<parseInt(second))
alert('Second Value is Greater than first');

else if(parseInt(first)>parseInt(second))
alert('First Value is Greater than second');

else if(parseInt(first)==parseInt(second))
alert('First Value and second value is equal');


4.Include the code in Html Page For TextBox

First Value:<input type="text" value="0" onkeyup="compare();" name="first" id="first">
Second Value:<input type="text" value="0" onkeyup="compare();" name="second" id="second">



Demo Link

CakePHP Files and Folder Structure

When you unpack Cake on your server you will find four folders - app, cake, tmp and vendors. The cake folder is where the core libraries for Cake lay and you generally won't ever need to touch them unless you want to do some customization to Cake itself.

The app
is where your application specific folders and files will go. The separation between the cake folder with the core libraries and the app folder make it possible for you to have many app folders sharing a single set of Cake libraries. This also makes it easy to update CakePHP: you just download the latest version of Cake and overwrite you current core libraries; No need to worry about overwriting something you wrote for your app.

The tmp directory is used for various Cake operations, such as baking (automatically creating new php files), caching, and logging.

You can use the vendors directory to keep third-party libraries in. You'll learn more about vendors later.

The folders structure and their basic purposes:


--- root (the root directory)

--- --- app (here's where your application logic will go)

--- --- --- config (application specific configurations)

--- --- --- controllers (controllers go here)

--- --- --- --- components

--- --- --- index.php

--- --- --- models (models go here)

--- --- --- plugins (third party apps – go here)

--- --- --- views (view related files go here)

--- --- --- --- elements (small repeated layout items go here)

--- --- --- --- errors (error pages go here)

--- --- --- --- helpers (your home-based helpers go here)

--- --- --- --- layouts (page layouts go here)

--- --- --- --- pages (static content managed by PagesController go here)

--- --- --- webroot (this directory as your webroot, and stick your public files in here)

--- --- --- --- css

--- --- --- --- files

--- --- --- --- img

--- --- --- --- js

--- --- cake (this is where the libraries are placed: Note: it's best not to touch)

--- --- index.php

--- --- tmp (used for logs, baking, etc.)

--- --- vendors (stick your third party libraries here)



How to Installing CakePHP?

Step 1 : Getting the most recent stable version
To install Cake PHP you first need to download the latest stable version from the CakePHP website at www.cakephp.org, once at the website click on Downloads > Release.
Download link : http://cakephp.org/downloads/index/nightly/1.2.x.x

Step 2: Unpacking
Now that you've downloaded the most recent release, place that compressed package on your web server in the webroot. Now you need to unpack the CakePHP package. There are two ways to do this, using a development setup, which allows you to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Features of CakePHP

Like Rails, CakePHP makes it easier for the user to interface with the database with active records. It also encourages use of the model-view-controller architectural pattern.

  • Active, friendly community
  • Flexible licensing
  • Compatible with PHP4 and PHP5
  • Integrated CRUD(Create, Read, Update & Delete) for database and simplified querying
  • MVC architecture
  • Request dispatcher with clean, custom URLs and routes
  • Built-in validation
  • Templating (PHP syntax with helper methods)
  • View Helpers for AJAX, JavaScript, HTML Forms and more
  • Email, Cookie, Security, Session, and Request Handling Components
  • Flexible Access Control Lists (ACL)
  • Application scaffolding
  • Data sanitization
  • Flexible caching
  • Localization
  • Works from any web site directory, with little to no Apache configuration involved

History of CakePHP

CakePHP started in 2005, when Ruby on Rails was gaining popularity. The community has since grown and spawned several sub-projects. CakePHP is not a port of Ruby on Rails to PHP, but appropriates many of its useful concepts.

The Mambo Foundation announced in 2007 that it would utilize the CakePHP framework for future versions of its widely used content management system, calling CakePHP a "solid choice and certainly one of the top frameworks available today."

What is CakePHP?

CakePHP is a free, open source, rapid development framework written in PHP. A structure of libraries, classes and run-time infrastructure for programmers creating web applications inspired originally by Ruby on Rails framework. The primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.

Get MicroSoft Free Softwares in India(For College Students)

Hi All get started with MicroSoft designer and developer products through Microsoft DreamSpark™ free Softwares.

Microsoft DreamSpark™ is a program that provides no-cost access to Microsoft designer and development tools,so to get a head start in your career.



Microsoft DreamSpark™ provides two ways to get the softwares.

Through Online

Step 1 : Go to http://www.dreamspark.com/

Step 2 : Sign In with your Windows Live ID.

Step 3 : Get verified as a student.

Step 4 : Download your products.

Through Offline

Step 1 : Visit any of thier partner locations(like NIIT,Aptech training institute)

Step 2 : Show your college identity card to collect your DVD containing the software.

Step 3 : Go to the link ‘Get Verified’ in DreamSpark website and enter the 25 digit verification key mentioned on the DVD.

Step 4 : Sign In with your Windows Live ID.

Step 5 : Download the relevant License Keys from the world wide DreamSpark website.

Microsoft DreamSpark is now available to university students across India. Microsoft DreamSpark is planning to expanded to include high school students by early 2009.

Create a Stored Procedure within a Stored Procedure

When you want to create a stored procedure dynamically,we can create a stored procedure within a stored procedure.


CREATE PROC procCreateProcedure
(
@spname NVARCHAR(100)
)
AS
BEGIN
DECLARE @ProcedureName NVARCHAR(100)
DECLARE @Exe VARCHAR(8000)


/*setting the stored procedure name with spname passed*/

SET @ProcedureName = @spname

/*setting the stored procedure name with spname passed*/

/*Nothing will be done if procedure name is empty*/
IF LTRIM(RTRIM(@ProcedureName)) = ”
BEGIN
RETURN
END
/*Nothing will be done if procedure name is empty*/


/*Creating the stored procedure*/

SET @Exe = ‘CREATE PROC ‘ + @ProcedureName + CHAR(13) +

‘AS’ + CHAR(13) + CHAR(13) +

‘BEGIN’ + CHAR(13) +

‘SELECT * FROM EMPLOYEE’+ CHAR(13) +

‘END’

/*Creating the stored procedure*/

/*Executing the created stored procedure*/
EXEC(@Exe)
/*Executing the created stored procedure*/

END

/*Executing procCreateProcedure to creat new stored procedure*/
EXEC procCreateProcedure ‘procTest’
/*Executing procCreateProcedure to creat new stored procedure*/

now execute and see the stored procedure by name you passed.

EXEC procTest


Here in this example a new stored procedure with name ‘procTest’ which is passed in ‘procCreateProcedure’ is created and employee table is fectched when ‘procTest’ stored procedure is executed.

Accessing Private Variable

Reflection in java:
Reflection is the mechanism by which Java exposes the features of a class during runtime, allowing Java programs to enumerate and access a class’ methods, fields, and constructors as objects. In other words, there are object based mirrors which reflect the Java object model, and you can use these objects to access an object’s features using runtime API constructs instead of compile time language constructs.

Each object instance has a getClass() method, inherited from java.lang.Object, which returns an object with the runtime representation of that object’s class; this object is an instance of the java.lang.Class.This object in turn has methods which return the fields, methods, constructors, superclass, and other properties of that class.

You can use these reflection objects to access fields, invoke methods, or instantiate instances, all without having compile time dependencies on those features. The Java runtime provides the corresponding classes for reflection. Most of the Java classes which support reflection are in the java.lang.reflect package.

Accessing Private Features with Reflection:
All features of a class can be obtained via Reflection, including Access to private methods & variables.Setting the Accessible flag in a reflected object of java.lang.reflect.AccessibleObject class allows us to read/modify a private variable that we normally wouldn’t have permission to. However, the access check can only be supressed if approved by installed SecurityManager.
The Classes java.lang.reflect.Field, java.lang.reflect.Method and java.lang.reflect.Constructor can inherit this behavior from java.lang.reflect.AccessibleObject class. The following example demonstrates read/modify access to a private variable which is normally inaccessible.

SimpleKeyPair.java


package com;

public class SimpleKeyPair {

private String privateKey = “Welcome SimpleKeyPair “; // private field

}

PrivateMemberAccessTest.java

package com;

import java.lang.reflect.Field;

public class PrivateMemberAccessTest {

public static void main(String[] args) throws Exception {

SimpleKeyPair keyPair = new SimpleKeyPair();

Class c = keyPair.getClass();

// get the reflected object

Field field = c.getDeclaredField(”privateKey”);

// set accessible true

field.setAccessible(true);

System.out.println(”Value of privateKey: ” + field.get(keyPair));

/* prints “Welcome SimpleKeyPair */

// modify the member varaible

field.set(keyPair, “Welcome PrivateMemberAccessTest”);

System.out.println(”Value of privateKey: ” + field.get(keyPair));

/* prints “PrivateMemberAccessTest” */

}

}


Output

=====

Value of privateKey: Welcome SimpleKeyPair

Value of privateKey: PrivateMemberAccessTest

JavaScript to Validate Email Format

Script :


var efmt=/^\w+((-\w+)(\.\w+))*\@[A-Za-z0-9]+((\.-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;

function checkEmailFormat(field,msg)
{
var ctrl=document.getElementById(field);
if((!efmt.test(ctrl.value)) && ctrl.value!=”)
{
alert(msg);
ctrl.focus();
}
}

Html Code :


< type=”Text” onblur=”checkEmailFormat(’Txtemail’,'Please enter a valid email address, like sample@yahoo.com’);” id=”Txtemail” />


Demo Link

What is "CLR(Common Language Runtime)"

Common language runtime is a .NET Framework run-time environment which manages the execution of programs written in any of several supported languages. Microsoft refers to its Common Language Runtime as a “managed execution environment.

Programmers writing in any of Visual Basic, Visual C++,or C# compile their programs into an intermediate form of code called Common Intermediate Language (CIL) in a portable execution (PE) file that can then be managed and executed by the Common Language Runtime.

The CLR’s just-in-time compiler (JIT compiler) converts the CIL code into code native to the operating system.The virtual machine aspect of the CLR allows programmers to ignore many details of the specific CPU that will execute the program.

The CLR also provides other important services,such as Memory management,Thread management,Exception handling,Garbage collection,Security.


Compare two ArrayList in JSP

Compare two ArrayList:

1.ArrayList are ListOfData and SecondList

2.Include this tag in the JSP Page


<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>


3.Find the Length of the ArrayList Using fn:length tag

4.Compare the ArrayList as


<c:if test="${not empty ListOfData}" >
<c:forEach var="j" begin="0" end="${fn:length(SecondList)-1}">
<c:forEach var="i" begin="0" end="${fn:length(ListOfData)-1}">

<tr>
<c:if test="${SecondList[j].empid==ListOfData[i].empid}">
<td>${ListOfData[i].empid} </td>
<td>${ListOfData[i].empname} </td>
<td>${ListOfData[i].empdest} </td>
</c:if>
</tr>
</c:forEach>
</c:forEach>
</c:if>