Friday, June 29, 2007

Get file extension using javascript

Get file extension using javascript:
=============================


//way to call
GetExtension(form1.attach1.value);


function GetExtension(filename) {
var ext;
//get last 3 letters i.e. extension
ext=filename.substring(filename.length-3,filename.length);
return ext;
}

Tuesday, June 26, 2007

play with ms sql server sysobjects

play with ms sql server sysobjects
===========================


Sometimes you may want to see the list of all the objects within a database. This can be easily achieved.

SELECT * FROM master..sysobjects


This below query list out all the store procedure within a database :

SELECT * FROM master..sysobjects WHERE TYPE='P'

You may try out the other options:

SELECT * FROM master..sysobjects WHERE TYPE='U'

SELECT * FROM master..sysobjects WHERE TYPE='X'

You may list out some system functions:


SELECT LEFT(name, 30) FROM master..sysobjects WHERE LEFT(name, 3) = 'fn_'

How to view structure of a table using Ms Sql Server

How to view structure of a table using Ms Sql Server
=========================================


You must be aware of describe table / desc table statement in oracle. By using this statement you can view the structure of a oracle table.

Same way in Ms Sql Server you can do the same by using
sp_columns store procedure.

Eg: sp_columns myTable

Generate insert statement from sql query

Generate insert statement from sql query
=================================


In some case you might have a requirement where you might want to generate insert statments directly by firing a sql query. I am sure you might need to use this especially for those who are into maintainance related work.

Anyway here is the process:

You might want to create a table : (I am assuming that you are already having a table)

create table myTable (
Id int,
name nvarchar(200))

select * from myTable


Insert some data into the table : (I am assuming that you are already having data into table)

insert into myTable values(1,'kingkong')
insert into myTable values(2,'godzilla')


