Quantcast Job Interview Questions - www.interviewhelper.org: November 2007



Get unlimited interview questions on our new improved website...


 Interview Helper Home | Forum | Submit Link | Online Tickets | Freelance Work | Free Games | Jobs

Wednesday, November 28, 2007

C Interview Questions

1. Write a program in C to find the 3*3 matrix multiplication.

2. Write a program in C to find the complex number of a given number.

3. how to print all the combinations of a given integer.

4. what is the significance of following functions

  • freopen()
  • strtok()
  • access()
  • state()
5. what is the "escape hatch" provided by #pragma directive?

6. what is source code of this tringle ...
A
A N I
A N I R B
A N I R B A N
A N I R B A N P A
A N I R B A N P A U L

7. What happens when you overload the stack?

8. what do you mean by preprocessor directory?

9. What is byte offset of a field within a structure?

10. What is unabridged list?

11. How is structure passing and returning implemented?

12. Write sample code or algorithim to get all possible combinations of data that will be entered from keyboard.

13. Explian Floyd Cycle finding algorithm for circular link list?

14. Why is that a pointer is depicted by '*' in C?

15. Write a program to print an 2D array in spiral manner

16. #includevoid fun(int);void main(){ inta; a=3; fun(a); }void fun(int){ if(n>0) { fun(--n);...

17. Given the values of two nodes in a *binary search tree*, write a cprogram to find the lowest common ancestor.

18. Can we define an array without any constant expression? If Yes, How?

19. For what purpose pragma.h header file is used?

20. What is the advantage of zero filling in calloc() ?

Oracle Interview Questions - Part 13

1.What are the various types of Exceptions ?
User defined and Predefined Exceptions.

2.Can we define exceptions twice in same block ?
No.

3.What is the difference between a procedure and a function ?
Functions return a single variable by value whereas procedures do not return any variable by value. Rather they return multiple variables by passing variables by reference through their OUT parameter.

4.Can you have two functions with the same name in a PL/SQL block ?
Yes.

5.Can you have two stored functions with the same name ?
Yes.

6.Can you call a stored function in the constraint of a table ?
No.

7.What are the various types of parameter modes in a procedure ?
IN, OUT AND INOUT.

8.What is Over Loading and what are its restrictions ?
OverLoading means an object performing different functions depending upon the no. of parameters or the data type of the parameters passed to it.

9.Can functions be overloaded ?
Yes.

10.Can 2 functions have same name & input parameters but differ only by return datatype?
No.
11.What are the constructs of a procedure, function or a package ?
The constructs of a procedure, function or a package are : variables and constants cursors exceptions

12.Why Create or Replace and not Drop and recreate procedures ?
So that Grants are not dropped.

13.Can you pass parameters in packages ? How ?
Yes. You can pass parameters to procedures or functions in a package.

14.What are the parts of a database trigger ?
The parts of a trigger are:
A triggering event or statement
A trigger restriction
A trigger action

15.What are the various types of database triggers ?
There are 12 types of triggers, they are combination of :
Insert, Delete and Update Triggers.
Before and After Triggers.
Row and Statement Triggers.(3*2*2=12)

16.What is the advantage of a stored procedure over a database trigger ?
We have control over the firing of a stored procedure but we have no control over the firing of a trigger.

17.What is the maximum no. of statements that can be specified in a trigger statement ?
One.

18.Can views be specified in a trigger statement ?
No

19.What are the values of :new and :old in Insert/Delete/Update Triggers ?
INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value

20.What are cascading triggers? What is the maximum no of cascading triggers at a time?
When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading. Max = 32.
21.What are mutating triggers ?
A trigger giving a SELECT on the table on which the trigger is written.

22.What are constraining triggers ?
A trigger giving an Insert / Update on a table having referential integrity constraint on the triggering table.

23.Describe Oracle database's physical and logical structure ?
Physical : Data files, Redo Log files, Control file.
Logical : Tables, Views, Tablespaces, etc.

24.Can you increase the size of a tablespace ? How ?
Yes, by adding datafiles to it.

25.Can you increase the size of datafiles ? How ?
No (for Oracle 7.0)Yes (for Oracle 7.3 by using the Resize clause ----- Confirm !!).

26.What is the use of Control files ?
Contains pointers to locations of various data files, redo log files, etc.

27.What is the use of Data Dictionary ?
Used by Oracle to store information about various physical and logical Oracle structures e.g. Tables, Tablespaces, datafiles, etc

28.What are the advantages of clusters ?
Access time reduced for joins.

29.What are the disadvantages of clusters ?
The time for Insert increases.

30.Can Long/Long RAW be clustered ?
No.
31.Can null keys be entered in cluster index, normal index ?
Yes.

32.Can Check constraint be used for self referential integrity ? How ?
Yes. In the CHECK condition for a column of a table, we can reference some other column of the same table and thus enforce self referential integrity.

33.What are the min. extents allocated to a rollback extent ?
Two

34.What are the states of a rollback segment ? What is the difference between partly available and needs recovery ?
The various states of a rollback segment are :ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID.

35.What is the difference between unique key and primary key ?
Unique key can be null; Primary key cannot be null.

36.An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ?
Yes.

37.Can you define multiple savepoints ?
Yes.

38.Can you Rollback to any savepoint ?
Yes.

40.What is the maximum no. of columns a table can have ?
256.

Data Warehousing Interview Questions

1) What is source qualifier?
2) Difference between DSS & OLTP?
3) Explain grouped cross tab?
4) Hierarchy of DWH?
5) How many repositories can we create in Informatica?
6) What is surrogate key?
7) What is difference between Mapplet and reusable transformation?
8) What is aggregate awareness?
9) Explain reference cursor?
10) What are parallel querys and query hints?
11) DWH architecture?
12) What are cursors?
13) Advantages of de normalized data?
14) What is operational data source (ODS)?
15) What is meta data and system catalog?
16) What is factless fact schema?
17) What is confirmed dimension?
18) What is the capacity of power cube?
19) Difference between PowerPlay transformer and power play reports?
20) What is IQD file?
21) What is Cognos script editor?
22) What is difference macros and prompts?
23) What is power play plug in?
24) Which kind of index is preferred in DWH?
25) What is hash partition?
26) What is DTM session?
27) How can you define a transformation? What are different types of transformations in Informatica?
28) What is mapplet?
29) What is query panel?
30) What is a look up function? What is default transformation for the look up function?
31) What is difference between a connected look up and unconnected look up?
32) What is staging area?
33) What is data merging, data cleansing and sampling?
34) What is up date strategy and what are th options for update strategy?
35) OLAP architecture?
36) What is subject area?
37) Why do we use DSS database for OLAP tools?
38) What is a universe?
39) Analysis in business objects?
40) Who launches the supervisor product in BO for first time?
41) How can you check the universe?
42) What are universe parameters?
43) Types of universes in business objects?
44) What is security domain in BO?
45) Where will you find the address of repository in BO?
46) What is broad cast agent?
47) In BO 4.1 version what is the alternative name for broadcast agent?
48) What services the broadcast agent offers on the server side?
49) How can you access your repository with different user profiles?
50) How many built-in objects are created in BO repository?
51) What are alertors in BO?
52) What are different types of saving options in web intelligence?
53) What is batch processing in BO?
54) How can you first report in BO by using broadcast agent?
55) Can we take report on Excel in BO?

VB Interview Questions

  • Why do you use Option Explicit?
  • What are the commonly used data types in VBScript?
  • What is a session object?
  • What are the three objects of ADO?
  • What are the lock-types available in ADO?
  • Explain. What are the cursor types available in ADO? Explain.
  • What is a COM component? How do you register a COM component?
  • What is a virtual root and how do you create one?
  • What is a database index, how do you create one, discuss its pros and cons?
  • How do you use multiple record sets(rs.NextRecordSet)?
  • As soon as you fetch a record set, what operations would you perform?
  • Define a transaction.
  • What are ACID properties of a transaction?
  • How would you remotely administer IIS?
  • What is RAID? What is it used for?
  • What is normalization? Explain normalization types.
  • What is the disadvantage of creating an index in every column of a database table?
  • What are the uses of source control software?
  • You have a query that runs slowly, how would you make it better?
  • How would you make it better in .NET environment?
  • What is a bit datatype? What is it used for?
  • How would you go about securing IIS and MS-SQL Server?
  • What is the difference between Request("field") and Request.Form("field")?
  • What versions of VB have you used? Have you also used VBA or VBScript?
  • Have you ever used classes? If so, how have you used them?
  • Have you ever created ActiveX DLLs? If so, why did you create the DLLs instead of using code in the main application?
  • Have you ever created ActiveX controls? If so, what did they do?
  • Have you ever created ActiveX EXEs? If so, what were they used for?
  • Have you ever used Collections? Collection Classes?
  • Have you ever used ADO? DAO? RDO? Any other database engines?
  • What database backends have you worked with? Access? SQL Server? Oracle?
  • Have you ever used resource files? If so, for what reason?
  • Have you used the FileSystemObject? The Dictionary Object? Regular Expressions?
  • Have you developed COM+ components? Any other types of server based components?
  • What source code control systems have you used?
  • What versions of Windows have you used? Have you used any other operating systems?
  • What third party ActiveX controls have you used?
  • Are there any other programming tools, such as database diagramming, UML, or CASE tools, that you've used?
  • Have you developed components for IIS? Developed ASP pages?
  • If you were writing a program, what method would you use to send information from the main form of the application to a modal popup form and then pass any changes to the data back to the main form when the popup form was closed?
  • How would you center a form on the screen? How about centering it on another form?
  • If an event, such as a tool bar button or menu click,occurs on a MDI parent how can it invoke an action on one or more MDI child forms?
  • What are some methods you can use to send data from one VB executable to another one?
  • What are the differences between a standard module and a class module?
  • What do you have to do to make your class visible to programs other than your own?
  • How can you tell what kind of object an object variable is holding?
  • Describe the different scopes of variables in VB.
  • Describe the difference between a public variable in a form and one in a standard code module.
  • How do you handle error conditions in your code?
  • What are some uses and misuses of variants?
  • What are some of the steps you can take to determine why your program is crashing with "Invalid Page Fault" errors?
  • What are the different ways you can use threading in VB? When are they appropriate?
  • How many tabs in a tabbed dialog do you consider appropriate?
  • How many items should you make available to users in a listbox or combo box?
  • What are the three main differences between flexgrid control and dbgrid(Data bound Grid) control
    The Microsoft FlexGrid (MSFlexGrid) control displays and operates on tabular data. It allows complete flexibility to sort, merge, and format tables containing strings and pictures. When bound to a Data control, MSFlexGrid displays read-only data.Adaptation to existing Visual Basic code for the data-bound grid (DBGrid).

    Dbgrid is A spreadsheet-like bound control that displays a series of rows and columns representing records and fields from a Recordset object.

    The data grids are bound controls; that is, they require a data source that actually connects to a database and retrieves their data. And it seems that the root of the problem with DBGrid is that there's no data source that can be readily included along with the DBGrid control.In Visual Basic, the solution is simply to include the Data Control on the same form as DBGrid. But the Data Control is an intrinsic control; it's unavailable to anything outside of the Visual Basic environment itself. and VB 6.0 has a new set of data controls (DataGrid, DataList, DataCombo, MSHFlexGrid, MSFlexGrid) that once again are bound controls. Unlike DBGrid, though, they support OLE DB, and therefore rely on the an ADO Data Source (and in particular the ActiveX Data Objects Data Control, or ADO DC) for data access. Unlike the Data Control, the ADODC is a custom control (that is, an .OCX) that can be added to any project. In short, if you add ADO DC to your project along with theDataGrid control.
  • ActiveX and Types of ActiveX Components in VB ?
    Standard EXE
    ActiveX EXE
    ActiveX DLL
    ActiveX document
    ActiveX Control
  • What is difference between inprocess and out of process ?
    An in-process component is implemented as a DLL, and runs in the same process space as its client app, enabling the most efficient communication between client and component.Each client app that uses the component starts a new instance of it.
    An out of process component is implemented as an EXE, and unlike a dll, runs in its own process space. As a result, exe's are slower then dll'sbecause communications between client and component must be marshalled across process boundaries. A single instance of an out of process component can service many clients.
  • Advantage of ActiveX Dll over Active Exe ?

    ACTIVEX DLL:An in-process component, or ActiveX DLL, runs in another application’s process. In-process components are used by applications or other in-process components. this allows you to wrap up common functionality (like an ActiveX Exe).

    ACTIVEX EXE:An out-of-process component, or ActiveX EXE, runs in its own address space. The client is usually an application running in another process.The code running in an ActiveX Exe is running in a separate process space. You would usually use this in N-Tier programming.

    An ActiveX EXE runs out of process while an ActiveX DLL runs in the same process space as VB app. Also, and ActiveX EXE can be run independent of your application if desired.
  • Explain single thread and multithread thread apartments.
    All components created with Visual Basic use the apartment model, whether they’re single-threaded or multithreaded. A single-threaded component has only one apartment, which contains all the objects the component provides.
    This means that a single-threaded DLL created with Visual Basic is safe to use with a multithreaded client. However, there’s a performance trade-off for this safety. Calls from all client threads except one are marshaled, just as if they were out-of-process calls.
  • What is a Component?
    If you compile an ActiveX dll, it becomes a component.If you compile an ActiveX Control, it becomes both a component and a control.
    Component is a general term used to describe code that's grouped by functionality. More specifically, a component in COM terms is a compiled collection of properties/methods and events.
    Typically a component is loaded into your project via the References whereas an ActiveX Control is loaded into your project via "components".
  • What is meant by "Early Binding" and "Late Binding"? Which is better?
    Early binding and late binding refer to the method used to bind an interface's properties and methods to an object reference (variable). Early binding uses type library information at design time to reference procedures, while late binding handles this at run time. Late bindinghandles this by interrogating the reference before each call to insure that it supports a particular method. Since every call to a late boundobject actually requires two calls ("Do you do this?" followed by "Okay, do it then"), late binding is much less efficient than early binding. Except where early binding is not supported (ASP, scripting, etc.), late binding should only be used in very special cases.
    It is a common misconception that any code using the CreateObject function instead of
    Set = New is using late binding. This is not the case. The type declaration of the object variable determines whetherit is late or early bound, as in the following:

    Dim A As Foo
    Dim B As Foo
    Dim C As Object
    Dim D As Object
    Set A = New Foo 'Early Bound
    Set B = CreateObject("FooLib.Foo") 'Early Bound
    Set C = CreateObject("FooLib.Foo") 'Late Bound
    Set D = New Foo 'Late Bound

