Wednesday, June 24, 2009

Update in Repeater



Code

public partial class Default2 : System.Web.UI.Page
{
Button b1, b2, b3;
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=abhishek;Persist Security Info=True;uid=sa;pwd=com");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
bindgrid();
}


}

public void bindgrid()
{
SqlDataAdapter da = new SqlDataAdapter("select * from ab", conn);
DataSet ds = new DataSet();
da.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
TextBox t1, t2;
if (e.CommandName =="Edit")
{
t1 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("id1");
t2 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("name");
t1.ReadOnly = false;
t2.ReadOnly = false;

b1 = (Button)e.Item.FindControl("b1");
b1.CommandName = "update";
b1.Text = "update";

}
else if (e.CommandName == "update")
{
t1 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("id1");
t2 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("name");
int i = int.Parse(t1.Text);


cmd.Connection = conn;
conn.Open();
cmd.CommandText="update ab set name='"+t2.Text+"' where id ='"+i+"'";
cmd.ExecuteNonQuery();
Repeater1.DataBind();
conn.Close();
bindgrid();



}
if (e.CommandName == "Insert")
{
b3 = (Button)e.Item.FindControl("b3");
b3.Text = "save";
t1 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("id1");
t2 = (TextBox)Repeater1.Items[e.Item.ItemIndex].FindControl("name");
t1.ReadOnly = false;
t2.ReadOnly = false;
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "insert into ab values('" + t1.Text + "','" + t2.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
bindgrid();

}
}




Code

Monday, June 22, 2009

Uploading and Storing Images to Database in ASP.NET

STEP1: Creating the Database.



The following are the basic steps on how to create a simple database in the Sql Server:



1. Launch Sql Server Management Studion Express and then connect
2. Expand the Databases folder from the Sql Server object explorer
3. Right click on the Databases folder and select “New Database”
4. From the pop up window, input the database name you like and click add
5. Expand the Database folder that you have just added
6. Right click on the Tables folder and select “New Table”
7. Then add the following fields below:





Note: in this demo, I set the Id to auto increment so that the id will be automatically generated for every new added row. To do this select the Column name “Id” and in the column properties set the “Identity Specification” to yes.



Then after adding all the necessary fields, name your Table the way you like. Note that in this demo I name it “TblImages”
STEP2: Setting up the WebForm (UI)



For the simplicity of this demo, I set up the UI like this below:






STEP3: Setting up the Connection String



In your webconfig file set up the connection string there as shown below:






providerName="System.Data.SqlClient" />





Note: MyConsString is the name of the Connection String that we can use as a reference in our codes for setting the connection string later.



STEP4: Writing the codes for Saving the binary image to Database.



Here are the code blocks below:



private void StartUpLoad()

{

//get the image file that was posted (binary format)

byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];

HttpPostedFile Image = FileUpload1.PostedFile;

Image.InputStream.Read(theImage, 0, (int)FileUpload1.PostedFile.ContentLength);

int length = theImage.Length; //get the length of the image

string fileName = FileUpload1.FileName.ToString(); //get the file name of the posted image

string type = FileUpload1.PostedFile.ContentType; //get the type of the posted image

int size = FileUpload1.PostedFile.ContentLength; //get the size in bytes that

if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")

{

//Call the method to execute Insertion of data to the Database

ExecuteInsert(theImage, type, size, fileName, length);

Response.Write("Save Successfully!");

}

}

public string GetConnectionString()

{

//sets the connection string from your web config file "ConnString" is the name of your Connection String

return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;

}



private void ExecuteInsert(byte[] Image, string Type, Int64 Size, string Name, int length)

{

SqlConnection conn = new SqlConnection(GetConnectionString());



string sql = "INSERT INTO TblImages (Image, ImageType, ImageSize, ImageName) VALUES "

+ " (@img,@type,@imgsize,@imgname)";

try

{

conn.Open();

SqlCommand cmd = new SqlCommand(sql, conn);

SqlParameter[] param = new SqlParameter[4];



//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);

param[0] = new SqlParameter("@img", SqlDbType.Image, length);

param[1] = new SqlParameter("@type", SqlDbType.NVarChar, 50);

param[2] = new SqlParameter("@imgsize", SqlDbType.BigInt, 9999);

param[3] = new SqlParameter("@imgname", SqlDbType.NVarChar, 50);



param[0].Value = Image;

param[1].Value = Type;

param[2].Value = Size;

param[3].Value = Name;



for (int i = 0; i < param.Length; i++)

{

cmd.Parameters.Add(param[i]);

}



cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}

catch (System.Data.SqlClient.SqlException ex)

{

string msg = "Insert Error:";

msg += ex.Message;

throw new Exception(msg);



}

finally

{

conn.Close();

}

}