Here is the main sql statement which generates the sql. The logic is straigh forward. Just to insert single quotes you might need to add '''' .. just change the query as per your own requirement



select convert(varchar(1000),'insert into myTable values(' + convert(varchar(10),Id) + ',' + '''' + convert(varchar(100),Name) + '''' + ')') from myTable

Result: (listing all the insert statement for a given table)

insert into myTable values(1,'kingkong')
insert into myTable values(2,'godzilla')


Same way like above you might want to generate custom update statement as well. You can also try it out by yourself

Wednesday, June 13, 2007

Sql Connection in Ruby

sql connection in Ruby
=================


Define a sql connectivity function:

def connection
#connection details like dsn, uid and password
$dsn = "POS"
$uid = ""
$pwd = ""
$c = ODBC.connect($dsn, $uid, $pwd)
end


def callConnection()
#opening database connection
connection()
end


#Typical login script
def onLoginClick(event)
$username="myUserName"
$password="myPassword"
$sql="select * from loginmaster where username='" + $username + "' and password='" + $password + "'"
#creating a connection object
$dsn = "POS"
$uid = ""
$pwd = ""
$c = ODBC.connect($dsn, $uid, $pwd)

$q=$c.prepare($sql)
$q.execute

if $q.fetch == nil then
#message will only show if you use wxpos - uncomment below if you are using wxwidget
# message_box("Incorrect Login", "Login",OK ICON_INFORMATION, self)

else
close()
end

end





Introduction to Ruby language

Introduction to Ruby language

About Ruby Language

Ruby is a powerful and dynamic open source, object-oriented language, cross-platform language and interpreted language developed by Yukihiro Matsumoto(Matz) around 1994. Matz is a professional programmer who has worked for the Japanese open source company, netlab. jp. Ruby is developed under Linux, and is written in fairly straightforward C. It runs under UNIX, DOS, Windows 95/98/NT/2000, Mac OSX, BeOS, Amiga, Acorn Risc OS, and OS/2.


Features of Ruby include :

• Simple Syntax
• Normal Object-Oriented features(ex. class, method calls)
• Advanced Object-Oriented features(ex. Mix-in, Singleton-method)
• Operator Overloading
• Exception Handling
• Iterators and Closures
• Garbage Collection
• Dynamic Loading of Object files(on some architecture)
• Highly Portable(works on many UNIX machines, and on DOS, Windows, Mac, BeOS etc.)


Reasons To Learn Ruby :

Ruby's primary focus is productivity of program development, and users will find that programming in Ruby is productive and even fun. Ruby is well suited for the problem domains such as these:

Text processing—Ruby's File, String, and Regexp classes help you process text data quickly and cleanly.

CGI programming—Ruby has everything you need to do CGI programming, including text-handling classes, a CGI library, database interface, and even eRuby (embedded Ruby) and mod_ruby for Apache.

Network programming—Network programming can be fun with Ruby's well-designed socket classes.

GUI programming—GUI tool kit interfaces such as Ruby/Tk, Ruby/Gtk, Ruby/WxRuby etc are available.

XML programming—Text-handling features and the UTF-8-aware regular expression engine make XML programming handy in Ruby. The interface to the expat XML parser library is also available.

Prototyping—With its high productivity, Ruby is often used to make prototypes. Prototypes sometimes become production systems by replacing the bottlenecks with C written extensions.

Programming education—You can teach students that programming is fun


Why should you switch to Ruby?

If you are happy with Perl or Python, you don’t have to. But if you do feel there must be a better language, Ruby may be your language of choice. Learning a new language is harmless. It gives you new ideas and insights. You don’t have to switch, just learn and try it. You may find yourself comfortable enough with Ruby to decide to switch to it."

. Yukihiro Matsumoto (Matz)

Ruby Home-page : http://www.ruby-lang.org/

wxRUBY (wxWidget/wxWindows) - Widgets

wxRuby is a library to allow Ruby programs to use wxWindows 2.4.x (wxWidgets) which is a mature cross platform, GUI toolkit that uses native widgets where possible.

With the help of wxRUBY nice GUI objects can be used with your program. wxRUBY supports a huge library of widgets.

It uses NativeWidgets where possible, but draws its own complex widgets when the native platform doesn't have them. On Win32 it uses all (or almost all) native widgets, but on GTK+ it draws a tree control and a list control that are like the Win32 versions. This makes cross-platform portability easier without having to just use "lowest common denominator" widgets.

There is a wrapper for the Scintilla (www.scintilla.org) syntax-highlighting text editor. Scintilla supports Ruby syntax. There were recent discussions on the mailing list about a Ruby IDE. The Scintilla support makes wxWindows an interesting possibility for writing such an IDE.

In addition to Win32 and GTK+, it also runs on the Mac, and a port to embedded systems is almost ready. wxWindows has been around for 10 years, and has a wide selection of widgets available.

wxRuby is actively being developed at: http://rubyforge.org/projects/wxruby/

Basic Screen Save in C language (begineers)

Basic Screen Save in C language (begineers)

/* very basic screen saver in C language */
/* Screen saver - random circles, lines and rectangle and other shapes
COMPILER: Turbo C 2.01
*/


#include
#include
#include
#include


char ch;
/****************************************/
/* for line */
int lrandx, lrandy, lrandxx, lrandyy;
/* for rectangle */
int rrandx, rrandy, rrandxx, rrandyy;
/* for circle*/
int crandx, crandy, cradius;
/* random colour and shape generation */

int shape;
int col;

int gdriver,gmode,errorcode;
/*****************************************/
void main(){
gdriver=EGA;
gmode=EGAHI;
/*initialize the graphics driver*/
initgraph(&gdriver,&gmode,"");
/* error handling for graphics driver */
errorcode = graphresult();
if (errorcode != grOk ) {
printf("Graphics Error \n %s",grapherrormsg(errorcode));
printf("\n Press any key to halt:");
getch();
exit(1);
}
/* setting initiation of text and background color */
initialscreen();
while (!kbhit()) /* do nothing */ {
sleep(0.5);
mainscreen();
/*
outtextxy(133,44,"Sss");
*/

}
/*closing or deallocating graphic driver*/
closegraph();
}


/*main background screen*/
mainscreen() {
shape=rand()%3;
col=rand() % 14;
if (shape==0) {
rrandx=rand() % 600;
rrandy=rand() % 600;
rrandxx=rand() % 800;
rrandyy=rand() % 800;
setcolor(col);
rectangle(rrandx, rrandy, rrandxx, rrandyy);
}
else if (shape==1) {
lrandx=rand() % 200;
lrandy=rand() % 200;
lrandxx=rand() % 200;
lrandyy=rand() % 200;
setcolor(col);
line(lrandx, lrandy, lrandxx, lrandyy);
}
else {
crandx=rand() % 600;
crandy=rand() % 600;
cradius=rand() % 100;
setcolor(col);
circle(crandx, crandy, cradius);
}
return 0;
}

initialscreen() {
setbkcolor(4);
setcolor(1);
settextstyle(0,0,2);
outtextxy(40,40,"SCREEN SAVER...");
setcolor(11);
outtextxy(150,120,"---- computer bapu");
sleep(2);
cleardevice();
return 0;
}

Generating character (letter) in C language

Generating character (letter) in C language

As shown below is the demostratation to generate a character B using pixels using C.

This is how the computer renders(displays) fonts at very low level. While making any doc you must know how the system renders font. Each and every letter is displayed by a pixel square of 1's and 0's ... 1 represents visibility while 0 represents hiding the pixel.

Eg: Its B as below. Its rather looks like a 8. You have to make perfect combination of 1's and 0's as in the grid to get desired output.
111111
110011
111111
111111
110011
111111

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

#include
#include
#include
void generatecharback();
void generatechar(char);
void main()
{
int gdriver, gmode;

gdriver=DETECT;
gmode=EGAHI;
initgraph(&gdriver,&gmode,"");
setbkcolor(4);
generatecharback();
generatechar('B');
outtextxy(203, 200, "char generation");
getch();
closegraph();
}

void generatecharback(){
int i=0;
int j=0;
for(i=0;i<=7;i++){
for(j=0;j<=7;j++){
putpixel(i+100,j+100,8);
}
}
}
void generatechar() {
int charray[1][65]={{1,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0}};
int i,j,k;
k=0;
for(i=0;i<=7;i++){
for(j=0;j<=7;j++){
if(charray[0][k]==1){
putpixel(j+100,i+100,WHITE);
}
k++;
}
}
}

IP Addressing

IP Addressing
============

An identifier for a computer or device on network Networks route messages based on the IP address of the destination. Every computer that communicates over the Internet is assigned an IP address that uniquely identifies the device and distinguishes it from other computers on the Internet. An IP address consists of 32 bits, often shown as 4 octets of numbers from 0-255 represented in decimal form instead of binary form. The four numbers in an IP address are used in different ways to identify a particular network and a host on that network.

For example, the IP address
168.212.226.204
in binary form is
10101000.11010100.11100010.11001100.


But it is easier for us to remember decimals than it is to remember binary numbers, so we use decimals to represent the IP addresses when describing them. However, the binary number is important because that will determine which class of network the IP address belongs to. An IP address consists of two parts, one identifying the network and one identifying the node, or host. The Class of the address determines which part belongs to the network address and which part belongs to the node address. All nodes on a given network share the same network prefix but must have a unique host number.

Class A Network -- binary address start with 0, therefore the decimal number can be anywhere from 1 to 126. The first 8 bits (the first octet) identify the network and the remaining 24 bits indicate the host within the network. An example of a Class A IP address is 102.168.212.226, where "102" identifies the network and "168.212.226" identifies the host on that network.

Class B Network -- binary addresses start with 10, therefore the decimal number can be anywhere from 128 to 191. (The number 127 is reserved for loopback and is used for internal testing on the local machine.) The first 16 bits (the first two octets) identify the network and the remaining 16 bits indicate the host within the network. An example of a Class B IP address is 168.212.226.204 where "168.212" identifies the network and "226.204" identifies the host on that network.

Class C Network -- binary addresses start with 110, therefore the decimal number can be anywhere from 192 to 223. The first 24 bits (the first three octets) identify the network and the remaining 8 bits indicate the host within the network. An example of a Class C IP address is 200.168.212.226 where "200.168.212" identifies the network and "226" identifies the host on that network.

Class D Network -- binary addresses start with 1110, therefore the decimal number can be anywhere from 224 to 239. Class D networks are used to support multicasting.

Class E Network -- binary addresses start with 1111, therefore the decimal number can be anywhere from 240 to 255. Class E networks are used for experimentation. They have never been documented or utilized in a standard way.

Tuesday, June 12, 2007

Web Ports

Web Ports
=========


Some of you might have woundered what are sockets and ports.

Sockets are low-level access points to the IP stack. Socket is used to send and receive data where data generally travels in blocks (these blocks are referred to as packets) of few kilobytes at a time.

Also these packets which travel from source to destination must follow a set of rules i.e. protocol.

Also at the source / destination there is a term called port which defines the kind of service. This no can be between 1 to 65535. Eg: port no 80 is used to identify http service (webpage request by the client).

Hence when we type www.google.com, the client (i.e. our machine with a ip address (through web browser client software)) it asks the google server at port no 80 to provide a service of delivering the webpage google.com. During this process it must use various protocols http(hyper text transfer protocol - transferrng of webpage also known as hypertext docs) and tcp/ip protocol (transmission control protocol/internet protocol) for disassembling of data to packets at source and assembling of packets at destination and tranfer of packets. Also tcp is responsible for assigning headers informa like destination ipaddress, checksum, packet no etc etc..


Anyway here is a list of port nos (most of which are reserved):


20 - FTP data
21 - FTP control
25 - smtp email outgoing
53 - DNS
66 - Oracle SQL*Net
80 - http (webpages)
81 - http proxy, alternative http port, cobalt server administration port
110 - pop3 incoming email
143 - IMAP incoming email
443 - Secure Socket Layer (SSL)
445 - Ms Sql Server over NetBIOS
457 - unixware/netscape fasttrack server
1080 - socks proxy
1100 - oracle webcache listener
1241 - kazaa file sharing server
1352 - lotus domino (notes)
1433 - ms sql server 2000
1434 - ms sql server over tcp/ip redirector
1521-1530 - oracle
1944 - ms sql server 7
2301 - compaq insight manager, compaq survey utility
3128 - http proxy (squid, netcache, etc.)
3306 - mysql
4000 - oracle webcache listener
4001 - oracle webcache listener
4002 - oracle webcache listener
4100 - sybase 11.0 (jConnect)
5000 - sybase 12.x
5432 - postgreSQL
5800 - VNC HTTP Console Port #1
5801 - VNC HTTP Console Port #2
5802 - VNC HTTP Console Port #3
6346 - Gnutella (HTTP-like protocol)
6347 - Gnutella (HTTP-like protocol)
7001 - BEA WebLogic
7002 - BEA WebLogic
8000 - HTTP Proxy, Alternative HTTP Port, HP Web JetAdmin
8001 - BEA WebLogic
Port - Server
8005 - Apache Tomcat Administration Server (non-HTTP protocol)
8080 - HTTP Proxy, Alternative HTTP Port
8888 - HTTP Proxy, Alternative HTTP Port
30821 - Netscape Enterprise Server Administration Server









Transactional Webservice in ASP.NET

Transactional Webservice in ASP.NET
=============================


You can make a transactional webservice using dot net


using System;
using System.Data.SqlClient;
using System.Web.Services;
//assembly required for transactional webservice
using System.EnterpriseServices;

public class myWebServiceTransaction {

//data source details
private static string connectionString = "Data Source=(local);Initial Catalog=Northwind;user ID=sa";

//attribute required for webservice transaction
[WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public void webServiceTransaction() {

// Create the connection.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("DELETE * FROM myTable", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();


// database actions are commited if there is no error
}

}

Monday, June 11, 2007

Multi level marketing maths funda

Multi Level Marketing (MLM) a bit of maths for programmers
==============================================


You must have heard about multi-level marketing (MLM). This is just like making members for a particular product/institution etc at multiple levels.Eg: Company has a scheme to sell PC or any item. If the client purchasing pc from the company catch 3 clients then he will get 25% discount. The same is applicable for the clients he has brought.

Here you are required to refer people to the company where they can bye a product / service. The referred people who have taken up the membership continue the trend by referring more members. The members referred can be set at different levels. Generally there can be only one member at level one (root level). At second level there can be three and third level there can be 9.

So at each level there can be (levelxlevel members)

At level 1st (1 members)
At level 2nd (1x3=3 members)
At level 3rd (3x3=9 members)

At level 4th(9x3=27 members)


Sometimes there may be more members at each level (depending on how companies formulate MLM schemes)


(1) -level 1
(2) (3) (4) -level 2
(5)(6)(7) (8)(9)(10) (11)(12)(13) -level3
.........so on..

So while programming a software you must be aware of the some basic maths.

1) At each level there may be (levelxlevel) members
2) If the scheme can posses only 3 members directly under(this is called downlink) a particular node(member) then we can calculat the no within that by a mathematical formula as
([NodeNo x 3] - 1) (NodeNo x 3) ([NodeNo x 3] + 1)




Ex: the following members are under node 3. ([3x3]-1 = 8 , 3x3 = 9 , [3x3]+1 = 10)

You may further enhance the above formula in case where there may be more than 3 members within a node.(downlink)

You must technically achieve the following while building a MLM kind of software:
1)Track members and sub-levels at various levels
2)Dynamically build a tree based on node name (you have to understand the above formula for this)
3)Based on no of members made at each level calculate points gained by each members. Eg: if you get particular no of points you may get a tricycle, Bycycle, mopet, schooter, bike, car and so on....just joking
4)Make n no of reports.




How to loop through a dataset

How to loop throught a dot net dataset
============================



private void printDataSet(DataSet myDataSet)
{
int i = 0;
//looping through a dataset
//you may specify the name of the table (Eg: Ds.Tables["myTableName"].Rows.Count
//instead of myDataSet.Tables[0].Rows.Count
for (i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
//fetch 1st field value in a row
Console.WriteLine(myDataSet.Tables[0].Rows[i][0].ToString());
//fetch 2nd field value in a row. you may also use the alternate syntax as
//myDataSet.Tables[0].Rows[i]["myFieldName"].ToString()

Console.WriteLine(myDataSet.Tables[0].Rows[i][1].ToString());
}
}

Javascript popup window

Code to make a javascript popup window
=============================

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Javascript popup window</title>

</head>
<body>

<a href="mypopuppage.html" onclick="window.open(this.href,'','width=400,height=400,resizable=yes,menubar=yes,scrollbars=yes');return false">Open Me Please</a>
</body>
</html>

Open URL in Browser using C#.NET for windows applications

Open URL in Browser using C#.NET for windows applications
===========================================

using System.Diagnostics;
using Microsoft.Win32;

//Usage: OpenUrl("http://computerbapu.blogspot.com");

//Try to open a url from C#.NET window's code
//Please using the namespace System.Diagnostics to access Process class
public void OpenUrl(string url) {
try
{
string targetURL = url;
Process p = new Process();
//get default browser
p.StartInfo.FileName = getMyDefaultBrowser();
p.StartInfo.Arguments = targetURL;
p.Start();
}
catch (Exception err)
{
MessageBox.Show("Problem : " + err.Message);
}
}



//the below code gets default browser. The entry is stored in the registry.
//To access registry key please use the namespace Microsoft.Win32

private string getMyDefaultBrowser() {
string browser = string.Empty;
RegistryKey myKey = null;
try
{
mykey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);
browser = mykey.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
}
}
finally
{
if (mykey != null) mykey.Close();
}
return browser;
}

Export To Excel using ASP.NET

Export to excel using Asp.net
==================================

In some of the situation you want to generate a excel sheet dynamically from a dataset. This can be easily done as explained below. You need t
//excel init logic
public void generateExcel(){
//connection related stuff
string myConnectionString="Server=(local);uid=sa;pwd=myPassword;database=myDataBaseName";
string mySql="select * from myTable";
SqlConnection myCon= new SqlConnection(myConnectionString);
//data you want to show in your excel sheet
SqlDataAdapter myDataAdapter = new SqlDataAdapter(mySql, myCon);
myCon.Open();

DataSet myDataSet = new DataSet();

myDataAdapter.Fill(myDataSet);
myDataAdapter.FillSchema(myDataSet,SchemaType.Mapped);

//pass a grid object..
DataGrid myDataGrid=new DataGrid();
myDataGrid.DataSource = myDataSet;
myDataGrid.DataBind();
//generation of excel sheet logic
ExportToExcel(myDataGrid,Response);
}


//excel generation logic
private void ExportToExcel(DataGrid dgExport, HttpResponse response ) {
//setting excel content type
response.Clear();
response.Charset = "";
response.ContentType ="application/vnd.ms-excel";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter htmlWrite = new System.Web.UI.Html32TextWriter(stringWrite) ;

DataGrid dg=new DataGrid();
dg=dgExport;
//excel design settings
dg.GridLines =GridLines.None;
dg.HeaderStyle.Font.Bold =true;
dg.HeaderStyle.ForeColor =System.Drawing.Color.Red;
dg.ItemStyle.ForeColor =System.Drawing.Color.Black;
dg.DataBind();
dg.RenderControl(htmlWrite);
response.Write(stringWrite.ToString());
response.End();
}

Transaction Control Language (TCL)

TRANSACTION CONTROL LANGUAGE
------------------------------------------


TRANSACTION:-
Collection of operation that forms a single logical unit of work are called Transactions.
In other words, Transactions are units or sequences of work accomplished in logical order, whether in a manual fashion by a user or automatically by some sort of a database program. In a relational database using SQL, transactions are accomplished using the DML commands, which are already discussed.
A transaction can either be one DML statement or a group of statements. When managing groups of transactions, each designated group of transactions must be successful as one entity or none of them will be successful.

The Following list describes the nature of transactions:
->All transactions have a begining and an end.
->A transaction can be saved or undone.
->If a transaction fails in the middle, no part of the transaction can be saved to the database.

TRANSACTIONAL CONTROL
Transactional control is the ability to manage various transactions that may occur within a relational database management system. (Note keep in mind that transaction is group of DML statements).
When a transaction is executed and completes successfully, the target table is not immediately changed, although it may appear so according to the output. When a transaction successfully completes, there are transactional control commands that are used to finalize the transaction.
There are three commands used to control transactions:
1) COMMIT
2) ROLLBACK
3) SAVEPOINT

When transaction has completed, it is not actually taken changes on database, the changes reflects are temporary and are discarded or saved by issuing transaction control commands. Explanatory figure is drawn as under.



TRANSACTIONAL CONTROL COMMANDS
1) COMMIT
->The commit command saves all transactions to the database since the last COMMIT or ROLLBACK command.
Syntax
commit [work];
The keyword commit is the only mandatory part of the syntax. Keyword work is optional; its only purpose is to make the command more user-friendly.
example
SQL>delete from emp
where emp_age > 75;

->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area. To allow changes permanently on database commit command is used.
SQL> COMMIT WORK;

->The above command will made changes permanently on database, since last commit or rollback command was issued.

NOTE: here work is totally optional, it is just to make command more user friendly.

2) ROLLBACK
->The rollback command is the transactional control command used to undo transactions that have not already been saved to the database. The rollback command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Syntax
SQL>rollback [work];
The keyword rollback is the only mandatory part of the syntax. Keyword work is optional; its only purpose is to make the command more user-friendly.
example
SQL>delete from emp
where emp_age > 75;
->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area. To discards changes made on database rollback command is used.
SQL> ROLLBACK WORK;
->The above command will discards changes made on database,since last commit or rollback command was issued.
note here work is totally optional, it is just to make command more user friendly.

3) SAVEPOINT
->A savepoint is a point in a transaction that you can roll the transaction back to without rolling back the entire transaction.
->Practical example
consider that a person walking and after passing some distance the road is split into two tracks. The person were not sure to choose which track, so before randomly selecting one track he make a signal flag, so that if the track was not the right one he can rollback to signal flag and select the right track. In this example the signal flag becomes the savepoint. figure is as under.

Syntax
SQL>SAVEPOINT
->Savepoint name should be explanatory.
example
->Before deleting the records of employee whose age is above 75, we are not sure that whether we are given work to actually delete the records of employee whose age is above 75yrs or 80yrs. So before proceding further we should create savepoint here if we are been order later than it might create loss of information.
SQL>savepoint orignally;
SQL>delete from emp
where emp_age > 75;
->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area.
->After some time we are given order to increase employee salary to 10%. We can increase by generating following command. But before that we will make savepoint to our data so incase if the top level management change their mind and order's no increment should be given than we have can simply pass rollback entry achieve present state.
SQL>savepoint increm_sal;
SQL>update emp
set salary=salary*10;
->It will Increase salary of employee by 10%.
->After sometime top level management decided that salary of only programmer should be increased by 10% than only we have to do is just to pass entry of rollback before salary is updated.
SQL>rollback to increm_sal;
->It will rollback the changes made to emp_salary now we can update salary records for employee who is programmer. If we have dout than we can put savepoint, otherwise savepoint is not compulsory.
SQL>update emp
set salary=salary*10;
where emp_status='PROGRAMMER';
->It will increase salary of only programmers.
If all the changes have been taken place and now we have decided that no further changes require and we have to made changes to apply on database permanently than we can simply generate commit command to reflect changes permanently on database.
SQL>commit work;

Data Manipulation Language (DML)

DATA MANIPULATION LANGUAGE
------------------------------------------


INTRODUCTION
By data manipulation language we mean:
->The retrieval of information stored in the database.
->The insetion of new information into the database.
->The deletion of information from the database.
->The modification of data stored in the database.
Thus, it is a language that enables users to access or manipulate data as organised by the appropriate data model.
There are basically two types of DML
i>Procedural DMLs
->It requires a user to specify what data is needed and how to get it.
ii>Non-Procedural DMLs
->It requires a user to specify what data is needed without specifying how to get it.
As SQL is Non-Procedural language we will switch on to Non-Procedural DMLs as it is easy to understand and became very efficient for new users to begin with it.
The category of DML contains four basic statements:
i>select - which retrieves rows from a table.
ii>Insert - Which adds rows to a table.
iii>Update - Which modifies existing rows in a table.
iv>Delete - Which removes rows from a table.

SELECT
->To view all rows or some of the rows from a table or more than one table depending upon a userdefined criteria,this command is used.
->By default, select statement display all rows which matches the criteria but we can get the unique records by using keyword distinct with it.
syntax:
SELECT [DISTINCT ALL] FROM
WHERE
->keyword ALL is optional by default it consider ALL rows in table.
example:
1)SQL>select * from emp;
->It will display all rows of emp table including all feilds.we can customize the output by selecting the rows which are needed to us.
2)SQL>select empno,ename from emp;
->It will display all rows of emp table including empno and employee_name detail for an employee.
3)SQL>select * from emp
where
job = 'clerk';
->It will display all details of employee whose status is clerk.
4)SQL>select distinct ename from emp;
->It will display all unique name of employee if employee_name is repeated twice than it will display only ones.Thus it discards the duplicate records.

INSERT
->INSERT command is used to insert one or more rows in a table.
(There are many of syntax for insert command but one mentioned as under is the only standard way to insert multiple rows.)
syntax:-
INSERT INTO (........)
VALUES (<&Fieldname1>......<&FieldnameN>);
->If the Fieldname should be valid field for a table.
->Field having datatype char,varchar2 and Date kind of data should be written in single quota.
examples:
1)SQL>Insert into emp (empno,ename,job)
values ('1','SHREY','MANAGER');
->Above command will insert data for one record, here as data are mentioned directly, so we have made use of single quota.
2)SQL>Insert into emp (empno,job)
values (&empno,'&job');
->Here we have customize the insert command to take data for only two field that is empno and job for multiple records.
->When you don't want to type the command which is used last than simply press the slash to activate the command which is used by you last.
3)SQL>Insert into emp
values (&empno,'&ename','&job');
->Note in Above command we haven't declare the field in which data is to be entered, it is optional when we have to enter data for all fields in column.
4)SQL>Insert into emp (empno,ename,job)
values ('5','VRAJ',NULL);
->The above command will create a row and assign value 5 for empno and vraj for ename and leave the column job.
->If we doesn't want to enter value for a particular field we can just type NULL in it place during defining the INSERT command. And just press enter while entering the value.
5)SQL>Insert into emp_bkup
(select * from emp);
->The above command will copies all the rows from table emp and insert it into the table emp_bkup, provided that the structure of emp and emp_bkup is same.
->The above command is efficient to run when we want to create backup copy of our data.

UPDATE
->Update command is used to modify content of table, that to under satisfaction of particular criteria.
syntax:
UPDATE
SET =
WHERE ;
->Where Clause is optional.
->Fieldname is name of column whose contents are to be manipulated.
example:
1)SQL>Update emp
set job = 'ACCOUNTANT'
where job = 'MUNIM';
->Above sql statement will Modify Job field for employee whose status is munim, it will update the status munim with accountant.
2)SQL>Update emp
set salary = salary * 10
where job = 'PROGRAMMER';
->Above statement will increase salary of employee by 10% whose status is programmer.

DELETE
->DELETE command is used to delete one or more rows from the table.
Note:-No warnings are given before deleting rows so be careful while performing this operation.
syntax:
DELETE FROM
WHERE
;
->Table_name is name of table from which you want to delete record/s.
->Criteria is condition under which you want to delete record/s.
example:
1)SQL>Delete from emp
Where empno = 4;
->Above statement remove record of empno 4.
->Only one record is deleted.
2)SQL>Delete from emp
Where job = 'OPERATOR';
->Above statement remove record/s of those employee whose status is operator in the company.

Data Definition Language (DDL)

DATA DEFINITION LANGUAGE (DDL)
--------------------------------------------------------------------------------


INTRODUCTION
A database scheme is specified by a set of definition which are expressed by a special language called a Data Definition Language. The result of compilation of DDL statement is a set of tables which are stored in a special file called Data Dictionary.
-> DDL defines the structure of data.
-> DDL statements in SQL language are responsible for creating or modifying database structures such as tables, views, and indexes.

Let us now understand DDL statements and how it works on Oracle database.

TABLE
(A table consist of Rows and Columns. Table is a collection of related records that are treated as a unit. )
Convention for Naming a Table in Oracle
-> Each table owned by a Oracle account must have a unique name.
-> A table name cannot exceed 30 characters in length.
-> A table name must begin with an alphabetic character.
-> A table name can contain the letters A through Z, the digits 0 through 9, and the characters $, #, and _(underscore).
-> A table name cannot be an SQL reserved word.
-> You can use uppercase and lowercase characters in naming tables; oracle is not case sensitive as long as table or column names are not enclosed in double quotes.
-> A table name should be descriptive.
Convention for Naming Column in Oracle.
-> Within a single table, a column name must be unique. However, you may use the same column name in different tables.
-> Like other database objects, a column name can be upto 30 characters long.
-> The column name must begin with an alphabetic character.
-> The column name can contain the letters A through Z, the digits 0 through 9, and the characters $, #, and _(underscore). The name cannot include spaces.
-> A column name cannot be an SQL reserved word.
-> As with tables, be descriptive in naming a column. Descriptive column names help users understand the definition of each column.
-> An Oracle table may have upto 254 columns.
Commands Related To Table
1) Syntax to CREATE Table
CREATE TABLE
(
[column level constraint],
:
:
,
[Table level constraint]
);

Here,
-> Table_name is the name for the table.
-> Column_name1 through Column_nameN are valid column names.
-> Datatypes is a valid Oracle datatype specification.
-> Constraint_name is a optional, but it should be used in order to avoid invalid information to be entered in the database.

NOTE:-you can assign default value for field by using the keyword default and specifying default value for that field.
eg:-city varchar2(25) default 'AHMEDABAD'
(Though SQL is not case sensitive, but contents of table are case sensitive so it is good practise to write data always in uppercase).
Tip - CHAR, VARCHAR AND DATE kind of data should be written in single quota.
example
sql> create table emp
(
emp_no number (6) primary key,
emp_name varchar2(35),
emp_address varchar2(45),
emp_city varchar2(30),
emp_state varchar2(30),
emp_age number(2),
emp_sex char,
emp_department varchar2(30)
);

Table created.

2) Describe Table
-> This command will describe the table.
Syntax for describing table
sql> desc ;
or
sql> describe ;
example
sql> desc emp;

3) ALTER Table
-> Alter command is used to make modification after table has created.
-> Modification like to add column, to drop constraint like primary key,etc., However you cannot delete the column or you can decrease the width of column.
Syntax to ALTER Table definition
ALTER TABLE
[ADD MODIFY DROP]
( ,
:
:
);
examples
-> To Add column in a table.
sql> alter table emp
add
(emp_phno number(10));
-> To Modify Table
sql> alter table emp
modify
(
emp_city varchar2(35),
emp_state varchar2(35)
);
-> To Drop Table's Primary key and other constraints.
general syntax
ALTER TABLE
[DROP ENABLE DISABLE]
CONSTRAINT ;
sql> alter table emp
drop primary key;
After successfully completion of above command you get the message table altered.

4) Command to Delete contents of Table
TRUNCATE
-> Truncate command will delete all the table contents by removing all the rows(records) from the table.
-> After the implementation of this command, only the structure of the table remains.
Syntax for Truncate command
sql> TRUNCATE TABLE ;
example
sql> truncate table emp;
-> It will delete all the rows of the emp table and only structure of the table remains.
5) Command to Delete Table
DROP
-> Drop command will delete the table contents and its structure.
Syntax for Drop command
sql> DROP TABLE ;
example
sql> drop table emp;
-> It will delete all the rows and the structure of emp table.

INTEGRITY CONSTRAINTS
An Integrity constraint is a trick used by oracle to prevent invalid data entry into the table. It is only a rules applied to restrict user to enter particular value. It prevent this by defining it at column-level or table-level constraint. The main difference between both is that column-level constraint is defined at the column level and cannot reference by any other columns in the table. A table-level constraint is defined at the table level and can reference to any of the table's columns.

NOTE:-not null and check constraint cannot be defined as table-level constraint.

Integrity constraint are categorized into three types they are as under
1) Domain Integrity Constraints
2) Entity Integrity Constraints
3) Referential Integrity Constraint.

I) DOMAIN INTEGRITY CONSTRAINTS
-> Domain integrity constraint Prevent invalid data entry by enforcing rules like NOT NULL and CHECK on the column.

NOT NULL
->By default, every column can contain null value. But, If we want to restrict the user to enter the value at any cost we should put not null constraint.
->In other words, not null field should always contains value.
example
create table emp
(
empno number(4) constraint ntnl not null,
ename varchar2(25),
job varchar2(25)
);
->here empno is column-level constraint and after implementation of the above command while user want to enter the value, he must have to enter empno. ntnl is the constraint name.

CHECK
-> check constraint is used to match the enter data with predifined criteria during designing of table.
-> As it check for predifined criteria it stops the invalid user to do mischief with the database.
-> Thus it helps in making database consistent by feeding reliable information.
example
create table emp
(
empno number(4) constraint ntnl not null,
ename varchar2(25),
job varchar2(25) constraint check(job in('clerk','manager'))
);
->here check constraint will look for job in clerk or manager and if enduser try's to enter job for another category an error code for it will be generated by sql.

II) ENTITY INTEGRITY CONSTRAINTS
-> Entity integrity constraint Prevent invalid data entry by enforcing rules like UNIQUE and PRIMARY KEY on the column.

UNIQUE
-> Unique constraint allowed null values, but it does not allowed duplicate values.
-> It may be composite upto 16 columns.
example
create table emp
(
empno number(4),
ename varchar2(25),
job varchar2(25),
constraint unino unique(empno)
);
->here unino is constraint name for table-level constraint definition and constraint unique is applied to empno, so after execution of above command user can enter only unique value or may not enter the value.

PRIMARY KEY
-> A primary key is a field that uniquely identifies each records in a table.
-> It should neither be duplicate nor null.
-> It may be composite upto 16 columns.
example
create table emp
(
empno number(4) constraint pkno primary key ,
ename varchar2(25),
job varchar2(25)
);
->here Primary key is created for empno so it will alone identifies each records in a table. pkno is again a constraint name for column-level definition of constraint.

III) REFRENTIAL INTEGRITY CONSTRAINTS
-> To establish a 'parent-child' or a 'master-details' relationship between two tables of a same database having a common column, we make use of referential integrity constraints. To implement this, we should define the column in the parent table as a primary key and the same column in the child table as a foreign key referring to the corresponding parent entry.
->foreign key is a column or combination of column which refers to primary key of primary table.
example
create table emp
(
empno number(4) constraint pkno primary key ,
ename varchar2(25),
job varchar2(25)
);

create table education_detail
(
empno number(4) ,
degree varchar2(30),
foreign key (empno) references emp(empno)
);

-> here emp table contains the details of the employee while education_detail table consist of their achived degree's by their no. one-to-many relationship is formed here. As one employee have many degree's and even few employee have no degree's.

ON CASCADE DELETE
-> It is special facilty through which we can ensure that the row deleted in the master table will automatically deletes the row in the reference table.
for example if we have records of employee details than after deleting any one of their record will automatically deletes the corresponding entry in the reference table.
example
create table education_detail
(
empno number(4) references emp(empno) on-delete-cascade,
degree varchar2(30)
);

Database keys

Database keys

================

1) PRIMARY KEY:-

A primary key is a field that uniquely identifies each record in a table. As it uniquely identify each entity, it cannot contain null value and duplicate value.
eg:-Consider the customer table, which has field :customer_number, customer_socialsecurity_number, and customer_address.here customer_number of each entity in customer table is distinct so customer-number can be a primary key of customer-table.

2) CANDIDATE KEY:-

A nominee's for primary key field are know as candidate key.
eg:-From above example of customer table, customer_socialsecurity_number is candidate key as it has all characteristics of primary key.

3) ALTERNATE KEY:-

A candidate key that is not the primary key is called an Alternate key.
eg:- In above example, customer_socialsecurity_number is a candidate key but not a primary key so it can be considered as alternate key.


4) COMPOSITE KEY:-

Creating more than one primary key are jointly known as composite key.
eg:-In above example, if customer_number and customer_socialsecurity_number are made primary key than they will be jointly known as composite key. In addition the combination of customer_number and customer_socialsecurity_number is unique.

5) FOREIGN KEY:-

Foreign key is a primary key of master table, which is reference in the current table, so it is known as foreign key in the current table. A foreign key is one or more columns whose value must exist in the primary key of another table.
eg:-Consider two tables emp(contains employees description) and emp_edu(contains details of employee's education), so emp_id which is primary key in emp table will be referred as foreign key in emp_edu table.

Backup Ms Sql Server Database using bat file

--Sometimes you may require a bat file to backup your ms sql server database.

@echo off
echo "Please press a key to backup you sql database.."
pause
echo "Backup process has started....This will take few minutes"
osql -U yourSqlUserName -P yourSqlPassword -Q "BACKUP DATABASE DatabaseName TO DISK = '%CD%\DatabaseName.BAK'"

pause

echo "You have Successfully Backup Up ... press a key to quit"
pause




--You might also want to restore your ms sql server database.

@echo off
echo "First Dropping your database if it exist... press a key"
pause
osql -U yourSqlUserName -P yourSqlPassword -Q "Drop Database DatabaseName"
echo "Restoring database ... press a key"
pause
osql -U yourSqlUserName -P yourSqlPassword -Q "RESTORE DATABASE DatabaseName FROM DISK = '%CD%\DatabaseName.BAK'"


echo "Restoring done ... press a key to quit"
pause

Saturday, June 9, 2007

Playing wav file using C#.NET 2.0.

Playing wav file using C#.NET 2.0.
==================================

The below code is self explainatory.

public void playWavFile() {
System.Media.SoundPlayer wavPlayer = new System.Media.SoundPlayer();
wavPlayer.SoundLocation = @"c:\click.wav";
wavPlayer.Play();
}


Also you can play some system sounds

public void playSystemSounds() {
SystemSounds.Beep.Play();
SystemSounds.Asterisk.Play();
SystemSounds.Exclamation.Play();
SystemSounds.Hand.Play();
SystemSounds.Question.Play();
}



Also the sound related classes include:

Microsoft.VisualBasic.Devices.Audio.Play Method
System.Media.SoundPlayer Class
System.Media.SoundPlayer.Play Method
System.Media.SoundPlayer.PlayLooping Method
System.Media.SoundPlayer.PlaySyncMethod

Thursday, June 7, 2007

Closing Database Connection In Dot NET 2.0.

Closing Database Connection In Dot NET 2.0.
===========================================


Its recommended to close connection after you utilize the resource. This was not done before (especially during the age of VB and other old application). Previously opening and closing the connection was more resource consuming hence during application startup connection was opened (As in visual basic sub main function) and it was only closed during application closure. Hence whenever application starts connection remains open even if use isn't doing anything. The major problem in keeping the connection open is...since database allows limited no of connections hence keeping the connection open without performing any database operations/actions would just waste resource. In addition when the no of connections reaches the limit it won't allow other connection to open....

Eg: This is just like storing gold ornaments without wearing it.

Hence computer scientist have come up with a new idea which is called connection pooling. Connection pooling is just like a shared connection, where database connections are created and held in a pool. A pool is created when certain connections remain open for utilization by various sessions. Whenever any application requires a connection, the provider extracts the next available connection from the pool. (Whenever a open method is called directly available connection is taken from the pool. Hence there is no resource over head at all)

Also as soon as the application closes the connection, it is returned to the pool and made available for the next application that requires connectivity. Hence opening and closing connection is just like taking charge of the resource that's it!!..hence its recommended to open the connection whenever you need it and close it as soon as you don't require it..This facilitates optimal utilization of connection resource.

Eg: This is just like sharing your gold ornaments with other relatives.


Sample connection string in dot net:
connectionString="Data Source=localhost;Initial Catalog=MyDatabase;Integrated Securing=SSPI;Min Pool Size=10";

Some of the connection string settings include:

Max Pool Size : Max No of connection allowed in the pool (default is 100)
Min Pool Size : Min No of connection retained in the pool (default is 0). The no of connections will be created when the first connection is opened, leading to a minor delay for the first request.
Pooling: When true(default), the connection is drawn from the approiate pool or if necessary is created and added to the appropriate pool
Connection Lifetime: Specifies a time interval in seconds. If a connection is returned to the pool and its creation time is older than the specified lifetime, it will be destroyed. The default is 0.(disable). This feature is useful when you want to recycle a large no of connections at once.

Also programatically you can clear pool by using methods like:
ClearPool()
ClearAllPools()

The above may be necessary when pool is full with unnecessary connections.


Provider independent connectivity code for dot net 2.0.

Provider independent connectivity code for dot net 2.0.
=======================================================


Make sure you use common namespace.

//Abstract ADO.NET Class
using System.Data.Common;

public DataSet getMyDS(string APINamespace, string Sql){
DbProviderFactory provider=DbProviderFactories.GetFactory(APINamespace);
DbConnection myConnection=provider.CreateConnection();


//you may dynamically pass connection string or pick it up from config file
myConnection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;User ID=sa;password=admin;";
myConnection.Open();

DbDataAdapter myAdapter = provider.CreateDataAdapter();
DbCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = Sql;
myAdapter.SelectCommand = myCommand;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
myConnection.Close();
return myDataSet;
}

//You can call the above function as shown below

myDataGrid.DataSource = getMyDS("System.Data.SqlClient","select categoryname from categories").Tables[0].DefaultView;


// Prime provider classes of System.Data.Common
// DbConnection - to establish connection
// DbCommand - for quering to data source eg: update/select/delete sql statements
// DbDataReader - It is readonly/forwardonly access to datasource
// DbAdapter - It acts as a channel to connect to datasource ( i.e. dataset connects to
datasource)

Wednesday, June 6, 2007

create pop up window in ASP.NET

You may call the below function to create popup window at runtime

public void PopUp(string url){

string myPopup = "<script language='javascript'>" + "window.open('" + url + "', 'CustomPopUp', " + "'width=200, height=200, resizable=no')" + "</script>";


Page.RegisterStartupScript("Popup", myPopup);


}

Enable / Disable Firewall Programatically using VBScript/C#

'VbScript Code to enable firewall
objFirewall = CreateObject("HNetCfg.FwMgr")
Set objPolicy = objFirewall.LocalPolicy.CurrentProfile
objPolicy.FirewallEnabled = TRUE

'VbScript Code to enable firewall
objFirewall = CreateObject("HNetCfg.FwMgr")
Set objPolicy = objFirewall.LocalPolicy.CurrentProfile
objPolicy.FirewallEnabled = FALSE

'You may want to call the above code using C# - The below code just try to make a vbs file at runtime using C# and calls it.


public void enableFirewall(){
try {
string filename=Application.StartupPath + "\\" + "firewall.vbs";
string enableFirewallScript="Set objFirewall = CreateObject(\"HNetCfg.FwMgr\") ";
enableFirewallScript=enableFirewallScript + "\n" + "Set objPolicy=objFirewall.LocalPolicy.CurrentProfile" + "\n";
enableFirewallScript=enableFirewallScript + "objPolicy.FirewallEnabled = TRUE" + "\n";
enableFirewallScript=enableFirewallScript + "MsgBox(\"Firewall Enabled\")";
CreateVBS("firewall.vbs",enableFirewallScript);try {
System.Diagnostics.Process.Start(@filename);
}
catch {
MessageBox.Show("Can't access Firewall","Alert!",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}}
catch {}
}