HR Interview Questions

1. Tell me about yourself?
I am down-to-earth, sweet, smart, creative, industrious, and thorough.

2. How has your experience prepared you for your career?
Coursework:
Aside from the discipline and engineering foundation learning that I have gained from my courses, I think the design projects, reports, and presentations have prepared me most for my career.
Work Experience:
Through internships, I have gained self-esteem, confidence, and problem-solving skills. I also refined my technical writing and learned to prepare professional documents for clients.
Student Organizations:
By working on multiple projects for different student organizations while keeping up my grades, I've built time management and efficiency skills. Additionally, I've developed leadership, communication, and teamwork abilities.
Life Experience:
In general, life has taught me determination and the importance of maintaining my ethical standards.

3. Describe the ideal job.
Ideally, I would like to work in a fun, warm environment with individuals working independently towards team goals or individual goals. I am not concerned about minor elements, such as dress codes, cubicles, and the level of formality. Most important to me is an atmosphere that fosters attention to quality, honesty, and integrity.

4. What type of supervisor have you found to be the best?
I have been fortunate enough to work under wonderful supervisors who have provided limited supervision, while answering thoughtful questions and guiding learning. In my experience, the best supervisors give positive feedback and tactful criticism.

5. What do you plan to be doing in five years' time?
Taking the Project Management exam and serving in supervisory/leadership roles both at work and in professional/community organization(s).

6. What contributions could you make in this organization that would help you to stand out from other applicants?
In previous internships, my industriousness and ability to teach myself have been valuable assets to the company. My self-teaching abilities will minimize overhead costs, and my industriousness at targeting needs without prompting will set me apart from others. Additionally, one thing that has always set me apart from my scientific/engineering peers are my broad interests and strong writing abilities.

7. What sort of criteria are you using to decide the organization you will work for?
Most importantly, I am looking for a company that values quality, ethics, and teamwork. I would like to work for a company that hires overachievers.

8. What made you choose your major?
My academic interests are broad, so I sought engineering to achieve a great balance of mathematics, chemistry, biology, physics, and writing.

9. Have your university and major met your expectations?
The College at has exceeded my expectations by providing group activities, career resources, individual attention, and professors with genuine interest in teaching.
My major has met my expectations by about 90%. I would have enjoyed more choices in courses, and would have preferred more calculus-based learning.

10. What made you choose this college?
I chose this college for the following reasons: The High standards of learning and the excellent faculty impressed me, I saw active student groups, and the people were very friendly.

11. List 2-3 of your greatest achievements since you've been in college and why?
Receiving the Meritorious Student Award and Outstanding Achievement Award in organizing the National Level Event.
I got involved with student activities to overcome my debilitating shyness. Receiving these awards signified that I had accomplished a transition from dragging myself to participate to feeling energized by it.
Earning the highest grade in class of ~200 people, I worked very hard for this grade, so it was a great feeling to see that the hard work paid off.

12. Which subjects have you enjoyed studying the most and why?
I have enjoyed software engineering, programming in C, Datastructure and DBMS because I love the topics, where I can put my creativity logically.
Calculus and linear algebra also excite me because I love logic.
MIS thrilled me because I have a strong interest in organizing the things logically.

13. Which subjects did you dislike and why?
Introductory Accounting little interest in me, most likely because I am not very good at numbers, the book was ineffective, and I had little spare time that semester to look into other resources.

14. Do you have plans to continue your education?
Yes, but not immediately. I plan to continue with either part time or distance learning MBA depending on which will be more beneficial to my work.

15. How would a professor who knows you well describe you? One who does not know you well?
A professor who knows me well would likely describe my personal qualities: sweet, down-to-earth, smart, hard-working, and conscientious.
As specific examples of those who did not know me well, my accounts professor considered me smart and respectful, and thought that I must have enjoyed the class a lot, due to my performance.

16. Given the chance, how would you alter your education?
Knowing now what I like the most, I would have used my electives for extra math and psychology classes, since I tend to be well-rounded enough that a variety of classes are unnecessary; my personal reading is diverse enough. I have found that mathematics and psychology are helpful to all career and life paths.

17. Which part-time job did you enjoy the most and why?
Working for was most enjoyable to me, since I felt like I was significantly contributing to the company, and I enjoyed learning on my own.

18. Interests:
Some of my interests include Music, singing, writing, reading (especially novels) , drawing, watching cricket, and computers.

19. What are your strengths?
My strongest strength is the ability to teach myself difficult material, regardless of the subject. Additionally, I have always excelled verbally and look forward to writing opportunities.

20. What are your weaknesses?
I tend to try to do too many things, leaving little time for myself. I have worked on balancing myself for the last several months. I am also working on improving my public speaking skills.

21. What sort of serious problems have you experienced, and how have you handled them?
Getting caught with Typhoid jsut a month before my Semester Exams was the very hard and serious issue but fortunately, I had studied throughout the semester. I missed about 15 days of college due to the illness. Within 2 weeks, I had recovered reasonably from the illness and thanks to my habit of making notes, which proved very beneficial at the time of exams.

22. Do you or have you in the past experimented with illegal drugs?
No. My only addictions are caffeine and sugar.

23. Would you be willing to take a drug test?
Of course.

24. Do you drink alcohol socially?
No, but I enjoy Shirley Temples quite a bit.

25. How do you propose to compensate for your lack of experience?
My zeal, fast learning and quick adaption to the technogies will be an added advantage for the job I would be doing. I am hard-worker and a very quick learner and never afraid to put an extra effort to reach the desired level required by the job.

Some of the questions posted by many college freshers

  • I have given an HR inteview where they ask me to write where do you see yourself in 5 years down lane.
  • Why should we not hire you?
  • What should be the answer for why did you choose and persue carrer in only hr in an interview
  • What to answer and what not to answer for "Tell me something about you"
  • Why do you want to leave your current job?
  • Why do you want to join in industry? (for recent graduates)
  • How do you organize your priorities?
  • What is management interview ? (after clearing technical interview they asked me to come for this?)
  • What are the things you are suppose to describe, if the HR asks you "Tell me something about yourself
  • How can I elobrate my strengths with examples?
  • What are the competitive challenges in Human Resource Management?
  • Why u want to change the present company?
  • What is ergonomics
  • Why do you want to join this company?
  • Why do you want to leave your previous job?
  • where do you see yourself after 10 years from now?
  • Suppose you already have job offer and giving to interview to other new company. What reasoning should you give for sitting again?
  • My questions are:-Why do you like to join this company?What would you do for the growth of this company?
  • What should i answer if my interviewer asks me about my short and long term goals.Tell me with some example.
  • Give an answer with an example how i should answer for tell me about yourself?
  • If they ask tell about yourself,from where i have to start.give an answer with an example?
  • Why do you think you would do well at this job?
  • What is more important to you: the money or the work?
  • What would your previous supervisor say your strongest point is?
  • Tell me about a problem you had with your supervisor.
  • What has disappointed you about a job?
  • Tell me about your ability to work under pressure.
  • Do your skills match this job or another job more closely?
  • What motivates you to do your best on the job?
  • Are you willing to work overtime? Nights? Weekends?
  • Would you be willing to relocate if required?
  • Are you willing to put the interests of the organization ahead of your own?
  • Describe your management style.
  • What have you learned from mistakes on the job?
  • Do you have any blind spots?
  • If you were hiring a person for this job, what would you look for?
  • Do you think you are overqualified for this position?
  • How do you propose to compensate for your lack of experience?
  • What qualities do you look for in a boss?
  • Tell me about a time when you helped resolve a dispute between others.

Monday, November 26, 2007

PHP Interview Questions - Part 4

1What is PHP?

PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

2 What is its relation to PHP/FI?

PHP is the successor to PHP/FI 2.0.

3 Can I run both PHP/FI 2.0 and PHP at the same time?

Yes, PHP was written so as to not interfere with an existing PHP/FI 2 installation. Instructions for building Apache 1.3.0 with both PHP/FI 2 and PHP modules can be found HERE. A different spin on this is HERE, although the first step where the PHP2 regex code is substituted with the PHP regex code seems redundant. The two regex dirs are pretty much identical.

4 What are the differences between PHP and PHP/FI 2.0?

For a complete list of the changes, read the CHANGES file included in the PHP distribution. Some highlights:

· All-new parser.

· Persistent database connections.

· A native Windows95/NT port.

· IMAP, SNMP, and LDAP extensions.

5 I heard it's possible to access Microsoft SQL Server from PHP. How?

On Windows 95/NT machines, you can simply use the included ODBC support and the correct ODBC driver.

A copy of step-by-step ODBC setup can be found here.

On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question - 1.6.

6 Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.

If you are running PHP on a Unix box and want to talk to MS-Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built-in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat-files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other unix platforms. Please visit our website for a free download.

One option that has proven successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