protected void Page_Load(object sender, EventArgs e)

{



}

protected void Button1_Click(object sender, EventArgs e)

{

StartUpLoad();

}



StartUpload() is method that gets all the necessary information from the uploaded file such as the image length, size, type, filename and the image itself in a binary format.



GetConnectionString() is a method that returns the connection string that was set up from the web.config file.



ExecuteInsert() is a method that will executes the insertion of data to the database. This method takes all the necessary data to be inserted in the database.



As you can see the code above is pretty straight forward and self explanatory…

Check out my next example about "Displaying Image to Image Control based on User Selection in ASP.NET"

That’s it! Hope you will find this example useful!

Saturday, June 20, 2009

Converting Excel file into Xml

You can Easily convert Excel Sheet into Xml File by One Click
I am Writing That code Here.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim Str As String = Nothing
Dim src, src2 As String
src = txtExcel.Text// name of .xls File
src2 = txtTablename.Text//name Excel Sheet it take multiple sheet name with seprated by comma




Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & src & ";Extended Properties=Excel 8.0;"//connecting to Excel
Dim stringItems() As String = src2.Split(",")

Dim count As Integer
For count = 0 To stringItems.Length - 1

Dim dx As New DataSet()

Dim DA As New OleDb.OleDbDataAdapter()
Dim DS As New DataSet()

Dim str2 As String
str2 = "$"
Dim objConn As New OleDb.OleDbConnection(Str)
Dim scomman As String = "select * from [" + stringItems(count) + "$]"
Dim ada As New OleDbDataAdapter(scomman, objConn)

ada.Fill(dx, "transport")

Dim doc As New XmlDataDocument(dx)
doc.Save("C:\" + stringItems(count) + ".xml")

Next

MsgBox("Xml Files Created", MsgBoxStyle.Information, "Xml Converter")


End Sub

Tuesday, June 16, 2009

Javascript Validation

function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}

Friday, June 12, 2009

Network engineer interview questions

Network engineer interview questions
OSPF

* Describe OSPF in your own words.
* OSPF areas, the purpose of having each of them
* Types of OSPF LSA, the purpose of each LSA type
* What exact LSA type you can see in different areas
* How OSPF establishes neighboor relation, what the stages are
* If OSPF router is stucked in each stage what the problem is and how to troubleshoot it
* OSPF hierarchy in the single or multi areas. Cool OSPF behavior in broadcast and nonbroadcast
* Draw the diagram of typical OSPF network and explain generally how it works, DR, BDR, election, ASBR, ABR, route redistribution and summarization

STP

* How it works and the purpose
* Diff types (SSTP, MSTP, RSTP) Cisco - PVST/PVST+
* root election
* Diff. port stages and timing for convergence
* Draw the typical diagram and explain how diff types of STP work
* What ports are blocking or forwarding
* How it works if there are topology changes

ACLs

* What are they
* Diff types
* Write an example if you want to allow and to deny…
* Well-known port numbers (DNS - 53 and etc…)

QOS

* What is that
* What is the diff b/w L2 and L3 QoS
* How it works

Network:

* Draw the typical network diagram you have to deal with
* explain how it works
* What part of it you are responsible
* firewall, what is that, how it works, how it is diff from ACLs
* What problems with the network you had had and how you solved it.
* What are the ways to troubleshoot the network, techniques, commands
* network security, ways to achieve it

Switching:

* VLANs
* STP
* How a L2 switch works with broadcast, unicast, multicast, known/unknown traffic
* VRRP, GLBP
* port monitoring and mirroring
* L3 switch, how it works
* PIM sparse and dense modes


^Back to Top
Windows admin interview questions