1. Install MySQL on your platform according to instructions with MySQL. Latest available from www.mysql.org (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.

2. Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.

3. Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.

4. Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.

5. Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press ok, and presto! you can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks: - You can construct your tables in access and export them to MySQL, then link them back in. That makes table creation quick.
- When creating tables in access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access.
- If you change a table in MySQL, you have to re-link it in access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing ok.

7 Is there a PHP mailing list?

Of course! To subscribe, send mail to php3-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message.

To unsubscribe, send mail to php3-unsubscribe@lists.php.net.

8 Help! I can't seem to subscribe to the mailing list!

Help! I can't seem to unsubscribe from the mailing list!

If you have problems subscribing to or unsubscribing from the PHP mailng list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php3-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php3-unsubscribe-joeblow=example.com@lists.php.net.

9 Is there an archive of the mailing list anywhere?

Yes, you will find a list of archive sites on the Support page.

10 How did you do those pop-out windows for the Search and Mirror buttons?

Our site designer, Colin Viebrock (cmv@privateworld.com), says:

Those fancy pop-out layers are done with Dynamic HTML (DHTML), Cascading Style Sheets (CSS) and Javascript (version 1.2).

There are plenty of references on the web about DHTML and CSS, including:

· CSS Level 1 Spec: www.w3.org/TR/REC-CSS1

· Macromedia's DHTML Zone: www.dhtmlzone.com/index.html

· Webreference's DHTML Lab: www.webreference.com/dhtml/

· Guide to Cascading Style Sheets: www.htmlhelp.com/reference/css/

· Dynamic Duo - Cross-Browser DHTML: www.dansteinman.com/dynduo/

· Netscape's Guide to JS 1.2: developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm

But your best source of information is to view the source code to the pages on the PHP site. To see the actual DHTML/Javascript code, use your browser's "View Source" function. To see how this code was generated dynamically using PHP, click on the "Source" button in the upper-right corner of any PHP page. You will probably also want to view the source of the "shared.inc" file - there is a link to it at the bottom of every source page.

11 Can I access Empress RDBMS databases?

Yes. PHP 3.0.6 and Empress RDBMS v8.10 and higher are compatible.

You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and the Empress ODBC driver for Windows.

If you are running PHP on a Unix box and want to access Empress databases, you can link the Empress ODBC client driver directly into the PHP unified ODBC API.
Note that does NOT make PHP an ODBC client. The unified ODBC interface simplies uses the ODBC application program interface (API).

Because Empress uses the PHP unified ODBC interface it has very little explicit Empress specific syntax. It is of course possible to use Empress specific SQL in the SQL statements themselves, but this does not affect the interface. It is a good general policy to stick to ANSI standard SQL whenever possible.

Empress Specifics: The only item which is specific to Empress in PHP is that there are two methods for specifying the DNS in the odbc_connect ()odbc_pconnect () functions. The connect syntax is: and

odbc_connect (dsn, user_id, password)

odbc_pconnect (dsn, user_id, password)

For Empress dsn can be specified as either:

Data source name

This is the logical database name specified in the ODBC.INI file.

A full connection string, as specified in the ODBC standard.

eg
dsn="DATABASE=db_name;SERVER=server_name;PORT=server_port"

Note that there are other options for this string. But the three shown above are the most important for use with PHP.

Which of these you use is up to you. There are advantages and disadvantages to both. Using the full connection string means that you do NOT require an ODBC.INI file to access the database. However, if you move the datasource, or change the port on which the RDBMS server listens, you will have to modify every call to the odbc_connect/pconnect function.
The choice is yours...

Empress Installation: In order to add the Empress interface to PHP you require an Empress RDBMS with the Empress Connectivity option. If your PHP installation is on the same platform as the RDBMS then setting EMPRESS_PATH to the installation directory will automatically locate the Empress ODBC client driver. However, if the PHP installation is on a separate platform from the RDBMS you will also require an ODBC client on that platform, and you will need to specify the location of the driver when configuring the PHP installation.


2. Obtaining PHP

1 Where can I obtain PHP?

You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://cvs.php.net.

2 Are pre-compiled binary versions available?

Yes, although they are not always up to date. The Windows binary is generally current, but the Unix binaries lag behind and are only available for certain platforms. All download are available in the Downloads section.

3 Where can I get libraries needed to compile some of the optional PHP extensions?

Note: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.

· LDAP (unix): ftp://ftp.openldap.org/pub/openldap/openldap-stable.tgz

· LDAP* (unix): ftp://terminator.rs.itd.umich.edu/ldap/ldap-3.3.tar.Z

· LDAP (unix/win): Netscape Directory (LDAP) SDK 1.1 There is also a free LDAP server at: ftp://ftp.critical-angle.com/pub/cai/slapd/.

· Berkeley DB2 (Unix/Win): http://www.sleepycat.com/

· SNMP* (Unix): http://www.ece.ucdavis.edu/ucd-snmp/ (Note: PHP uses the native SNMP interface in Windows.)

· GD* (Unix/Win): http://www.boutell.com/gd/#buildgd

· mSQL* (Unix): http://www.hughes.com.au/

· mSQL* (Win) : MSQL PC Home Page

· MySQL (Unix): http://www.mysql.com/

· IMAP* (Win/Unix): ftp://ftp.cac.washington.edu/imap/old/imap-4.5.tar.Z

· Sybase-CT* (Linux, libc5): Available locally

· FreeType (libttf): http://www.freetype.org/

· ZLib (Unix/Win32): http://www.cdrom.com/pub/infozip/zlib/

· expat XML parser (Unix/Win32): http://www.jclark.com/xml/expat.html

· PDFLib: http://www.pdflib.com

· mcrypt: ftp://argeas.cs-net.gr/pub/unix/mcrypt/

· mhash: http://sasweb.de/mhash/

· t1lib: http://www.neuroinformatik.ruhr-uni-bochum.de/ini/PEOPLE/rmz/t1lib/t1lib.html

· dmalloc: http://www.dmalloc.com/

· aspell: http://metalab.unc.edu/kevina/aspell/aspell-.26.2.tar.gz

· Readline: ftp://prep.ai.mit.edu/pub/gnu/readline/

4 How do I get these libraries to work?

You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.

5 I got the latest version of the PHP source code from the CVS repository on my Windows 95/NT machine, what do I need to compile it?

First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need to download the support files. You will need to unzip this file (which has subdirectories, so make sure your unzip program keeps them) into the win32 subdirectory of the source distribution.

6 Where do I find the Browser Capabilities File?

You can find PHP's own browscap.ini file at http://php.netvision.net.il/browscap/. There is also another browscap.ini file at http://www.cyscape.com/asp/browscap/.


3. Installation

To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows 95 and NT users should also read the README.WIN32 file. There are also some helpful hints for Windows users here.

If you are trying to install PHP for use with Netscape's web server on Unix see: http://www.webgenx.com/php/phpnes.php3

1 Where should my php3.ini file be located?

By default on UNIX it should be in /usr/local/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it to something like:

  --with-config-file-path=/etc
  

And then you would copy php3.ini-dist from the distribution to /etc/php3.ini and edit it to make any local changes you want.

2 I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?

· Assuming you installed Apache PHP completely with RPMS, you need to uncomment or add some or all of the following lines in your http.conf file:
# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c
# Extra Modules
LoadModule php_module modules/mod_php.so
LoadModule php3_module modules/libphp3.so
LoadModule perl_module modules/libperl.so

· And add:
AddType application/x-httpd-php3 .php3
To the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

3 I installed PHP using RPMS, but it doesn't compile with the database support I need! What's going on here?

Due to the way PHP is currently built, it is not easy to build a complete flexible PHP RPM. This issue will be addressed in PHP4. For PHP, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP, read on...
Currently the RPM packagers are setting up the RPMS to install without database support to simplify installations AND because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level
This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.
Of course all of this information can be adjusted for any database server that PHP supports. I will assume you installed MySQL and Apache completely with RPMS for this example as well.
of your database server.

· First remove mod_php3
rpm -e mod_php3

· Then get the source rpm and INSTALL it, NOT --rebuild
rpm -Uvh mod_php3-3.0.5-2.src.rpm

· Then edit the /usr/src/redhat/SPECS/mod_php3.spec file
In the %build section add the database support you want, and the path.
For MySQL you would add --with-mysql=/usr \
The %build section will look something like this:
./configure --prefix=/usr \
--with-apxs=/usr/sbin/apxs \
--with-config-file-path=/usr/lib \
--enable-debug=no \
--enable-safe-mode \
--with-exec-dir=/usr/bin \
--with-mysql=/usr \
--with-system-regex

· Once this modification is made then build the binary rpm as follows:
rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

· Then install the rpm
rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

Make sure you restart Apache, and you now have PHP with MySQL support using RPM's. Note that it is probably much easier to just build from the distribution tarball of PHP and follow the instructions in INSTALL.REDHAT found in that distribution.


4. Build Problems

1 I got the latest version of PHP using the anonymous CVS service, but there's no configure script!

You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run make -f build.mk in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)

2 I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!

You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify '--with-apache=/path/to/apache' and not '--with-apache=/path/to/apache/src'.

3 When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!

You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

If you're using a csh-variant for your login shell (why?), it would be:

    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

4 When it is compiling the file language-parser.tab.c, it gives me errors that say 'yytname undeclared'.

You need to update your version of Bison. You can find the latest version at ftp://prep.ai.mit.edu/pub/gnu/.

5 When I run 'make', it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.

Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running "cp *.o functions" and then re-running 'make' to see if that helps. If it does, you should really upgrade to a recent version of GNU make.

6 When linking PHP, it complains about a number of undefined references.

Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.

If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.

Some people have also reported that they had to add '-ldl' immediately following 'libphp3.a' when linking with Apache.

7 I can't figure out how to build PHP with Apache 1.3.

This is actually quite easy. Follow these steps carefully:

· Grab the latest Apache 1.3 distribution from www.apache.org.

· Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.

· Compile PHP by first running ./configure --with-apache=//apache-1.3 (substitute for the actual path to your apache-1.3 directory.

· Type 'make' followed by 'make install' to build PHP and copy the necessary files to the Apache distribution tree.

· Change directories into to your //apache-1.3/src directory and edit the Configuration file. At the end of the file, add: AddModule modules/php3/libphp3.a.

· Type: './Configure' followed by 'make'.

· You should now have a PHP-enabled httpd binary!

Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.

8 I have followed all the steps to install the Apache module version on UNIX, and my PHP scripts show up in my browser or I am being asked to save the file. Help!

This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:

· Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l
If you don't see mod_php3.c listed then you are not running the right binary. Find and install the correct binary.

· Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3
Also make sure that this AddType line is not hidden away inside a or block which would prevent it from applying to the location of your test script.

· Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.

9 It says to use: --activate-module=src/modules/php3/libphp3.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php3/libmodphp3.a and it doesn't work!? What's going on?

Well, you decided to try to outsmart the people who wrote those nice step-by-step instructions for you and you have now discovered that these people cannot be outsmarted. The libphp3.a file is not supposed to exist. The Apache build process will create it.

10 When I try to build Apache with PHP as a static module using --activate-module=src/modules/php3/libphp3.a it tells me that my compiler is not ANSI compliant.

This is a crappy error message and has been fixed in Apache-1.3.10 (not available yet). For now, go and edit the src/Configure file in the Apache source directory and down around line 2140 you will find a line that looks like this:

if ./helpers/TestCompile sanity; then

Change this line to be this:

if ./helpers/TestCompile -v sanity; then

and now re-run the Apache configure script. It will now show you the actual errors that caused your build to fail. It is usually due to a missing library.

11 When I try to build PHP using --with-apxs I get strange error messages

There are two things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Edit your apxs (sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs) and check for these lines:

my $CFG_CFLAGS_SHLIB  = ' ';      # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';      # substituted via Makefile.tmpl

If this is what you see, you have found your problem. Change these lines to say:

my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE';      # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);# substituted via Makefile.tmpl 

The second possible problem should only be an issue on RedHat-6.1. The apxs script RedHat ships is broken. Look for this line:

my $CFG_LIBEXECDIR    = 'modules';        # substituted via APACI install

If you see the above line, change it to this:

my $CFG_LIBEXECDIR    = '/usr/lib/apache';        # substituted via APACI install

5. Using PHP

1 I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

Make sure that the track_vars feature is enabled in your php3.ini file. If you compiled PHP with "--enable-track-vars" it will be on by default. Alternatively you can enable it at run-time on a per-script basis by putting at the top of your file. When track_vars is on, it creates three associative arrays. $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS. So, to write a generic script to handle POST method variables you would need something similar to the following:

    while (list($var, $value) = each($HTTP_POST_VARS)) {
        echo "$var = $value
\n";
    }

2 I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?

First off, take a look at the addslashes() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php3.ini file.

The ereg_replace magic you're looking for, however, is simply:

    $escaped = ereg_replace("'", "\\'", $input);

3 When I do the following, the output is printed in the wrong order:

      function myfunc($argument) {
        echo $argument + 10;
      }
      $variable = 10;
      echo "myfunc($variable) = " . myfunc($variable);
    

What's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo it.

4 Hey, what happened to my newlines in:

  1 
  2 

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). This means that you need to insert an extra newline after each block of PHP code in the above example.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

5 I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as a module. So, the following bit of code will show you all the request headers:

    $headers = getallheaders();
  for(reset($headers); $key = key($headers); next($headers)) {
        echo "headers[$key] = ".$headers[$key]."
\n";
    }

6 When I try to use authentication with IIS I get 'No Input file specified'

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by php) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. When the ISAPI module is ready, this will no longer be a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.

7 I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine.

8 My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape. Even when I telnet to port 80 directly the correct content shows up. How can this be? PHP is server-side and my browser can't possibly know that the content it is seeing is generated by PHP, so what is going on?

Very good question! ;) This is a tricky little issue and it has come up twice in the past month as of this writing. Both times I ended up spending a good 20 minutes trying to figure out what the heck was going on. The answer is that both IE and Lynx ignore any NULs (\0) in the HTML stream. Netscape does not. The best way to check for this is to compile the command-line version of PHP (also known as the CGI version) and run your script from the command line and pipe it through 'od -c' and look for any \0 characters. (If you are on Windows you need to find an editor or some other program that lets you look at binary files) When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will. If this issue has bitten you, congratulations! You are not alone.

9 How do I get all the results from a SELECT MULTIPLE HTML tag?

The SELECT MULTIPLE tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.

   

This tells PHP to treat var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element id instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

   variable = documents.forms[0].elements['var[]'];

10 How am I supposed to mix XML and PHP? It complains about my tags!

You need to turn off the short tags by setting short_tags to 0 in your php3.ini file, or by using the php3_short_tags Apache directive. (You could even use a section to do this selectively.) You can also disable and re-enable the short tags in your script using the short_tags() function.

11 How can I use PHP with FrontPage or Dreamweaver or some other HTML editor that insists on moving my code around?

One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Most of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php3.ini variable, or use the php3_asp_tags Apache directive.

12 Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?

The best way is to stick a tag on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.

13 Why do I always get an error that looks something like this:
Warning: 0 is not a MySQL result index in file on line 8
What am I doing wrong?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:

        $result = mysql_query("select * from tables_priv");
        if(!$result) {
            echo mysql_error();
            exit;
        }

or:

        $result = mysql_query("select * from tables_priv") 
                    or die("Bad query: ".mysql_error());

14 I'm trying to use an tag, but the $foo.x and $foo.y variables aren't available. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

  

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because $foo.x and $foo.y are invalid variable names in PHP, they are automagically converted to $foo_x and $foo_y. That is, the periods are replaced with underscores.


6. New Features

1 I saw PHP offers persistent database connections. What does that mean?

Persistent connections are SQL links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same SQL link, they do not give you an ability to build up a transaction efficently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When each request comes in from a a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be serviced by a different child process than the first time. What a persistent connection does for you in this case it make it so each child process only needs to connect to your SQL server the first time that it serves a page that makes us of such a connection. When another page then requires a connection to the SQL server, it can reuse the connection that child established earlier.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently this is only theoretical -- PHP does not yet work as a plug-in for any multithreaded web servers. Work is progressing on support for ISAPI, WSAPI, and NSAPI (on Windows), which will all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack, Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. When this happens, the behavior will be essentially the same as for the multiprocess model described before.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!


7. Common Problems

1 I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?

This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:

· Stop your httpd processes

· gdb httpd

· > run -X -f /path/to/httpd.conf

· Then fetch the URL causing the problem with your browser

· If you are getting a core dump, gdb should inform you of this now

· type: bt

· Send the resulting backtrace to php-dev@lists.php.net

If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. (This should happen automatically with PHP and Apache 1.3.x)

2 I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?

Environment variables are now normal global variables, so you must either declare them as global variables in your function (by using "global $DOCUMENT_ROOT;", for example) or by using the global variable array (ie, "$GLOBALS["DOCUMENT_ROOT"]".

3 I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.

4 I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net.


8. Migrating from PHP2 to PHP3

1 When I add two strings together and then echo it, it echoes zero instead of the concatenation of the two strings! What's going on? Wouldn't it be great if adding two strings just concatenated them together?

PHP3 does not support the overloading of the addition operator for strings because values that arrive via the GET and POST methods and from databases are always stored as strings. This means that if the plus operator were overloaded to concatenate strings, you could add what you thought were two numbers and get the wrong result! (For example, "4" + "5" would be equal to "45".) One way around this would be to explicitly type-cast one or both of the operands, which is what PHP/FI 2 did.

This has been simplified in PHP3 by the addition of a real string concatenation operator. If you want to "add" two strings together, just write it like: "this" . "that" which will result in the string "thisthat".

The answer to the final part of the question is an emphatic no. Operator overloading can be a source of great confusion, especially when variables aren't very strongly typed to begin with, as they are in PHP3.

2 When I use the chmod(), umask(), or mkdir() functions, the permissions are wrong!

Unlike PHP/FI 2, PHP3 does not interpret the numeric arguments for these functions any differently than for any other function, which means you need to pass in an octal value if you are specifying an octal number, such as:

        chmod($myfile, 0600);

not

        chmod($myfile, 600);

3 I converted my script from PHP/FI 2.0 to PHP3 syntax, but now it just hangs! When I looked at the processes running on my server, there was one process that was chewing up all of the CPU cycles!

You probably missed the semi-colon on a while (condition); statement. This will cause PHP3 to spin out of control because it is simply executing an empty body for your while loop! Change the semi-colon to a colon and it should work correctly.

4 My user-functions don't work any more! I get a "Parse error (expecting '('" on the first line of the function.

PHP3's function declaration now resembles C function declarations, so your function should look like:

        function printsum($a, $b) {
           echo $a + $b;
        }
    

You can also use old-style function declarations by use the 'old_function' designation, like so:

        old_function printsum $a, $b (
           echo $a + $b;
        );
    

5 What happened to the securevar() function that was in PHP2? How can I make sure that a GET-method variable does not overwrite a POST-method one?

The securevar() function in PHP2 was a badly named function. It gave the impression that when used the POST-method was secure. It is not. It is only slightly more difficult to fake POST-method variables than GET-method ones.

There are a couple of ways to achieve similar things in PHP3. The most straightforward way is to do it manually by using the $HTTP_POST_VARSFAQ question 5.1 for instructions on how to enable it. To make sure that $foo, for example, comes from the POST data and nowhere else you would do: array. See

         $foo = $HTTP_POST_VARS["foo"];
  

A second way to do this is to change the gpc_order setting in your php3.ini file. The default setting is "GPC" which means that GET variables are parsed first followed by POST variables and lastly by COOKIE variables. This means that GET vars are overwritten by POST vars which are in turn overwritten by COOKIE vars. So, by default if you have the same variables in your GET and POST data the POST one will be the one that shows up in the main PHP symbol table and you would have to use the $HTTP_GET_VARS to get at it. Along with changing the order from "GPC" to something like "CGP" which would make POST variables have the highest priority, you can leave out any of the letters to completely disable PHP's ability to see a certain type of variable. If you never wanted GET-method data to be turned into PHP variables you could use a gpc_order setting of "PC".

Wednesday, November 21, 2007

PHP Interview Questions - Part 3

I. How can we send mail using JavaScript?

II. How can we repair a MySQL table?

III. What are the advantages of stored procedures, triggers, indexes?

IV. What is the maximum length of a table name, database name, and fieldname in MySQL?

V. How many values can the SET function of MySQL take?

VI. What are the other commands to know the structure of table using MySQL commands except explain command?

VII. How many tables will create when we create table, what are they?

VIII. What is the purpose of the following files having extensions 1) .frm 2) .myd 3) .myi? What do these files contain?

IX. What is maximum size of a database in MySQL?

X. Give the syntax of Grant and Revoke commands?

XI. What is Normalization?

XII. Suppose your Zend engine supports the mode Then how can u configure your PHP Zend engine to support mode ?

XIII. Shopping cart online validation i.e. how can we configure Paypal, etc.?

XIV. What is meant by nl2br()?

XV. Draw the architecture of Zend engine?

XVI. What are the current versions of apache, PHP, and mysql?

XVII. What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of combination of other software programmes, servers and operating systems?

XVIII. How can we encrypt and decrypt a data present in a mysql table using mysql?

XIX. How can we encrypt the username and password using PHP?

XX. What are the features and advantages of object-oriented programming?

XXI. What are the differences between procedure-oriented languages and object-oriented languages?

XXII. What is the use of friend function?

XXIII. What are the differences between public, private, protected, static, transient, final and volatile?

XXIV. How can we increase the execution time of a PHP script?

XXV. How can we take a backup of a mysql table and how can we restore it. ?

XXVI. How can we optimize or increase the speed of a mysql select query?

XXVII. How many ways can we get the value of current session id?

XXVIII. How can we destroy the session, how can we unset the variable of a session?

XXIX. How can we destroy the cookie?

XXX. How many ways we can pass the variable through the navigation between the pages?

XXXI. What is the difference between ereg_replace() and eregi_replace()?

XXXII. What are the different functions in sorting an array?

XXXIII. How can we know the count/number of elements of an array?

XXXIV. What is the PHP predefined variable that tells the What types of images that PHP supports?

XXXV. How can I know that a variable is a number or not using a JavaScript?

XXXVI. List out some tools through which we can draw E-R diagrams for mysql.

XXXVII. How can I retrieve values from one database server and store them in other database server using PHP?

XXXVIII. List out the predefined classes in PHP?

XXXIX. How can I make a script that can be bilanguage (supports English, German)?

XL. What are the difference between abstract class and interface?

XLI. How can we find the number of rows in a table using MySQL?

XLII. How can we find the number of rows in a result set using PHP?

XLIII. How many ways we can we find the current date using MySQL?

XLIV. What are the advantages and disadvantages of Cascading Style Sheets?

XLV. What type of inheritance that PHP supports?

XLVI. How can increase the performance of MySQL select query?

XLVII. What are the advantages/disadvantages of MySQL and PHP?

XLVIII. What is the difference between GROUP BY and ORDER BY in Sql?

XLIX. What is the difference between char and varchar data types?

L. What is the functionality of md5 function in PHP?

LI. How can I load data from a text file into a table?

LII. How can we know the number of days between two given dates using MySQL?

LIII. How can we know the number of days between two given dates using PHP?

LIV. How can we change the name of a column of a table?

LV. How can we change the name and data type of a column of a table?

LVI. What are the differences between drop a table and truncate a table?

LVII. When you want to show some part of a text displayed on an HTML page in red font color, what different possibilities are there to do this? What are the advantages/disadvantages of these methods?

LVIII. When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?

LIX. What are the different methods of passing data or information between two calls of a web page? What are the advantages/disadvantages of these methods?

LX. An Apache web server is running on a Linux system. Suddenly, the web server delivers the pages very slow. How could you find out possible reasons for that (when using system commands, please specify their names)?

LXI. What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?

LXII. A select query over a large table runs very slow because of the growing number of entries in that table. What different measures could be taken to improve speed?

LXIII. What is MIME?

LXIV. What is PEAR in PHP?

LXV. How can I use the COM components in PHP?

LXVI. How can I load the DLLs dynamically?

LXVII. How many ways we can give the output to a browser?

LXVIII. How can we know that a session is started or not?

LXIX. What is the default session time in PHP and how can I change it?

LXX. What changes I have to done in PHP.ini file for file uploading?

LXXI. What are the differences between MySQL_fetch_array(), MySQL_fetch_object(), MySQL_fetch_row()?

LXXII. How can I set a cron and how can i execute it in Unix, Linux, and windows?

LXXIII. Steps for the payment gateway processing?

LXXIV. How many ways I can register the variables into session?

LXXV. Explain different types of errors in PHP (i.e. arguments in errorreporting function)?

LXXVI. How many ways I can redirect a PHP page?

LXXVII. List out different arguments in PHP header function?

LXXVIII. What type of headers have to add in the mail function in which file a attached?

LXXIX. What is the difference between

LXXX. What are the differences between include() and include_once() functions?

LXXXI. Describe the importance of database abstraction layers in PHP and database connection?

LXXXII. Explain MySQL optimization?

LXXXIII. What is the difference between using copy() and move() function in PHP file uploading?

LXXXIV. What is the difference between Reply-to and Return-path in the headers of a mail function?

LXXXV. Explain about Type Juggling in PHP?

LXXXVI. How can I get the only name of the current executing file?

LXXXVII. How can I embed a Java program in PHP file and what changes have to be done in PHP.ini file?

LXXXVIII. How can I find what type of images that the PHP version supports?

LXXXIX. What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods?

XC. Who is the father of PHP and explain the changes in PHP versions?

XCI. How can we submit a form without a submit button?

XCII. In how many ways we can retrieve the date in the result set of mysql using PHP?

XCIII. What is the difference between mysql_fetch_object and mysql_fetch_array?

XCIV. What is the difference between $message and $$message?

XCV. How can we extract string ‘techinterviews.com ‘ from a string ‘http://www.techinterviews.com’ using regular expression of PHP?