1. Describe how the DHCP lease is obtained. It’s a four-step process consisting of (a) IP request, (b) IP offer, © IP selection and (d) acknowledgement.
2. I can’t seem to access the Internet, don’t have any access to the corporate network and on ipconfig my address is 169.254.*.*. What happened? The 169.254.*.* netmask is assigned to Windows machines running 98/2000/XP if the DHCP server is not available. The name for the technology is APIPA (Automatic Private Internet Protocol Addressing).
3. We’ve installed a new Windows-based DHCP server, however, the users do not seem to be getting DHCP leases off of it. The server must be authorized first with the Active Directory.
4. How can you force the client to give up the dhcp lease if you have access to the client PC? ipconfig /release
5. What authentication options do Windows 2000 Servers have for remote clients? PAP, SPAP, CHAP, MS-CHAP and EAP.
6. What are the networking protocol options for the Windows clients if for some reason you do not want to use TCP/IP? NWLink (Novell), NetBEUI, AppleTalk (Apple).
7. What is data link layer in the OSI reference model responsible for? Data link layer is located above the physical layer, but below the network layer. Taking raw data bits and packaging them into frames. The network layer will be responsible for addressing the frames, while the physical layer is reponsible for retrieving and sending raw data bits.
8. What is binding order? The order by which the network protocols are used for client-server communications. The most frequently used protocols should be at the top.
9. How do cryptography-based keys ensure the validity of data transferred across the network? Each IP packet is assigned a checksum, so if the checksums do not match on both receiving and transmitting ends, the data was modified or corrupted.
10. Should we deploy IPSEC-based security or certificate-based security? They are really two different technologies. IPSec secures the TCP/IP communication and protects the integrity of the packets. Certificate-based security ensures the validity of authenticated clients and servers.
11. What is LMHOSTS file? It’s a file stored on a host machine that is used to resolve NetBIOS to specific IP addresses.
12. What’s the difference between forward lookup and reverse lookup in DNS? Forward lookup is name-to-address, the reverse lookup is address-to-name.
13. How can you recover a file encrypted using EFS? Use the domain recovery agent.


^Back to Top

Read more at TechInterviews.com
Network engineer/architect interview questions

1. Explain how traceroute, ping, and tcpdump work and what they are used for?
2. Describe a case where you have used these tools to troubleshoot.
3. What is the last major networking problem you troubleshot and solved on your own in the last year?
4. What LAN analyzer tools are you familiar with and describe how you use them to troubleshoot and on what media and network types.
5. Explain the contents of a routing table (default route, next hop, etc.)
6. What routing protocols have you configured?
7. Describe the commands to set up a route.
8. What routing problems have you troubleshot?
9. How do you display a routing table on a Cisco? On a host?
10. How do you use a routing table and for what?
11. What is a route flap?
12. What is a metric?
13. When do you use BGP, IGRP, OSPF, Static Routes?
14. What do you see as current networking security issues (e.g. NFS mounting, spoofing, one time passwords, etc.)?
15. Describe a routing filter and what it does.
16. Describe an access list and what it does.
17. What is a network management system?
18. Describe how SNMP works.
19. Describe the working environment you are currently in, e.g. frequent interruptions, frequent priority shifting, team or individual.
20. What do you use to write documentation? Editor? Mail reader?
21. What platform (s) do you currently work on at your desk?
22. How do you manage multiple concurrent high level projects?
23. Describe a recent short term stressful situation and how you managed it.
24. How do you manage a long term demanding stressful work environment?
25. Have you worked in an assignment based environment, e.g. work request/trouble ticket system, and if so, describe that environment.
26. Describe what network statistics or measurement tools you are familiar with and how you have used them.
27. Describe what a VPN is and how it works.
28. Describe how VoIP works.
29. Describe methods of QoS.
30. How does ToS bit work?


^Back to Top
CCNA/Cisco admin interview questions