XCVI. How can we create a database using PHP and mysql?

XCVII. What are the differences between require and include, include_once?

XCVIII. Can we use include (”techinterviews.php”) two times in a PHP page “makeit.PHP”?

XCIX. What are the different tables present in mysql, which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10)) ?

C. Functions in IMAP, POP3 AND LDAP?

CI. How can I execute a PHP script using command line?

CII. What are the different types of errors in PHP?

CIII. What is the functionality of the function strstr and stristr?

CIV. What are the differences between PHP 3 and PHP 4 and PHP 5?

CV. How can we convert asp pages to PHP pages?

CVI. What is the functionality of the function htmlentities?

CVII. How can we get second of the current time using date function?

CVIII. How can we convert the time zones using PHP?

CIX. What is meant by urlencode and urldocode?

CX. What is the difference between the functions unlink and unset?

CXI. How can we register the variables into a session?

CXII. How can we get the properties (size, type, width, height) of an image using PHP image functions?

CXIII. How can we get the browser properties using PHP?

CXIV. What is the maximum size of a file that can be uploaded using PHP and how can we change this?

Thursday, November 15, 2007

Dot Net Interview Questions - Part 15

19. Can I write my own .NET host?

Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box (http://staff.develop.com/jasonw/clr/readme.htm ). There is also a code sample in the .NET SDK called CorHost.

20. What is garbage collection?

Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

21. Is it true that objects don't always get destroyed immediately when the last reference goes away?

Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. There is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#:

22. Why doesn't the .NET runtime offer deterministic destruction?

Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap.Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

23. Is the lack of deterministic destruction in .NET a problem?

It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

24. Does non-deterministic destruction affect the usage of COM objects from managed code?

Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

25. I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?

An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources.

Microsoft recommend the following pattern:

public class CTest : IDisposable

{

public void Dispose()

{

... // Cleanup activities
GC.SuppressFinalize(this);

}

~CTest() // C# syntax hiding the Finalize() method

{ Dispose(); } }

In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

26. Do I have any control over the garbage collection algorithm?

A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately.

27. How can I find out what the garbage collector is doing?

Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to view them.


28. What is serialization?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

29. Does the .NET Framework have in-built support for serialization?

There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

30. I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?

It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents.SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

31. Can I customise the serialization process?

Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.

Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

32. Why is XmlSerializer so slow?

There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

33. Why do I get errors when I try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

34. XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?

Look at the InnerException property of the exception that is thrown to get a more specific error message.


35. What are attributes?

There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.

[serializable] public class CTest {}

The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you've come across Keith Brown's universal delegator you'll be familiar with this idea.

36. Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:

[AttributeUsage(AttributeTargets.Class)]

public class InspiredByAttribute : System.Attribute

{ public string InspiredBy;

public InspiredByAttribute( string inspiredBy )

{ InspiredBy = inspiredBy;

} }

[InspiredBy("Andy Mc's brilliant .NET FAQ")]

class CTest

{ } class Capp { public static void Main() {

object[] atts = typeof(CTest).GetCustomAttributes(true);

foreach( object att in atts )

if( att is InspiredByAttribute )

Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy );

}}

Dot Net Interview Questions - Part 14

1. What is .NET?

That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways".A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

2. Does .NET only apply to people building web-sites?

No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable
alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has
lots to interest you - not least ASP.NET.

3. When was .NET announced?

Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a

number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

4. When was the first version of .NET released?

The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.

5. What platforms does the .NET Framework run on?

The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home.

The Mono project is attempting to implement the .NET framework on Linux.

6. What languages does the .NET Framework support?

MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop .NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

7. Will the .NET Framework go through a standardisation process?

From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)."

Basic terminology

8. What is the CLR?

CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)Security model, Type system , All .NET base classes, Many .NET framework classes, Development, debugging, and profiling tools, Execution and code management

IL-to-native translators and optimizers


9. What is IL?

IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

10. What is C#?

C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced C sharp) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++." Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

11. What does 'managed' mean in the .NET context?

The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.

Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).

Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.

Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

12. What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

Assemblies

13. What is an assembly?

An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.

An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.

Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary. Finally, assemblies are the unit of versioning in .NET - more on this below.

14. What is the difference between a private assembly and a shared assembly?

Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

15. How do assemblies find each other?

By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

16. How does assembly versioning work?

Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.

The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.

Remember: versioning is only applied to shared assemblies, not private assemblies.

Application Domains

17. What is an Application Domain?

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate an application from other applications.

Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

18. How does an AppDomain get created?

AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.

using System;

using System.Runtime.Remoting;

public class CAppDomainInfo : MarshalByRefObject

{ public string GetAppDomainInfo()

{ return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;

} }

public class App

{ public static int Main()

{ AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );

ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );

CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());

string info = adInfo.GetAppDomainInfo();

Console.WriteLine( "AppDomain info: " + info );

return 0; } }

Dot Net Interview Questions - Part 13

  1. How to implement DataGrid in .NET? How would u make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables? If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why?
  2. How can we create Tree control in asp.net?
  3. Write a program in C# for checking a given number is PRIME or not.
  4. Write a program to find the angle between the hours and minutes in a clock
  5. Write a C# program to find the Factorial of n
  6. How do I upload a file from my ASP.NET page?
    In order to perform file upload in your ASP.NET page, you will need to use two classes: the System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile class. The HtmlInputFile class represents and HTML input control that the user will use on the client side to select a file to upload. The HttpPostedFile class represents the uploaded file and is obtained from the PostedFile property of the HtmlInputFile class. In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:

    Also, remember that the /data directory is the only directory with Write permissions enabled for the anonymous user. Therefore, you will need to make sure that the your code uploads the file to the /data directory or one of its subdirectories.
    Below is a simple example of how to upload a file via an ASP.NET page in C#.
    <%@ Import Namespace="System" %>
    <%@ Import Namespace="System.Web" %>
    <%@ Import Namespace="System.Web.UI.HtmlControls" %>
    <%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Drawing" %>


    upload_cs








    OnClick="UploadFile">




    uploaded

    bytes





  7. How do I send an email message from my ASP.NET page?
    You can use the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail class to send email in your ASPX pages. Below is a simple example of using this class to send mail in C# and VB.NET. In order to send mail through our mail server, you would want to make sure to set the static SmtpServer property of the SmtpMail class to mail-fwd.

    <%@ Import Namespace="System" %>
    <%@ Import Namespace="System.Web" %>
    <%@ Import Namespace="System.Web.Mail" %>


    Mail Test






  8. Write a program to create a user control with name and surname as data members and login as method and also the code to call it. (Hint use event delegates) Practical Example of Passing an Events to delegates
  9. How can you read 3rd line from a text file?

Dot Net Interview Questions - Part 12

  1. Can we do sorting in XSL ? how do you deal sorting columns dynamically in XML.
  2. What is “Async” property of XML Means ?
  3. What is XPath Query ?
  4. Difference Between Element and Node.
  5. What is CDATA Section.
  6. DOM & SAX parsers explanation and difference
  7. What is GetElementbyname method will do?
  8. What is selectnode method will give?
  9. What is valid xml document? What a well formed xml document?
  10. What is the Difference between XmlDocument and XmlDataDocument?
  11. Explain what a DiffGram is, and a good use for one?
    A DiffGram is an XML format that is used to identify current and original versions of data elements. When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used.
    The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.
    DiffGram Format
    The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section, as shown in the following example.


xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">









The DiffGram format consists of the following blocks of data:

<DataInstance>

The name of this element, DataInstance, is used for explanation purposes in this documentation. A DataInstance element represents a DataSet or a row of a DataTable. Instead of DataInstance, the element would contain the name of the DataSet or DataTable. This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the diffgr:hasChanges annotation.

This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

This block of the DiffGram format contains error information for a particular row in the DataInstance block. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

  1. If I replace my Sqlserver with XML files and how about handling the same?
  2. Write syntax to serialize class using XML Serializer?

    ---IIS---

  1. In which process does IIS runs (was asking about the EXE file)
    inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.
  2. Where are the IIS log files stored?
    C:\WINDOWS\system32\Logfiles\W3SVC1
    OR
    c:\winnt\system32\LogFiles\W3SVC1
  3. What are the different IIS authentication modes in IIS 5.0 and Explain? Difference between basic and digest authentication modes?
    IIS provides a variety of authentication schemes:
    • Anonymous (enabled by default)
    • Basic
    • Digest
    • Integrated Windows authentication (enabled by default)
    • Client Certificate Mapping

Anonymous
Anonymous authentication gives users access to the public areas of your Web site without prompting them for a user name or password. Although listed as an authentication scheme, it is not technically performing any client authentication because the client is not required to supply any credentials. Instead, IIS provides stored credentials to Windows using a special user account, IUSR_machinename. By default, IIS controls the password for this account. Whether or not IIS controls the password affects the permissions the anonymous user has. When IIS controls the password, a sub authentication DLL (iissuba.dll) authenticates the user using a network logon. The function of this DLL is to validate the password supplied by IIS and to inform Windows that the password is valid, thereby authenticating the client. However, it does not actually provide a password to Windows. When IIS does not control the password, IIS calls the LogonUser() API in Windows and provides the account name, password and domain name to log on the user using a local logon. After the logon, IIS caches the security token and impersonates the account. A local logon makes it possible for the anonymous user to access network resources, whereas a network logon does not.
Basic Authentication

IIS Basic authentication as an implementation of the basic authentication scheme found in section 11 of the HTTP 1.0 specification.
As the specification makes clear, this method is, in and of itself, non-secure. The reason is that Basic authentication assumes a trusted connection between client and server. Thus, the username and password are transmitted in clear text. More specifically, they are transmitted using Base64 encoding, which is trivially easy to decode. This makes Basic authentication the wrong choice to use over a public network on its own.
Basic Authentication is a long-standing standard supported by nearly all browsers. It also imposes no special requirements on the server side -- users can authenticate against any NT domain, or even against accounts on the local machine. With SSL to shelter the security credentials while they are in transmission, you have an authentication solution that is both highly secure and quite flexible.
Digest Authentication
The Digest authentication option was added in Windows 2000 and IIS 5.0. Like Basic authentication, this is an implementation of a technique suggested by Web standards, namely RFC 2069 (superceded by RFC 2617).
Digest authentication also uses a challenge/response model, but it is much more secure than Basic authentication (when used without SSL). It achieves this greater security not by encrypting the secret (the password) before sending it, but rather by following a different design pattern -- one that does not require the client to transmit the password over the wire at all.
Instead of sending the password itself, the client transmits a one-way message digest (a checksum) of the user's password, using (by default) the MD5 algorithm. The server then fetches the password for that user from a Windows 2000 Domain Controller, reruns the checksum algorithm on it, and compares the two digests. If they match, the server knows that the client knows the correct password, even though the password itself was never sent. (If you have ever wondered what the default ISAPI filter "md5filt" that is installed with IIS 5.0 is used for, now you know.
Integrated Windows Authentication
Integrated Windows authentication (formerly known as NTLM authentication and Windows NT Challenge/Response authentication) can use either NTLM or Kerberos V5 authentication and only works with Internet Explorer 2.0 and later.
When Internet Explorer attempts to access a protected resource, IIS sends two WWW-Authenticate headers, Negotiate and NTLM.

    • If Internet Explorer recognizes the Negotiate header, it will choose it because it is listed first. When using Negotiate, the browser will return information for both NTLM and Kerberos. At the server, IIS will use Kerberos if both the client (Internet Explorer 5.0 and later) and server (IIS 5.0 and later) are running Windows 2000 and later, and both are members of the same domain or trusted domains. Otherwise, the server will default to using NTLM.
    • If Internet Explorer does not understand Negotiate, it will use NTLM.

So, which mechanism is used depends upon a negotiation between Internet Explorer and IIS.
When used in conjunction with Kerberos v5 authentication, IIS can delegate security credentials among computers running Windows 2000 and later that are trusted and configured for delegation. Delegation enables remote access of resources on behalf of the delegated user.
Integrated Windows authentication is the best authentication scheme in an intranet environment where users have Windows domain accounts, especially when using Kerberos. Integrated Windows authentication, like digest authentication, does not pass the user's password across the network. Instead, a hashed value is exchanged.
Client Certificate Mapping
A certificate is a digitally signed statement that contains information about an entity and the entity's public key, thus binding these two pieces of information together. A trusted organization (or entity) called a Certification Authority (CA) issues a certificate after the CA verifies that the entity is who it says it is. Certificates can contain different types of data. For example, an X.509 certificate includes the format of the certificate, the serial number of the certificate, the algorithm used to sign the certificate, the name of the CA that issued the certificate, the name and public key of the entity requesting the certificate, and the CA's signature. X.509 client certificates simplify authentication for larger user bases because they do not rely on a centralized account database. You can verify a certificate simply by examining the certificate.

  1. How to configure the sites in Web server (IIS)?
  2. Advantages in IIS 6.0?
    http://www.microsoft.com/windowsserver2003/iis/evaluation/features/default.mspx
    http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechnol/windowsserver2003/proddocs/datacenter/gs_whatschanged.asp
  3. IIS Isolation Levels?
    Internet Information Server introduced the notion "Isolation Level", which is also present in IIS4 under a different name. IIS5 supports three isolation levels, that you can set from the Home Directory tab of the site's Properties dialog:
    • Low (IIS Process): ASP pages run in INetInfo.Exe, the main IIS process, therefore they are executed in-process. This is the fastest setting, and is the default under IIS4. The problem is that if ASP crashes, IIS crashes as well and must be restarted (IIS5 has a reliable restart feature that automatically restarts a server when a fatal error occurs).
    • Medium (Pooled): In this case ASP runs in a different process, which makes this setting more reliable: if ASP crashes IIS won't. All the ASP applications at the Medium isolation level share the same process, so you can have a web site running with just two processes (IIS and ASP process). IIS5 is the first Internet Information Server version that supports this setting, which is also the default setting when you create an IIS5 application. Note that an ASP application that runs at this level is run under COM+, so it's hosted in DLLHOST.EXE (and you can see this executable in the Task Manager).
    • High (Isolated): Each ASP application runs out-process in its own process space, therefore if an ASP application crashes, neither IIS nor any other ASP application will be affected. The downside is that you consume more memory and resources if the server hosts many ASP applications. Both IIS4 and IIS5 supports this setting: under IIS4 this process runs inside MTS.EXE, while under IIS5 it runs inside DLLHOST.EXE.

When selecting an isolation level for your ASP application, keep in mind that out-process settings - that is, Medium and High - are less efficient than in-process (Low). However, out-process communication has been vastly improved under IIS5, and in fact IIS5's Medium isolation level often deliver better results than IIS4's Low isolation. In practice, you shouldn't set the Low isolation level for an IIS5 application unless you really need to serve hundreds pages per second.

  1. How will you do Redo and Undo in a TextControl?

Dot Net Interview Questions - Part 11

  1. How you will protect / secure a web service?
    For the most part, things that you do to secure a Web site can be used to secure a Web Service. If you need to encrypt the data exchange, you use Secure Sockets Layer (SSL) or a Virtual Private Network to keep the bits secure. For authentication, use HTTP Basic or Digest authentication with Microsoft® Windows® integration to figure out who the caller is.
    these items cannot:
    • Parse a SOAP request for valid values
    • Authenticate access at the Web Method level (they can authenticate at the Web Service level)
    • Stop reading a request as soon as it is recognized as invalid
  2. How will you expose/publish a webservice?
  3. What is disco file?
  4. What’s the attribute for webservice method? What is the namespace for creating webservice?
    [WebMethod]
    using System.Web;
    using System.Web.Services;
  5. What is Remoting?
    The process of communication between different operating system processes, regardless of whether they are on the same computer. The .NET remoting system is an architecture designed to simplify communication between objects living in different application domains, whether on the same computer or not, and between different contexts, whether in the same application domain or not.
  6. Difference between web services & remoting?

ASP.NET Web Services

.NET Remoting

Protocol

Can be accessed only over HTTP

Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

State Management

Web services work in a stateless environment

Provide support for both stateful and stateless environments through Singleton and SingleCall objects

Type System

Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized.

Using binary communication, .NET Remoting can provide support for rich type system

Interoperability

Web services support interoperability across platforms, and are ideal for heterogeneous environments.

.NET remoting requires the client be built using .NET, enforcing homogenous environment.

Reliability

Highly reliable due to the fact that Web services are always hosted in IIS

Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application.

Extensibility

Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages.

Very extensible by allowing us to customize the different components of the .NET remoting framework.

Ease-of-Programming

Easy-to-create and deploy.

Complex to program.

Though both the .NET Remoting infrastructure and ASP.NET Web services can enable cross-process communication, each is designed to benefit a different target audience. ASP.NET Web services provide a simple programming model and a wide reach. .NET Remoting provides a more complex programming model and has a much narrower reach.
As explained before, the clear performance advantage provided by TCPChannel-remoting should make you think about using this channel whenever you can afford to do so. If you can create direct TCP connections from your clients to your server and if you need to support only the .NET platform, you should go for this channel. If you are going to go cross-platform or you have the requirement of supporting SOAP via HTTP, you should definitely go for ASP.NET Web services.
Both the .NET remoting and ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications. It is important to understand how both technologies work and then choose the one that is right for your application. For applications that require interoperability and must function over public networks, Web services are probably the best bet. For those that require communications with other .NET components and where performance is a key priority, .NET Remoting is the best choice. In short, use Web services when you need to send and receive data from different computing platforms, use .NET Remoting when sending and receiving data between .NET applications. In some architectural scenarios, you might also be able to use.NET Remoting in conjunction with ASP.NET Web services and take advantage of the best of both worlds.
The Key difference between ASP.NET webservices and .NET Remoting is how they serialize data into messages and the format they choose for metadata. ASP.NET uses XML serializer for serializing or Marshalling. And XSD is used for Metadata. .NET Remoting relies on
System.Runtime.Serialization.Formatter.Binary and System.Runtime.Serialization.SOAPFormatter and relies on .NET CLR Runtime assemblies for metadata.

  1. Can you pass SOAP messages through remoting?
  2. CAO and SAO.
    Client Activated objects are those remote objects whose Lifetime is directly Controlled by the client. This is in direct contrast to SAO. Where the server, not the client has complete control over the lifetime of the objects.
    Client activated objects are instantiated on the server as soon as the client request the object to be created. Unlike as SAO a CAO doesn’t delay the object creation until the first method is called on the object. (In SAO the object is instantiated when the client calls the method on the object)
  3. singleton and singlecall.
    Singleton
    types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance.
    Single Call types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system.
  4. What is Asynchronous Web Services?
  5. Web Client class and its methods?
  6. Flow of remoting?
  7. What is the use of trace utility?
    Using the SOAP Trace Utility
    The Microsoft® Simple Object Access Protocol (SOAP) Toolkit 2.0 includes a TCP/IP trace utility, MSSOAPT.EXE. You use this trace utility to view the SOAP messages sent by HTTP between a SOAP client and a service on the server.

Using the Trace Utility on the Server
To see all of a service's messages received from and sent to all clients, perform the following steps on the server.

    1. On the server, open the Web Services Description Language (WSDL) file.
    2. In the WSDL file, locate the element that corresponds to the service and change the location attribute for this element to port 8080. For example, if the location attribute specifies change this attribute to .
    3. Run MSSOAPT.exe.
    4. On the File menu, point to New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
    5. In the Trace Setup dialog box, click OK to accept the default values.

Using the Trace Utility on the Client
To see all messages sent to and received from a service, do the following steps on the client.

    1. Copy the WSDL file from the server to the client.
    2. Modify location attribute of the element in the local copy of the WSDL document to direct the client to localhost:8080 and make a note of the current host and port. For example, if the WSDL contains , change it to and make note of "MyServer".
    3. On the client, run MSSOPT.exe.
    4. On the File menu, point to New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
    5. In the Destination host box, enter the host specified in Step 2.
    6. In the Destination port box, enter the port specified in Step 2.
    7. Click OK.
  1. Explain the concept of data island?
  2. How to use XML DOM model on client side using JavaScript.
  3. What are the ways to create a tree view control using XML, XSL & JavaScript?
  4. Questions on XPathNavigator, and the other classes in System.XML Namespace?
  5. What is Use of Template in XSL?
  6. What is “Well Formed XML” and “Valid XML”
  7. How you will do SubString in XSL

Dot Net Interview Questions - Part 10

  1. What are the different modes for the sessionstates in the web.config file?

Off

Indicates that session state is not enabled.

Inproc

Indicates that session state is stored locally.

StateServer

Indicates that session state is stored on a remote server.

SQLServer

Indicates that session state is stored on the SQL Server.

  1. What is smart navigation?
    When a page is requested by an Internet Explorer 5 browser, or later, smart navigation enhances the user's experience of the page by performing the following:
    • eliminating the flash caused by navigation.
    • persisting the scroll position when moving from page to page.
    • persisting element focus between navigations.
    • retaining only the last page state in the browser's history.