1. You need to retrieve a file from the file server for your word processing application, which layer of the OSI model is responsible for this function?
1. Presentation layer
2. Application layer
3. Session layer
4. Transport layer
5. Datalink layer
2. You are working in a word processing program, which is run from the file server. Your data comes back to you in an unintelligible manner. Which layer of the OSI model would you investigate?
1. Application layer
2. Presentation layer
3. Session layer
4. Network layer
5. Datalink layer
3. The IEEE subdivided the datalink layer to provide for environments that need connectionless or connection-oriented services. What are the two layers called?
1. Physical
2. MAC
3. LLC
4. Session
5. IP
4. You are working with graphic translations. Which layer of the OSI model is responsible for code formatting and conversion and graphic standards.
1. Network layer
2. Session layer
3. Transport layer
4. Presentation layer
5. Which is the best definition of encapsulation?
1. Each layer of the OSI model uses encryption to put the PDU from the upper layer into its data field. It adds header and trailer information that is available to its counterpart on the system that will receive it.
2. Data always needs to be tunneled to its destination so encapsulation must be used.
3. Each layer of the OSI model uses compression to put the PDU from the upper layer into its data field. It adds header and trailer information that is available to its counterpart on the system that will receive it.
4. Each layer of the OSI model uses encapsulation to put the PDU from the upper layer into its data field. It adds header and trailer information that is available to its counterpart on the system that will receive it.
6. Routers can be configured using several sources. Select which of the following sources can be used.
1. Console Port
2. Virtual Terminals
3. TFTP Server
4. Floppy disk
5. Removable media
7. Which memory component on a Cisco router contains the dynamic system configuration?
1. ROM
2. NVRAM
3. Flash
4. RAM/DRAM
8. Which combination of keys will allow you to view the previous commands that you typed at the router?
1. ESC-P
2. Ctrl-P
3. Shift-P
4. Alt-P
9. Which commands will display the active configuration parameters?
1. show running-config
2. write term
3. show version
4. display term
10. You are configuring a router, which prompt tells you that you are in the privileged EXEC mode?
1. @
2. >
3. !
4. :
5. #
11. What does the command “IP name-server 255.255.255.255″ accomplish?
1. It disables domain name lookup.
2. It sets the domain name lookup to be a local broadcast.
3. This is an illegal command.
4. The command is now defunct and has been replaced by “IP server-name ip any”
12. The following selections show the command prompt and the configuration of the IP network mask. Which two are correct?
1. Router(config-if)#netmask-format { bitcount | decimal | hexadecimal }
2. Router#term IP netmask-format { bitcount | decimal | hexadecimal }
3. Router(config-if)#IP netmask-format { bitcount | decimal | hexadecimal }
4. Router#ip netmask-format { bitcount | decimal | hexadecimal }
13. Which layer is responsible for flow control with sliding windows and reliability with sequence numbers and acknowledgments?
1. Transport
2. Application
3. Internet
4. Network Interface
14. Which processes does TCP, but not UDP, use?
1. Windowing
2. Acknowledgements
3. Source Port
4. Destination Port
15. Select which protocols use distance vector routing?
1. OSPF
2. RIP
3. IGRP
4. PPP


^Back to Top

Read more at TechInterviews.com
Networking and Unix interview questions

What is UTP?

UTP — Unshielded twisted pair 10BASE-T is the preferred Ethernet medium of the 90s. It is based on a star topology and provides a number of advantages over coaxial media:

It uses inexpensive, readily available copper phone wire. UTP wire is much easier to install and debug than coax. UTP uses RG-45 connectors, which are cheap and reliable.

What is a router? What is a gateway?

Routers are machines that direct a packet through the maze of networks that stand between its source and destination. Normally a router is used for internal networks while a gateway acts a door for the packet to reach the ‘outside’ of the internal network

What is Semaphore? What is deadlock?

Semaphore is a synchronization tool to solve critical-section problem, can be used to control access to the critical section for a process or thread. The main disadvantage (same of mutual-exclusion) is require busy waiting. It will create problems in a multiprogramming system, where a single CPU is shared among many processes.

Busy waiting wastes CPU cycles.

Deadlock is a situation when two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes. The implementation of a semaphore with a waiting queue may result in this situation.

What is Virtual Memory?

Virtual memory is a technique that allows the execution of processes that may not be completely in memory. A separation of user logical memory from physical memory allows an extremely large virtual memory to be provided for programmers when only a smaller physical memory is available. It is commonly implemented by demand paging. A demand paging system is similar to a paging system with swapping. Processes reside on secondary memory (which is usually a disk). When we want to execute a process, we swap it into memory.

Explain the layered aspect of a UNIX system. What are the layers? What does it mean to say they are layers?

A UNIX system has essentially three main layers:

. The hardware

. The operating system kernel

. The user-level programs

The kernel hides the system’s hardware underneath an abstract, high-level programming interface. It is responsible for implementing many of the facilities that users and user-level programs take for granted.

The kernel assembles all of the following UNIX concepts from lower-level hardware features:

. Processes (time-sharing, protected address space)

. Signals and semaphores

. Virtual Memory (swapping, paging, and mapping)

. The filesystem (files, directories, namespace)

. Pipes and network connections (inter-process communication)

C++ code job interviews

: Write a short code using C++ to print out all odd number from 1 to 100 using a for loop(Asked by Intacct.com people)

for( unsigned int i = 1; i < = 100; i++ )
if( i & 0x00000001 )
cout << i<<\",\";

ISO layers and what layer is the IP operated from?( Asked by Cisco system people)

cation, Presentation, Session, Transport, Network, Data link and Physical. The IP is operated in the Network layer.

3.Q: Write a program that ask for user input from 5 to 9 then calculate the average( Asked by Cisco system people)

A.int main()
{
int MAX=4;
int total =0;
int average=0;
int numb;
cout<<"Please enter your input from 5 to 9";
cin>>numb;
if((numb <5)&&(numb>9))
cout<<"please re type your input";
else
for(i=0;i<=MAX; i++)
{
total = total + numb;
average= total /MAX;
}
cout<<"The average number is">>average<
return 0;
}