Smart navigation is best used with ASP.NET pages that require frequent postbacks but with visual content that does not change dramatically on return. Consider this carefully when deciding whether to set this property to true.
Set the SmartNavigation attribute to true in the @ Page directive in the .aspx file. When the page is requested, the dynamically generated class sets this property.

  1. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?
  2. How would you get ASP.NET running in Apache web servers - why would you even do this?
  3. What tags do you need to add within the asp:datagrid tags to bind columns manually
  4. What base class do all Web Forms inherit from? System.Web.UI.Page
  5. How can we create pie chart in asp.net?
  6. Is it possible for me to change my aspx file extension to some other name?Yes.
    Open IIS->Default Website -> Properties
    Select HomeDirectory tab
    Click on configuration button
    Click on add. Enter aspnet_isapi details (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG)

    Open machine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG) & add new extension under tag
  7. What is AutoEventWireup attribute for ?

    ---WEBSERVICE & REMOTING---

  1. What is a WebService and what is the underlying protocol used in it?Why Web Services?
    Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.
    There are three main uses of Web services.
    1. Application integration Web services within an intranet are commonly used to integrate business applications running on disparate platforms. For example, a .NET client running on Windows 2000 can easily invoke a Java Web service running on a mainframe or Unix machine to retrieve data from a legacy application.
    2. Business integration Web services allow trading partners to engage in e-business leveraging the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code.
    3. Commercial Web services focus on selling content and business services to clients over the Internet similar to familiar Web pages. Unlike Web pages, commercial Web services target applications not humans as their direct users. Continental Airlines exposes flight schedules and status Web services for travel Web sites and agencies to use in their applications. Like Web pages, commercial Web services are valuable only if they expose a valuable service or content. It would be very difficult to get customers to pay you for using a Web service that creates business charts with the customers? data. Customers would rather buy a charting component (e.g. COM or .NET component) and install it on the same machine as their application. On the other hand, it makes sense to sell real-time weather information or stock quotes as a Web service. Technology can help you add value to your services and explore new markets, but ultimately customers pay for contents and/or business services, not for technology
  1. Are Web Services a replacement for other distributed computing platforms?
    No. Web Services is just a new way of looking at existing implementation platforms.
  2. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice? Ans: WebService will support only DataSet.
  3. How to generate WebService proxy? What is SOAP, WSDL, UDDI and the concept behind Web Services? What are various components of WSDL? What is the use of WSDL.exe utility?
    SOAP is an XML-based messaging framework specifically designed for exchanging formatted data across the Internet, for example using request and reply messages or sending entire documents. SOAP is simple, easy to use, and completely neutral with respect to operating system, programming language, or distributed computing platform.
    After SOAP became available as a mechanism for exchanging XML messages among enterprises (or among disparate applications within the same enterprise), a better way was needed to describe the messages and how they are exchanged. The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL spec describes how to map messages and operations to SOAP 1.1, HTTP GET/POST, and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols (using "ports").
    The Universal Description, Discovery, and Integration (UDDI) framework defines a data model (in XML) and SOAP APIs for registration and searches on business information, including the web services a business exposes to the Internet. UDDI is an independent consortium of vendors, founded by Microsoft, IBM, and Ariba, for the purpose of developing an Internet standard for web service description registration and discovery. Microsoft, IBM, and Ariba also are hosting the initial deployment of a UDDI service, which is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses). UDDI uses a private agreement profile of SOAP (i.e. UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use the SOAP APIs to register themselves with UDDI, and other businesses search UDDI when they want to discover a trading partner, for example someone from whom they wish to procure sheet metal, bolts, or transistors. The information in UDDI is categorized according to industry type and geographical location, allowing UDDI consumers to search through lists of potentially matching businesses to find the specific one they want to contact. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes.
  4. How to generate proxy class other than .net app and wsdl tool?
    To access an XML Web service from a client application, you first add a Web reference, which is a reference to an XML Web service. When you create a Web reference, Visual Studio creates an XML Web service proxy class automatically and adds it to your project. This proxy class exposes the methods of the XML Web service and handles the marshalling of appropriate arguments back and forth between the XML Web service and your application. Visual Studio uses the Web Services Description Language (WSDL) to create the proxy.
    To generate an XML Web service proxy class:
    • From a command prompt, use Wsdl.exe to create a proxy class, specifying (at a minimum) the URL to an XML Web service or a service description, or the path to a saved service description.
      Wsdl /language:language /protocol:protocol /namespace:myNameSpace /out:filename
      /username:username /password:password /domain:domain
  1. What is a proxy in web service? How do I use a proxy server when invoking a Web service?
  2. asynchronous web service means?
  3. What are the events fired when web service called?
  4. How will do transaction in Web Services?
  5. How does SOAP transport happen and what is the role of HTTP in it? How you can access a webservice using soap?
  6. What are the different formatters can be used in both? Why?.. binary/soap

Wednesday, November 14, 2007

Dot Net Interview Questions - Part 9

  1. How do you implement postback with a text box? What is postback and usestate?
    Make AutoPostBack property to true
  2. How can you debug an ASP page, without touching the code?
  3. What is SQL injection?
    An SQL injection attack "injects" or manipulates SQL code by adding unexpected SQL to a query.
    Many web pages take parameters from web user, and make SQL query to the database. Take for instance when a user login, web page that user name and password and make SQL query to the database to check if a user has valid name and password.
    Username: ' or 1=1 ---
    Password: [Empty]
    This would execute the following query against the users table:
    select count(*) from users where userName='' or 1=1 --' and userPass=''
  4. How can u handle Exceptions in Asp.Net?
  5. How can u handle Un Managed Code Exceptions in ASP.Net?
  6. Asp.net - How to find last error which occurred?
    A: Server.GetLastError();
    [C#]
    Exception LastError;
    String ErrMessage;
    LastError = Server.GetLastError();
    if (LastError != null)
    ErrMessage = LastError.Message;
    else
    ErrMessage = "No Errors";
    Response.Write("Last Error = " + ErrMessage);

7. How to do Caching in ASP?
A: <%@ OutputCache Duration="60" VaryByParam="None" %>

VaryByParam value

Description

none

One version of page cached (only raw GET)

*

n versions of page cached based on query string and/or POST body

v1

n versions of page cached based on value of v1 variable in query string or POST body

v1;v2

n versions of page cached based on value of v1 and v2 variables in query string or POST body

<%@ OutputCache Duration="60" VaryByParam="none" %>
<%@ OutputCache Duration="60" VaryByParam="*" %>
<%@ OutputCache Duration="60" VaryByParam="name;age" %>

The OutputCache directive supports several other cache varying options

    • VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.)
    • VaryByControl - for user controls, maintain separate cache entry for properties of a user control
    • VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplicationderived class
  1. What is the Global ASA(X) File?

  1. Any alternative to avoid name collisions other then Namespaces.
    A scenario that two namespaces named N1 and N2 are there both having the same class say A. now in another class i ve written
    using N1;using N2;
    and i am instantiating class A in this class. Then how will u avoid name collisions?
    Ans: using alias
    Eg:
    using MyAlias = MyCompany.Proj.Nested;
  2. Which is the namespace used to write error message in event Log File?
  3. What are the page level transaction and class level transaction?
  4. What are different transaction options?
  5. What is the namespace for encryption?
  6. What is the difference between application and cache variables?
  7. What is the difference between control and component?
  8. You ve defined one page_load event in aspx page and same page_load event in code behind how will prog run?
  9. Where would you use an IHttpModule, and what are the limitations of any approach you might take in implementing one?
  10. Can you edit data in the Repeater control? Which template must you provide, in order to display data in a Repeater control? How can you provide an alternating color scheme in a Repeater control? What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
  11. What is the use of web.config? Difference between machine.config and Web.config?
    ASP.NET configuration files are XML-based text files--each named web.config--that can appear in any directory on an ASP.NET Web application server. Each web.config file applies configuration settings to the directory it is located in and to all virtual child directories beneath it. Settings in child directories can optionally override or modify settings specified in parent directories. The root configuration file--WinNT\Microsoft.NET\Framework\\config\machine.config—provides default configuration settings for the entire machine. ASP.NET configures IIS to prevent direct browser access to web.config
    files to ensure that their values cannot become public (attempts to access them will cause ASP.NET to return 403: Access Forbidden).
    At run time ASP.NET uses these web.config configuration files to hierarchically compute a unique collection of settings for each incoming URL target request (these settings are calculated only once and then cached across subsequent requests; ASP.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change).
What is the use of sessionstate tag in the web.config file?
Configuring session state:
Session state features can be configured via the section in a web.config file. To double the default timeout of 20 minutes, you can add the following to the web.config file of an application:

Dot Net Interview Questions - Part 8

  1. Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform?
    A: Many of the ASP.NET configuration options are not configurable at the site, application or subdirectory level on the shared hosting platform. Certain options can affect the security, performance and stability of the server and, therefore cannot be changed. The following settings are the only ones that can be changed in your site’s web.config file (s):
    browserCaps
    clientTarget
    pages
    customErrors
    globalization
    authorization
    authentication
    webControls
    webServices
  2. Briefly describe the role of global.asax?
  3. How can u debug your .net application?
  4. How do u deploy your asp.net application?
  5. Where do we store our connection string in asp.net application?
  6. Various steps taken to optimize a web based application (caching, stored procedure etc.)
  7. How does ASP.NET framework maps client side events to Server side events.

  8. Security types in ASP/ASP.NET? Different Authentication modes?
  9. How .Net has implemented security for web applications?
  10. How to do Forms authentication in asp.net?
  11. Explain authentication levels in .net ?
  12. Explain autherization levels in .net ?
  13. What is Role-Based security?
    A role is a named set of principals that have the same privileges with respect to security (such as a teller or a manager). A principal can be a member of one or more roles. Therefore, applications can use role membership to determine whether a principal is authorized to perform a requested action.
  14. How will you do windows authentication and what is the namespace? If a user is logged under integrated windows authentication mode, but he is still not able to logon, what might be the possible cause for this? In ASP.Net application how do you find the name of the logged in person under windows authentication?
  15. What are the different authentication modes in the .NET environment?
     ="Windows|Forms|Passport|None">
       ="name"
         loginUrl="url" 
         protection="All|None|Encryption|Validation"
         timeout="30" path="/" >
         requireSSL="true|false"
         slidingExpiration="true|false">
         ="Clear|SHA1|MD5">
            ="username" password="password"/>
         
       
       internal"/>
  

Attribute

Option

Description

Mode


Controls the default authentication mode for an application.


Windows

Specifies Windows authentication as the default authentication mode. Use this mode when using any form of Microsoft Internet Information Services (IIS) authentication: Basic, Digest, Integrated Windows authentication (NTLM/Kerberos), or certificates.


Forms

Specifies ASP.NET forms-based authentication as the default authentication mode.


Passport

Specifies Microsoft Passport authentication as the default authentication mode.


None

Specifies no authentication. Only anonymous users are expected or applications can handle events to provide their own authentication.

  1. How do you specify whether your data should be passed as Query string and Forms (Mainly about POST and GET)
    Through attribute tag of form tag.
  2. What is the other method, other than GET and POST, in ASP.NET?
  3. What are validator? Name the Validation controls in asp.net? How do u disable them? Will the asp.net validators run in server side or client side? How do you do Client-side validation in .Net? How to disable validator control by client side JavaScript?
    A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation ("EnableClientScript" property set to true/false) using client script.
    The following validation controls are available in asp.net:
    RequiredFieldValidator Control, CompareValidator Control, RangeValidator Control, RegularExpressionValidator Control, CustomValidator Control, ValidationSummary Control.
  4. Which two properties are there on every validation control? ControlToValidate, ErrorMessage
How do you use css in asp.net?
Within the section of an HTML document that will use these styles, add a link to this external CSS style sheet that
follows this form:

MyStyles.css is the name of your external CSS style sheet.

Dot Net Interview Questions - Part 7

  1. How do u implement locking concept for dataset?

  2. Asp.net and asp – differences?

Code Render Block

Code Declaration Block

Compiled

Request/Response

Event Driven

Object Oriented - Constructors/Destructors, Inheritance, overloading..

Exception Handling - Try, Catch, Finally

Down-level Support

Cultures

User Controls

In-built client side validation

Session - weren't transferable across servers

It can span across servers, It can survive server crashes, can work with browsers that don't support cookies

built on top of the window & IIS, it was always a separate entity & its functionality was limited.

its an integral part of OS under the .net framework. It shares many of the same objects that traditional applications would use, and all .net objects are available for asp.net's consumption.

Garbage Collection

Declare variable with datatype

In built graphics support

Cultures

  1. How ASP and ASP.NET page works? Explain about asp.net page life cycle?
  2. Order of events in an asp.net page? Control Execution Lifecycle?

Phase

What a control needs to do

Method or event to override

Initialize

Initialize settings needed during the lifetime of the incoming Web request.

Init event (OnInit method)

Load view state

At the end of this phase, the ViewState property of a control is automatically populated as described in Maintaining State in a Control. A control can override the default implementation of the LoadViewState method to customize state restoration.

LoadViewState method

Process postback data

Process incoming form data and update properties accordingly.

LoadPostData method (if IPostBackDataHandler is implemented)

Load

Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data.

Load event

(OnLoad method)

Send postback change notifications

Raise change events in response to state changes between the current and previous postbacks.

RaisePostDataChangedEvent method (if IPostBackDataHandler is implemented)

Handle postback events

Handle the client-side event that caused the postback and raise appropriate events on the server.

RaisePostBackEvent method(if IPostBackEventHandler is implemented)

Prerender

Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost.

PreRender event
(OnPreRender method)

Save state

The ViewState property of a control is automatically persisted to a string object after this stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a control can override the SaveViewState method to modify the ViewState property.

SaveViewState method

Render

Generate output to be rendered to the client.

Render method

Dispose

Perform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.

Dispose method

Unload

Perform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.

UnLoad event (On UnLoad method)

Note To override an EventName event, override the OnEventName method (and call base.OnEventName)

  1. What are server controls?
    ASP.NET server controls are components that run on the server and encapsulate user-interface and other related functionality. They are used in ASP.NET pages and in ASP.NET code-behind classes.
  2. What is the difference between Web User Control and Web Custom Control?
    Custom Controls
    Web custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.
    There are several ways that you can create Web custom controls:
    • You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box, you can create it by compiling the existing controls together.
    • If an existing server control almost meets your requirements but lacks some required features, you can customize the control by deriving from it and overriding its properties, methods, and events.
    • If none of the existing Web server controls (or their combinations) meet your requirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the basic functionality of Web server controls, so you can focus on programming the features you need.

If none of the existing ASP.NET server controls meet the specific requirements of your applications, you can create either a Web user control or a Web custom control that encapsulates the functionality you need. The main difference between the two controls lies in ease of creation vs. ease of use at design time.
Web user controls
are easy to make, but they can be less convenient to use in advanced scenarios. You develop Web user controls almost exactly the same way that you develop Web Forms pages. Like Web Forms, user controls can be created in the visual designer, they can be written with code separated from the HTML, and they can handle execution events. However, because Web user controls are compiled dynamically at run time they cannot be added to the Toolbox, and they are represented by a simple placeholder glyph when added to a page. This makes Web user controls harder to use if you are accustomed to full Visual Studio .NET design-time support, including the Properties window and Design view previews. Also, the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control.
Web custom controls
are compiled code, which makes them easier to use but more difficult to create; Web custom controls must be authored in code. Once you have created the control, however, you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition, you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.

Web user controls

Web custom controls

Easier to create

Harder to create

Limited support for consumers who use a visual design tool

Full visual design tool support for consumers

A separate copy of the control is required in each application

Only a single copy of the control is required, in the global assembly cache

Cannot be added to the Toolbox in Visual Studio

Can be added to the Toolbox in Visual Studio

Good for static layout

Good for dynamic layout

  1. Application and Session Events
    The ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:
    • Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request.
    • Session events are similar to application events (there is a Session_OnStart and a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.

You can create handlers for these types of events in the Global.asax file.

  1. Difference between ASP Session and ASP.NET Session?
    asp.net session supports cookie less session & it can span across multiple servers.
  2. What is cookie less session? How it works?
    By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following:
  3. How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are the limits?
    By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session data in an external process, which can even reside on another machine. To enable this feature:
    • Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port
    • Set the mode attribute of the section to "StateServer".
    • Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.

The following sample assumes that the state service is running on the same machine as the Web server ("localhost") and uses the default port (42424):

Note that if you try the sample above with this setting, you can reset the Web server (enter iisreset on the command line) and the session state value will persist.

  1. What method do you use to explicitly kill a users session?Abandon()
  2. What are the different ways you would consider sending data across pages in ASP (i.e between 1.asp to 2.asp)?Session, public properties
  3. What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?
    Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip.
    To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips.
    However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
    Client-Based State Management Options:
    View State
    Hidden Form Fields
    Cookies
    Query Strings
    Server-Based
    State Management Options
    Application State
    Session State

    Database Support
  4. What are the disadvantages of view state / what are the benefits?
    Automatic view-state management is a feature of server controls that enables them to repopulate their property values on a round trip (without you having to write any code). This feature does impact performance, however, since a server control's view state is passed to and from the server in a hidden form field. You should be aware of when view state helps you and when it hinders your page's performance.
  5. When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade?
    Maintaining state using database technology is a common practice when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted.
  6. What are the contents of cookie?
  7. How do you create a permanent cookie?
  8. What is ViewState? What does the "EnableViewState" property do?Why would I want it on or off?
  9. Explain the differences between Server-side and Client-side code?
    Server side code will process at server side & it will send the result to client. Client side code (javascript) will execute only at client side.
  10. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?

Dot Net Interview Questions - Part 6

  1. What’s different about switch statements in C#?
    No fall-throughs allowed. Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case, or goto default.
    case 1:
    cost += 25;
    break;
    case 2:
    cost += 25;
    goto case 1;


  2. Advantage of ADO.Net?
    • ADO.NET Does Not Depend On Continuously Live Connections
    • Database Interactions Are Performed Using Data Commands
    • Data Can Be Cached in Datasets
    • Datasets Are Independent of Data Sources
    • Data Is Persisted as XML
    • Schemas Define Data Structures
  3. How would u connect to database using .NET?
    SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" + "Initial Catalog=northwind");
    nwindConn.Open();
  4. What are relation objects in dataset and how & where to use them?
    In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table.
    The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.
    custDS.Relations.Add("CustOrders",
    custDS.Tables["Customers"].Columns["CustID"],
    custDS.Tables["Orders"].Columns["CustID"]);

    OR
    private void CreateRelation()
    {
    // Get the DataColumn objects from two DataTable objects in a DataSet.
    DataColumn parentCol;
    DataColumn childCol;
    // Code to get the DataSet not shown here.
    parentCol = DataSet1.Tables["Customers"].Columns["CustID"];
    childCol = DataSet1.Tables["Orders"].Columns["CustID"];
    // Create DataRelation.
    DataRelation relCustOrder;
    relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
    // Add the relation to the DataSet.
    DataSet1.Relations.Add(relCustOrder);
    }

5. Difference between OLEDB Provider and SqlClient ?
Ans: SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.

  1. What are the different namespaces used in the project to connect the database? What data providers available in .net to connect to database?
    • System.Data.OleDb – classes that make up the .NET Framework Data Provider for OLE DB-compatible data sources. These classes allow you to connect to an OLE DB data source, execute commands against the source, and read the results.
    • System.Data.SqlClient – classes that make up the .NET Framework Data Provider for SQL Server, which allows you to connect to SQL Server 7.0, execute commands, and read results. The System.Data.SqlClient namespace is similar to the System.Data.OleDb namespace, but is optimized for access to SQL Server 7.0 and later.
    • System.Data.Odbc - classes that make up the .NET Framework Data Provider for ODBC. These classes allow you to access ODBC data source in the managed space.
    • System.Data.OracleClient - classes that make up the .NET Framework Data Provider for Oracle. These classes allow you to access an Oracle data source in the managed space.
  2. Difference between DataReader and DataAdapter / DataSet and DataAdapter?
    You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory.
    After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example.
    SqlDataReader myReader = myCommand.ExecuteReader();
    You use the Read method of the DataReader object to obtain a row from the results of the query.
    while (myReader.Read())
    Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
    myReader.Close();
    The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.
    The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.
  3. Which method do you invoke on the DataAdapter control to load your generated dataset with data? Fill()
  4. Explain different methods and Properties of DataReader which you have used in your project?
    1. Read
    2. GetString
    3. GetInt32
    while (myReader.Read())
    Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
    myReader.GetString(1));
    myReader.Close();
  5. What happens when we issue Dataset.ReadXml command?
    Reads XML schema and data into the DataSet.
  6. In how many ways we can retrieve table records count? How to find the count of records in a dataset?
    foreach(DataTable thisTable in myDataSet.Tables){
    // For each row, print the values of each column.
    foreach(DataRow myRow in thisTable.Rows){
  7. How to check if a datareader is closed or opened? IsClosed()
  8. What happens when u try to update data in a dataset in .NET while the record is already deleted in SQL SERVER as backend?
    OR What is concurrency? How will you avoid concurrency when dealing with dataset? (One user deleted one row after that another user through his dataset was trying to update same row. What will happen? How will you avoid the problem?)
  9. How do you merge 2 datasets into the third dataset in a simple manner? OR If you are executing these statements in commandObject. "Select * from Table1;Select * from Table2” how you will deal result set?
  10. How do you sort a dataset?
  11. If a dataset contains 100 rows, how to fetch rows between 5 and 15 only?
  12. Differences between dataset.clone and dataset.copy?
    Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
    Copy - Copies both the structure and data for this DataSet.
  13. What is the use of parameter object?
  14. How to generate XML from a dataset and vice versa?
  15. What is method to get XML and schema from Dataset?
    ans: getXML () and get Schema ()

Dot Net Interview Questions - Part 5

  1. Can you explain what inheritance is and an example of when you might use it?
  2. How can you write a class to restrict that only one object of this class can be created (Singleton class)?
  3. What are the access-specifiers available in c#?
    Private, Protected, Public, Internal, Protected Internal.
  4. Explain about Protected and protected internal, “internal” access-specifier?
    protected - Access is limited to the containing class or types derived from the containing class.
    internal - Access is limited to the current assembly.
    protected internal - Access is limited to the current assembly or types derived from the containing class.
  5. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?
    (Class constructor method is also known as type constructor or type initializer)
    Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention.
    A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.
  6. What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?
    A: When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes)
    Make a constructor private if:
    - You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.
    - You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.
  7. I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private?(yes)
  8. Overloaded constructor will call default constructor internally?(no)
  9. What are virtual destructors?
  10. Destructor and finalize
    Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors.
    In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .Net frameworks Garbage Collector (GC). GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method.
    Points to remember:
    1. Destructors are invoked automatically, and cannot be invoked explicitly.
    2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
    3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
    4. Destructors cannot be used with structs. They are only used with classes.
    5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
    6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
    7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
  11. What is the difference between Finalize and Dispose (Garbage collection)
    Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.
    In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
    Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.
  12. What is close method? How its different from Finalize & Dispose?
  13. What is boxing & unboxing?
  14. What is check/uncheck?
  15. What is the use of base keyword? Tell me a practical example for base keyword’s usage?
  16. What are the different .net tools which u used in projects?
  17. try
    {
    ...
    }
    catch
    {
    ...//exception occurred here. What'll happen?
    }
    finally
    {
    ..
    }

    Ans : It will throw exception.
  18. What will do to avoid prior case?
    try
   {
    try
    {
      ...
    }
    catch
    {
     ...
     //exception occurred here.
    }
    finally
    {
     ...
    }
   }
   catch
   {
     ...
   }
   finally{...}
19.       try
     {
       ...
     }
     catch
     {
       ...
     }
     finally
     {
       ...
     } 

Will it go to finally block if there is no exception happened?
Ans: Yes. The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits.

  1. Is goto statement supported in C#? How about Java?
    Gotos are supported in C#to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.

Dot Net Interview Questions - Part 4

  1. What is the new three features of COM+ services, which are not there in COM (MTS)?
  2. Is the COM architecture same as .Net architecture? What is the difference between them?
  3. Can we copy a COM dll to GAC folder?
  4. What is Pinvoke?
    Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic-link libraries (DLLs), such as those in the Win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed.
  5. Is it true that COM objects no longer need to be registered on the server?
    Answer: Yes and No. Legacy COM objects still need to be registered on the server before they can be used. COM developed using the new .NET Framework will not need to be registered. Developers will be able to auto-register these objects just by placing them in the 'bin' folder of the application.
  6. Can .NET Framework components use the features of Component Services?
    Answer: Yes, you can use the features and functions of Component Services from a .NET Framework component.
  7. What are the OOPS concepts?
    1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data.
    2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors.
    3) Polymorphism: It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. In general polymorphism means "one interface, multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation.
  8. What is the difference between a Struct and a Class?
    • The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.
    • When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.
    • It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values.
    • It is an error to initialize an instance field in a struct.
    • There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.
    • A struct is a value type, while a class is a reference type.
  9. Value type & reference types difference? Example from .NET. Integer & struct are value types or reference types in .NET?
    Most programming languages provide built-in data types, such as integers and floating-point numbers, that are copied when they are passed as arguments (that is, they are passed by value). In the .NET Framework, these are called value types. The runtime supports two kinds of value types:
    • Built-in value types
      The .NET Framework defines built-in value types, such as System.Int32 and System.Boolean, which correspond and are identical to primitive data types used by programming languages.
    • User-defined value types
      Your language will provide ways to define your own value types, which derive from System.ValueType. If you want to define a type representing a value that is small, such as a complex number (using two floating-point numbers), you might choose to define it as a value type because you can pass the value type efficiently by value. If the type you are defining would be more efficiently passed by reference, you should define it as a class instead.

Variables of reference types, referred to as objects, store references to the actual data. This following are the reference types:

    • class
    • interface
    • delegate

This following are the built-in reference types:

    • object
    • string
  1. What is Inheritance, Multiple Inheritance, Shared and Repeatable Inheritance?
  2. What is Method overloading?
    Method overloading occurs when a class contains two methods with the same name, but different signatures.
  3. What is Method Overriding? How to override a function in C#?
    Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
    You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
  4. Can we call a base class method without creating instance?
    Its possible If its a static method.
    Its possible by inheriting from that class also.
    Its possible from derived classes using base keyword.
  5. You have one base class virtual function how will call that function from derived class?
    class a
   {
      public virtual int m()
      {
         return 1;
      }
   }
   class b:a
   {
      public int j()
      {
         return m();
      }
}
  1. In which cases you use override and new base?
    Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

---C# Language features---

  1. What are Sealed Classes in C#?
    The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
  2. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
  3. class Token
   {
      public string Display()
      {
       //Implementation goes here
       return "base";
      }
   }
   class IdentifierToken:Token
   {
      public new string Display() //What is the use of new keyword
      {
       //Implementation goes here
       return "derive";
      }
   }
      static void Method(Token t)
      {
        Console.Write(t.Display());
      }
      public static void Main()
      {
        IdentifierToken Variable=new IdentifierToken();
        Method(Variable); //Which Class Method is called here
        Console.ReadLine();
      }
For the above code What is the "new" keyword and Which Class Method is called here

Ans: it will call base class Display method

 
       class Token
       {
         public virtual string Display()
         {
          //Implementation goes here
          return "base";
         }
       }
       class IdentifierToken:Token
       {
         public override string Display() //What is the use of new keyword
         {
          //Implementation goes here
          return "derive";
         }
       }
       static void Method(Token t)
       {
         Console.Write(t.Display());
       }
       public static void Main()
       {
         IdentifierToken Variable=new IdentifierToken();
         Method(Variable); //Which Class Method is called here
         Console.ReadLine();
       }

A: Derive

  1. In which Scenario you will go for Interface or Abstract Class?
    Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
    Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

Feature

Interface

Abstract class

Multiple inheritance

A class may implement several interfaces.

A class may extend only one abstract class.

Default implementation

An interface cannot provide any code at all, much less default code.

An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

Constants

Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.

Both instance and static constants are possible