4.Q: Can you be bale to identify between Straight- through and Cross- over cable wiring? and in what case do you use Straight- through and Cross-over? (Asked by Cisco system people)

A. Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switched

We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

5.Q: If you hear the CPU fan is running and the monitor power is still on, but you did not see any thing show up in the monitor screen. What would you do to find out what is going wrong? (Asked by WNI people)

A. I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

^Back to Top
C++ object-oriented interview questions

1. How do you write a function that can reverse a linked-list? (Cisco System)

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur->next = head;

for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}

curnext->next = cur;
}
}

2. What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

4. How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

5. What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:

* a->b is a trivial functional dependency (b is a subset of a)
* a is a superkey for schema R


^Back to Top
Interview questions on C/C++

A reader submitted the interview questions he was asked. More C/C++ questions will be added here, as people keep sending us a set of 2-3 questions they got on their job itnerview.

Q1: Tell how to check whether a linked list is circular.

A: Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}

Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

How can you quickly find the number of elements stored in a a) static array b) dynamic array ?

Why is it difficult to store linked list in an array?

How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

This is a C question that I had for an intern position at Microsoft: Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique. After I wrote out my function, he asked me to figure out from the code how many times the printf statement is run, and also questions on optimizing my algorithm.

What’s the output of the following program? Why?

#include
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Union;

Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;

printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)

What is output equal to in

output = (X & Y) | (X & Z) | (Y & Z)


^Back to Top
C++ gamedev interview questions

This set of questions came from a prominent gaming company. As you can see, the answers are not given (the interviews are typically conducted by senior developers), but there’s a set of notes with common mistakes to avoid.

1. Explain which of the following declarations will compile and what will be constant - a pointer or the value pointed at:
* const char *
* char const *
* char * const

Note: Ask the candidate whether the first declaration is pointing to a string or a single character. Both explanations are correct, but if he says that it’s a single character pointer, ask why a whole string is initialized as char* in C++. If he says this is a string declaration, ask him to declare a pointer to a single character. Competent candidates should not have problems pointing out why const char* can be both a character and a string declaration, incompetent ones will come up with invalid reasons.
2. You’re given a simple code for the class BankCustomer. Write the following functions:
* Copy constructor
* = operator overload
* == operator overload
* + operator overload (customers’ balances should be added up, as an example of joint account between husband and wife)

Note:Anyone confusing assignment and equality operators should be dismissed from the interview. The applicant might make a mistake of passing by value, not by reference. The candidate might also want to return a pointer, not a new object, from the addition operator. Slightly hint that you’d like the value to be changed outside the function, too, in the first case. Ask him whether the statement customer3 = customer1 + customer2 would work in the second case.
3. What problems might the following macro bring to the application?

#define sq(x) x*x

4. Consider the following struct declarations:

struct A { A(){ cout << \"A\"; } };
struct B { B(){ cout << \"B\"; } };
struct C { C(){ cout << \"C\"; } };
struct D { D(){ cout << \"D\"; } };
struct E : D { E(){ cout << \"E\"; } };
struct F : A, B
{
C c;
D d;
E e;
F() : B(), A(),d(),c(),e() { cout << \"F\"; }
};

What constructors will be called when an instance of F is initialized? Produce the program output when this happens.
5. Anything wrong with this code?

T *p = new T[10];
delete p;


Note: Incorrect replies: “No, everything is correct”, “Only the first element of the array will be deleted”, “The entire array will be deleted, but only the first element destructor will be called”.
6. Anything wrong with this code?

T *p = 0;
delete p;

Note: Typical wrong answer: Yes, the program will crash in an attempt to delete a null pointer. The candidate does not understand pointers. A very smart candidate will ask whether delete is overloaded for the class T.
7. Explain virtual inheritance. Draw the diagram explaining the initialization of the base class when virtual inheritance is used.
Note: Typical mistake for applicant is to draw an inheritance diagram, where a single base class is inherited with virtual methods. Explain to the candidate that this is not virtual inheritance. Ask them for the classic definition of virtual inheritance. Such question might be too complex for a beginning or even intermediate developer, but any applicant with advanced C++ experience should be somewhat familiar with the concept, even though he’ll probably say he’d avoid using it in a real project. Moreover, even the experienced developers, who know about virtual inheritance, cannot coherently explain the initialization process. If you find a candidate that knows both the concept and the initialization process well, he’s hired.
8. What’s potentially wrong with the following code?

long value;
//some stuff
value &= 0xFFFF;

Note: Hint to the candidate about the base platform they’re developing for. If the person still doesn’t find anything wrong with the code, they are not experienced with C++.
9. What does the following code do and why would anyone write something like that?

void send (int *to, int * from, int count)
{
int n = (count + 7) / 8;
switch ( count % 8)
{
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while ( --n > 0 );
}
}

10. In the H file you see the following declaration:

class Foo {
void Bar( void ) const ;
};

Tell me all you know about the Bar() function.

JDBC and JSP interview questions

JDBC and JSP interview questions

1. What is the query used to display all tables names in SQL Server (Query analyzer)?

select * from information_schema.tables

2. How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers
* JDBC-ODBC Bridge Driver
* Native API Partly Java Driver
* Network protocol Driver
* JDBC Net pure Java Driver
3. Can we implement an interface in a JSP?- No
4. What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
5. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
6. How to pass information from JSP to included JSP?- Using <%jsp:param> tag.
7. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.
8. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
9. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
10. How do you delete a Cookie within a JSP?

Cookie mycook = new Cookie(\"name\",\"value\");
response.addCookie(mycook);
Cookie killmycook = new Cookie(\"mycook\",\"value\");
killmycook.setMaxAge(0);
killmycook.setPath(\"/\");
killmycook.addCookie(killmycook);

11. How do I mix JSP and SSI #include?- If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.



But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use

<%@ vinclude="data.inc" %>

The is used for including non-JSP files.
12. I made my class Cloneable but I still get Can’t access protected method clone. Why?- Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().
13. Why is XML such an important development?- It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
14. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues:
* the quality of the driver code,
* the size of the driver code,
* the database server and its load,
* network topology,
* the number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
15. How do I find whether a parameter exists in the request object?

boolean hasFoo = !(request.getParameter(\"foo\") == null
|| request.getParameter(\"foo\").equals(\"\"));

or

boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)

16. How can I send user authentication information while makingURLConnection?- You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

Sql server

1. What is normalization? - Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization.
2. What is a Stored Procedure? - Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.
3. Can you give an example of Stored Procedure? - sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way.
4. What is a trigger? - Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.
5. What is a view? - If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.
6. What is an Index? - When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.
7. What are the types of indexes available with SQL Server? - There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.
8. What is the basic difference between clustered and a non-clustered index? - The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
9. What are cursors? - Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values.
10. When do we use the UPDATE_STATISTICS command? - This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
11. Which TCP/IP port does SQL Server run on? - SQL Server runs on port 1433 but we can also change it for better security.
12. From where can you change the default port? - From the Network Utility TCP/IP properties –> Port number.both on client and the server.
13. Can you tell me the difference between DELETE & TRUNCATE commands? - Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.
14. Can we use Truncate command on a table which is referenced by FOREIGN KEY? - No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.
15. What is the use of DBCC commands? - DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
16. Can you give me some DBCC command options?(Database consistency check) - DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage.
17. What command do we use to rename a db? - sp_renamedb ‘oldname’ , ‘newname’
18. Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? - In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.
19. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
20. What do you mean by COLLATION? - Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary.
21. What is a Join in SQL Server? - Join actually puts data from two or more tables into a single result set.
22. Can you explain the types of Joins that we can have with Sql Server? - There are three types of joins: Inner Join, Outer Join, Cross Join
23. When do you use SQL Profiler? - SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..
24. What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.
25. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group.
26. Which stored procedure will you be running to add a linked server? - sp_addlinkedserver, sp_addlinkedsrvlogin
27. What are the OS services that the SQL Server installation adds? - MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
28. Can you explain the role of each service? - SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers
29. How do you troubleshoot SQL Server if its running very slow? - First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes
30. Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot? - First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ——Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues.
31. What are the authentication modes in SQL Server? - Windows mode and mixed mode (SQL & Windows).
32. Where do you think the users names and passwords will be stored in sql server? - They get stored in master db in the sysxlogins table.
33. What is log shipping? Can we do logshipping with SQL Server 7.0 - Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan.
34. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? - For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER .m which will basically bring it into the maintenance mode after which we can restore the master db.
35. Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take? - (I am not sure- but I think we have a command to do it).
36. What is BCP? When do we use it? - BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.
37. What should we do to copy the tables, schema and views from one SQL Server to another? - We have to write some DTS packages for it.
38. What are the different types of joins and what dies each do?
39. What are the four main query statements?
40. What is a sub-query? When would you use one?
41. What is a NOLOCK?
42. What are three SQL keywords used to change or set someone’s permissions?
43. What is the difference between HAVING clause and the WHERE clause?
44. What is referential integrity? What are the advantages of it?
45. What is database normalization?
46. Which command using Query Analyzer will give you the version of SQL server and operating system?
47. Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table?
48. What is the purpose of using COLLATE in a query?
49. What is a trigger?
50. What is one of the first things you would do to increase performance of a query? For example, a boss tells you that “a query that ran yesterday took 30 seconds, but today it takes 6 minutes”
51. What is an execution plan? When would you use it? How would you view the execution plan?
52. What is the STUFF function and how does it differ from the REPLACE function?
53. What does it mean to have quoted_identifier on? What are the implications of having it off?
54. What are the different types of replication? How are they used?
55. What is the difference between a local and a global variable?
56. What is the difference between a Local temporary table and a Global temporary table? How is each one used?
57. What are cursors? Name four types of cursors and when each one would be applied?
58. What is the purpose of UPDATE STATISTICS?
59. How do you use DBCC statements to monitor various aspects of a SQL server installation?
60. How do you load large data to the SQL server database?
61. How do you check the performance of a query and how do you optimize it?
62. How do SQL server 2000 and XML linked? Can XML be used to access data?
63. What is SQL server agent?
64. What is referential integrity and how is it achieved?
65. What is indexing?
66. What is normalization and what are the different forms of normalizations?
67. Difference between server.transfer and server.execute method?
68. What id de-normalization and when do you do it?
69. What is better - 2nd Normal form or 3rd normal form? Why?
70. Can we rewrite subqueries into simple select statements or with joins? Example?
71. What is a function? Give some example?
72. What is a stored procedure?
73. Difference between Function and Procedure-in general?
74. Difference between Function and Stored Procedure?
75. Can a stored procedure call another stored procedure. If yes what level and can it be controlled?
76. Can a stored procedure call itself(recursive). If yes what level and can it be controlled.?
77. How do you find the number of rows in a table?
78. Difference between Cluster and Non-cluster index?
79. What is a table called, if it does not have neither Cluster nor Non-cluster Index?
80. Explain DBMS, RDBMS?
81. Explain basic SQL queries with SELECT from where Order By, Group By-Having?
82. Explain the basic concepts of SQL server architecture?
83. Explain couple pf features of SQL server
84. Scalability, Availability, Integration with internet, etc.)?
85. Explain fundamentals of Data ware housing & OLAP?
86. Explain the new features of SQL server 2000?
87. How do we upgrade from SQL Server 6.5 to 7.0 and 7.0 to 2000?
88. What is data integrity? Explain constraints?
89. Explain some DBCC commands?
90. Explain sp_configure commands, set commands?
91. Explain what are db_options used for?
92. What is the basic functions for master, msdb, tempdb databases?
93. What is a job?
94. What are tasks?
95. What are primary keys and foreign keys?
96. How would you Update the rows which are divisible by 10, given a set of numbers in column?
97. If a stored procedure is taking a table data type, how it looks?
98. How m-m relationships are implemented?
99. How do you know which index a table is using?
100. How will oyu test the stored procedure taking two parameters namely first name and last name returning full name?
101. How do you find the error, how can you know the number of rows effected by last SQL statement?
102. How can you get @@error and @@rowcount at the same time?
103. What are sub-queries? Give example? In which case sub-queries are not feasible?
104. What are the type of joins? When do we use Outer and Self joins?
105. Which virtual table does a trigger use?
106. How do you measure the performance of a stored procedure?
107. Questions regarding Raiseerror?
108. Questions on identity?
109. If there is failure during updation of certain rows, what will be the state?

Orcale

Interview questions for Oracle database administrator

1. Differentiate between TRUNCATE and DELETE
2. What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?
3. Can you use a commit statement within a database trigger?
4. What is an UTL_FILE.What are different procedures and functions associated with it?
5. Difference between database triggers and form triggers?
6. What is OCI. What are its uses?
7. What are ORACLE PRECOMPILERS?
8. What is syntax for dropping a procedure and a function? Are these operations possible?
9. Can a function take OUT parameters. If not why?
10. Can the default values be assigned to actual parameters?
11. What is difference between a formal and an actual parameter?
12. What are different modes of parameters used in functions and procedures?
13. Difference between procedure and function.
14. Can cursor variables be stored in PL/SQL tables.If yes how. If not why?
15. How do you pass cursor variables in PL/SQL?
16. How do you open and close a cursor variable.Why it is required?
17. What should be the return type for a cursor variable.Can we use a scalar data type as return type?
18. What is use of a cursor variable? How it is defined?
19. What WHERE CURRENT OF clause does in a cursor?
20. Difference between NO DATA FOUND and %NOTFOUND
21. What is a cursor for loop?
22. What are cursor attributes?
23. Difference between an implicit & an explicit cursor.
24. What is a cursor?
25. What is the purpose of a cluster?
26. How do you find the numbert of rows in a Table ?
27. Display the number value in Words?
28. What is a pseudo column. Give some examples?
29. How you will avoid your query from using indexes?
30. What is a OUTER JOIN?
31. Which is more faster - IN or EXISTS?
32. When do you use WHERE clause and when do you use HAVING clause?
33. There is a % sign in one field of a column. What will be the query to find it?
34. What is difference between SUBSTR and INSTR?
35. Which datatype is used for storing graphics and images?
36. What is difference between SQL and SQL*PLUS?
37. What is difference between UNIQUE and PRIMARY KEY constraints?
38. What is difference between Rename and Alias?
39. What are various joins used while writing SUBQUERIES?

Monday, June 8, 2009

Sqlserver Interview questions

What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems
that maintain data records and indices in tables. Relationships may be created and
maintained across and among the data and tables. In a relational database, relationships
between data items are expressed by means of tables. Interdependencies among these
tables are expressed by data values rather than by pointers. This allows a high degree of
data independence. An RDBMS has the capability to recombine the data items from
different files, providing powerful tools for data usage. (Read More Here)

What are the properties of the Relational tables?
Relational tables have six properties:
• Values are atomic.
• Column values are of the same kind.
• Each row is unique.
• The sequence of columns is insignificant.
• The sequence of rows is insignificant.
• Each column must have a unique name.

What is Normalization?
Database normalization is a data design and organization process applied to data structures
based on rules that help building relational databases. In relational database design, the
process of organizing data to minimize redundancy is called normalization. Normalization
usually involves dividing a database into two or more tables and defining relationships
between the tables. The objective is to isolate data so that additions, deletions, and
modifications of a field can be made in just one table and then propagated through the rest
of the database via the defined relationships.

What is De‐normalization?
De‐normalization is the process of attempting to optimize the performance of a database by
adding redundant data. It is sometimes necessary because current DBMSs implement the
relational model poorly. A true relational DBMS would allow for a fully normalized database
at the logical level, while providing physical storage of data that is tuned for high
performance. De‐normalization is a technique to move from higher to lower normal forms
of database modeling in order to speed up database access.

What are different normalization forms?

1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key.
Each field contains at most one value from its attribute domain.

2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi‐valued key, remove it to a separate table.

3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table.
All attributes must be directly dependent on the primary key. (Read More Here)

BCNF: Boyce‐Codd Normal Form
If there are non‐trivial dependencies between candidate key attributes, separate them out
into distinct tables.

4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.

5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related
many‐to‐many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model
notation.

DKNF: Domain‐Key Normal Form
A model free from all modification anomalies is said to be in DKNF.

Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it
must first fulfill all the criteria of a 2NF and 1NF database.

What is Stored Procedure?
A stored procedure is a named group of SQL statements that have been previously created
and stored in the server database. Stored procedures accept input parameters so that a
single procedure can be used over the network by several clients using different input data.
And when the procedure is modified, all clients automatically get the new version. Stored
procedures reduce network traffic and improve performance. Stored procedures can be
used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or
UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to
maintain the referential integrity of data by changing the data in a systematic fashion. A
trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a
data modification to the associated table. Triggers can be viewed as similar to stored
procedures in that both consist of procedural logic that is stored at the database level.
Stored procedures, however, are not event‐drive and are not attached to a specific table as
triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure
while triggers are implicitly executed. In addition, triggers can also execute stored
procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so
when the trigger is fired because of data modification it can also cause another data
modification, thereby firing another trigger. A trigger that contains data modification logic
within itself is called a nested trigger.
What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as
well as updating or deleting rows. Rows updated or deleted in the view are updated or
deleted in the table the view was created with. It should also be noted that as data in the
original table changes, so does data in the view, as views are the way to look at part of the
original table. The results of using a view are not permanently stored in the database. The
data accessed through a view is actually constructed using standard T‐SQL select command
and can come from one to many different base tables or even other views.

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an
existing table to locate rows more quickly and efficiently. It is possible to create an index on
one or more columns of a table, and each index is given a name. The users cannot see the
indexes; they are just used to speed up queries. Effective indexes are one of the best ways
to improve performance in a database application. A table scan happens when there is no
index available to help a query. In a table scan SQL Server examines every row in the table
to satisfy the query results. Table scans are sometimes unavoidable, but on large tables,
scans have a terrific impact on performance.