Complete Dot Net Interview Question and Answers
Complete Dot Net Interview Question and Answers
INDEX .Net Framework 1. 2. Object Oriented Programming Concept 3. Basic Common Questions 4. C# 5. C# Laguage feature 6. ASP.Net 7. Constructor Basic 8. ADO.Net 9. More About ASP.Net 10. Design Pattern 11. Web Services & Remoting 12. COM 10. XML 11. AJAX 12. UML 12. IIS 13. SQL 14. Queries 15. INDEXES 16. SQL DataType 17. JOINS 18. Locks 19. Store Procedure 20. TRIGGERS 21. VIEW 22. Transactions And Other 23. SQL Server2000 24.TOOLS SQL SERVER 25. Permission SQLSERVER 26. Admin SQLSERVER 27. Services and user Accounts maintenance .NET FRAMEWORK 1. What is .NET Framework? The .NET Framework has two main components: the common language runtime and the .NET Framework class library. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that ensure security and robustness. The class library is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services. 2. .Net Architecture
1
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture. 4. ADO.NET architecture
5. Is .NET a runtime service or a development platform? It's both and actually a lot more. Microsoft .NET includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The .NET frameworks SDK consists of two parts: the .NET common language runtime and the .NET class library. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform. 6. What is MSIL, IL? When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-intime (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code. 7. Can I write IL programs directly? Yes. Peter Drayton posted this simple example to the DOTNET mailing list: .assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } } Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated. 8. Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays. 9. What is JIT (just in time)? how it works? Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access. 10. What is strong name? A name that consists of an assembly's identityits simple text name, version number, and culture information (if provided)strengthened by a public key and a digital signature generated over the assembly.
3. What is CLR, CTS, CLS? The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging. Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
2
Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this: caspol -cg 1.2 FullTrust Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect. 18. Can I create my own permission set? Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this: caspol -ap samplepermset.xml Then, to apply the permission set to a code group, do something like this: caspol -cg 1.3 SamplePermSet (By default, 1.3 is the 'Internet' code group) 19. I'm having some trouble with CAS. How can I diagnose my problem? Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp. 19. I can't be bothered with all this CAS stuff. Can I turn it off? Yes, as long as you are an administrator. Just run: caspol -s off 20. Which namespace is the base class for .net Class library? System.object 21. What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling? Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached. Following are important differences between object pooling and connection pooling: Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.) COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced. 22. What is Application Domain? 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. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are mplicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries 23. 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; } }
3
the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. -> It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies. -> It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. It is the unit at which side-by-side execution is supported. -> Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies. 27. What are the contents of assembly? In general, a static assembly can consist of four elements: - The assembly manifest, which contains assembly metadata. - Type metadata. - Microsoft intermediate language (MSIL) code that implements the types. - A set of resources. 28. What are the different types of assemblies? Private, Public/Shared, Satellite 29. 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. 30. What are Satellite Assemblies? How you will create this? How will you get the different language strings? Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. (For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.) 31. How will u load dynamic assembly? How will create assemblies at run time? There are basically two methods in .Net to generate dynamic code through your program. One is to use CodeDom library while other is to use Reflection Emit library. The System.CodeDom library is used to generate the standard CLS (Common Language Specification) compliant code that can be emitted in any of .Net languages. On the other hand, the System.Reflection.Emit library is used to generate the MSIL (Micrsoft Intermediate Language) code. Dot Net Reflection Emit allows us to construct assemblies, modules, types at runtime and define code inside these types. 32. What is Assembly manifest? what all details the assembly manifest will contain? Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies. 33. Difference between assembly manifest & metadata? Assembly Manifest - An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly's metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This
24. What is serialization in .NET? What are the ways to control 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).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. 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.
26. 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. 25. What is exception handling? When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception. Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded. 26. What is Assembly? - Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. - An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. - An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. - Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions: -> It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main). -> It forms a security boundary. An assembly is the unit at which permissions are requested and granted. -> It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly. -> It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies
4
development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services. 41. How do you create threading in .NET? What is the namespace for that? System.Threading.Thread 42. Serialize and MarshalByRef? Serialization is the act of saving the state of an object so that it can be recreated (i.e deserialized) at a later date. The MarshalByRef class is part of the System.Runtime.Remoting namespace and enables us to access and use objects that reside in different application domains. It is the base class for objects that need to communicate across application domains. MarshalByRef objects are accessed directly within their own application domain by using a proxy to communicate. With MarshalByValue the a copy of the entire object is passed across the application domain using directive vs using statement. You create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. A using statement can be exited either when the end of the using statement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement. The using directive has two uses: - Create an alias for a namespace (a using alias). - Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive). 43. Describe the Managed Execution Process? The managed execution process includes the following steps: - Choosing a compiler. - To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime. - Compiling your code to Microsoft intermediate language (MSIL). - Compiling translates your source code into MSIL and generates the required metadata. - Compiling MSIL to native code. At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out hether the code can be determined to be type safe. Executing your code. The common language runtime provides the infrastructure that enables execution to take place as well as a variety of services that can be used during execution. 44. What is Active Directory? What is the namespace used to access the Microsoft Active Directories? What are ADSI Directories? Active Directory Service Interfaces (ADSI) is a programmatic interface for Microsoft Windows Active Directory. It enables your applications to interact with diverse directories on a network, using a single interface. Visual Studio .NET and the .NET Framework make it easy to add ADSI functionality with the DirectoryEntry and DirectorySearcher components. Using ADSI, you can create applications that perform common administrative tasks, such as backing up databases, accessing printers, and administering user accounts. ADSI makes it possible for you to: Log on once to work with diverse directories. The DirectoryEntry component class provides username and password properties that can be entered at runtime and communicated to the Active Directory object you are binding to.Use a single application programming interface (API) to perform tasks on multiple directory systems by offering the user a variety of protocols to use. The DirectoryServices namespace provides the classes to perform most administrative functions. Perform "rich querying" on directory systems. ADSI technology allows for searching for an object by specifying two query dialects: SQL and LDAP. Access and use a single, hierarchical structure for administering and maintaining diverse and complicated network configurations by accessing an Active Directory tree. Integrate directory information with databases such as SQL Server. The DirectoryEntry path may be used as an ADO.NET connection string provided that it is using the LDAP provider. using System.DirectoryServices; 45. What are diff betweeen ASP.NET 2.0 and 1.1? Some of the new features in ASP.NET 2.0 are: - Master Pages, Themes, and Web Parts - Standard controls for navigation - Standard controls for security - Roles, personalization, and internationalization services - Improved and simplified data access controls - Full support for XML standards like, XHTML, XML, and WSDL - Improved compilation and deployment (installation) - Improved site management - New and improved development tools - 64- Bit platform support.
5
5. What is Method overloading? Method overloading occurs when a class contains two methods with the same name, but different signatures. 6. 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. 7. 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. 8. 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(); } }
9. 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. BASIC COMMON QUESTION 1. what is runnable interface? runnable interface is implemented when thread is use. it is needed to start thread. 2.What is the use of a form in html page? Is there any way to submit the page without using the form. In html we can use JAVASCRIPT for validation purpose. Since we require a specific form name for validation and to specicy the action after certain operation is performed. 3.Explain about session? Where it runs & what are different types of session handling? HTTP is a protocol which does not maintain the state of the client. It is state-less protocol, to make the protocol stateful we need to provide the session handling mechanism. This will be provided as per the need of the Application.The basic categories are 4 ways: 1. Using Cookies 2. Using Session API in Servlets 3. Using Hidden form fields 4. URL Rewriting. The best one is using Session objects with help of Session API. Cookies are harmful because they are allowed to store on to the client machine. This way you can send a virus file as cookie So normally the System Admin disables them to protect their network. The session API allows us to create SessionID and set for the client. per Client you can have one session object which will run in the Server. 4. Explain Session One of the challenges to developing a successful Web application is maintaining user information over the course of a visit, or session, as the user moves from page to page in an application. Essentially, a session is the period of time that a unique user interacts with a Web application. HTTP is a stateless protocol, in the sense that a Web server is concerned only with the current HTTP request for any given Web page. The server retains no knowledge of previous requests, even if these occurred only prior to the current request. This inability to remember the state of previous requests presents unique challenges when writing Web applications such as an online shopping cart, that need to track the catalog items a user has selected while moving around the various pages of the catalog. ASP.NET provides a solution for managing session information via the System.Web.SessionState namespace. This namespace describes a collection of classes used to enable storage of data specific to a single client within a Web application. The session-state data is used to give the client the appearance of a persistent connection with the application. Using the intrinsic ASP.NET Session object and a special user ID generated by the Web server, developers can create smart applications that can identify each user and
6
collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method. Garbage collection consists of the following steps: The garbage collector searches for managed objects that are referenced in managed code. The garbage collector attempts to finalize objects that are not referenced. The garbage collector frees objects that are not referenced and reclaims their memory. 2. Why do we need to call CG.SupressFinalize? Requests that the system not call the finalizer method for the specified object. [C#] public static void SuppressFinalize(object obj); The method removes obj from the set of objects that require finalization. The obj parameter is required to be the caller of this method. Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it. 3. What is nmake tool? The Nmake tool (Nmake.exe) is a 32-bit tool that you use to build projects based on commands contained in a .mak file.usage : nmake -a all 4. What are Namespaces? The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable. 5. What is the difference between CONST and READONLY? Both are meant for constant values. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. readonly int b; public X() { b=1; } public X(string s) { b=5; } public X(string s, int i) { b=i; } Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks; (this can't be possible with const) 6. What is the difference between ref & out parameters? An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter. 7. What is the difference between Array and LinkedList? Array is a simple sequence of numbers which are not concerned about each-others positions. they are independent of each-others positions. adding, removing or modifying any array element is very easy.Compared to arrays ,linked list is a comlicated sequence of numbers.each number in the linked list is connected to its previous & next no. via a link which is nothieng but a pointer.Addition,removal of no.s in linked list is related to this pointer direction & linking that no. to the no. which is already present in the list. 8. What is the difference between Array and Arraylist? An array is a collection of the same type. The size of the array is fixed in its declaration. A linked list is similar to an array but it doesnt have a limited size. 9. What is Asynchronous call and how it can be implemented using delegates? A synchronous call will wait for a method to complete before program flow is resumed. With an asynchronous call the program flow continues whilst the method executes. //create object SomeFunction objFunc = new SomeFunction(); //create delegate SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA); //invoke the method asynchronously (use interface IAsyncResult) IAsyncResult asynchCall = SomeDelegate.Invoke();
For the above code What is the "new" keyword and Which Class Method is called here 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(); } Derive
3. 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.
Interfaces vs. Abstract Classes Feature Interface Abstract class A class may implement several A class may extend only one abstract Multiple inheritance interfaces. class. An interface cannot provide any An abstract class can provide complete Default code at all, much less default code, default code, and/or just stubs that implementation code. have to be overridden. Static final constants only, can use them without qualification in classes that implement the Both instance and static constants are interface. On the other paw, possible. Both static and instance Constants these unqualified names pollute intialiser code are also possible to the namespace. You can use them compute the constants. and it is not obvious where they are coming from since the qualification is optional. An interface implementation may A third party class must be rewritten to Third party be added to any existing third extend only from the abstract class. convenience party class. Interfaces are often used to An abstract class defines the core identity describe the peripheral abilities of of its descendants. If you defined a Dog a class, not its central identity, abstract class then Damamation e.g. an Automobile class might is-a vs -able or can-do descendants are Dogs, they are not implement the Recyclable merely dogable. Implemented interfaces interface, which could apply to enumerate the general things a class can many otherwise totally unrelated do, not the things a class is. objects. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class You can write a new replacement author has imposed structure on you. module for an interface that Depending on the cleverness of the contains not one stick of code in author of the abstract class, this may be common with the existing good or bad. Another issue that's implementations. When you important is what I call "heterogeneous implement the interface, you vs. homogeneous." If start from scratch without any implementors/subclasses are Plug-in default implementation. You have homogeneous, tend towards an abstract to obtain your tools from other base class. If they are heterogeneous, use classes; nothing comes with the an interface. (Now all I have to do is come interface other than a few up with a good definition of constants. This gives you freedom hetero/homogeneous in this context.) If to implement a radically different the various objects are all of-a-kind, and internal design. share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface. If the various implementations are all of a If all the various implementations kind and share a common status and Homogeneity share is the method signatures, behavior, usually an abstract class works then an interface works best. best. If your client code talks only in Just like an interface, if your client code terms of an interface, you can talks only in terms of an abstract class, Maintenance easily change the concrete you can easily change the concrete implementation behind it, using a implementation behind it, using a factory factory method. method. Slow, requires extra indirection to find the corresponding method in Speed the actual class. Modern JVMs are Fast discovering ways to reduce this speed penalty. The constant declarations in an You can put shared code into an abstract interface are all presumed public class, where you cannot into an interface. static final, so you may leave that If interfaces want to share code, you will part out. You can't call any have to write other bubblegum to arrange Terseness methods to compute the initial that. You may use methods to compute values of your constants. You the initial values of your constants and need not declare individual variables, both instance and static. You methods of an interface abstract. must declare all the individual methods of They are all presumed so. an abstract class abstract. If you add a new method to an If you add a new method to an abstract interface, you must track down all class, you have the option of providing a implementations of that interface Adding functionality default implementation of it. Then all in the universe and provide them existing code will continue to work with a concrete implementation without change. of that method.
4. How to implement getCommon method in class a? Are you seeing any problem in the implementation? public class a:ICommonImplements1,ICommonImplements2 { public int getCommon() { return 1; } } interface IWeather { void display(); } public class A:IWeather { public void display() { MessageBox.Show("A"); } } public class B:A { } public class C:B,IWeather { public void display() { MessageBox.Show("C"); } } 5. When I instantiate C.display(), will it work? interface IPrint { string Display(); } interface IWrite { string Display(); } class PrintDoc:IPrint,IWrite { //Here is implementation } 6. How to implement the Display in the class printDoc (How to resolve the naming Conflict) No naming conflicts class PrintDoc:IPrint,IWrite { public string Display() { return "s"; } } interface IList { int Count { get; set; } } interface ICounter { void Count(int i); } interface IListCounter: IList, ICounter {} class C { void Test(IListCounter x) { x .Count(1); // Error x.Count = 1; // Error ((IList)x).Count = 1; // Ok, invokes IList.Count.set ((ICounter)x).Count(1); // Ok, invokes ICounter.Count } } 7. Write one code example for compile time binding and one for run time binding? What is early/late binding? An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
see the code interface ICommon { int getCommon(); } interface ICommonImplements1:ICommon { } interface ICommonImplements2:ICommon
9
lblFileLength.Text = loFile.PostedFile.ContentLength.ToString(); lblFileType.Text = loFile.PostedFile.ContentType; pnStatus.Visible = true; } catch (Exception x) { Label lblError = new Label(); lblError.ForeColor = Color.Red; lblError.Text = "Exception occurred: " + x.Message; lblError.Visible = true; this.Controls.Add(lblError); } } } </script> <body> <form id="upload_cs" method="post" runat="server" enctype="multipart/form-data"> <P> <INPUT type="file" id="loFile" runat="server"> </P> <P> <asp:Button id="btnUpload" runat="server" Text=" Upload " OnClick="UploadFile"></asp:Button></P> <P> <asp:Panel id="pnStatus" runat="server" Visible="False"> <asp:Label id="lblFileName" Font-Bold="True" Runat="server"></asp:Label> uploaded<BR> <asp:Label id="lblFileLength" Runat="server"></asp:Label> bytes<BR> <asp:Label id="lblFileType" Runat="server"></asp:Label> </asp:Panel></P> </form> </body> </html> 2. 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. C# <%@ Import Namespace="System" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.Mail" %> <HTML> <HEAD> title>Mail Test</title> </HEAD> <script language="C#" runat="server"> private void Page_Load(Object sender, EventArgs e) { Try { MailMessage mailObj = new MailMessage(); mailObj.From = "[email protected]"; mailObj.To = "[email protected]"; mailObj.Subject = "Your Widget Order"; mailObj.Body = "Your order was processed."; mailObj.BodyFormat = MailFormat.Text; SmtpMail.SmtpServer = "mail-fwd"; SmtpMail.Send(mailObj); Response.Write("Mail sent successfully"); } catch (Exception x) { Response.Write("Your message was not sent: " + x.Message); } } </script> <body> <form id="mail_test" method="post" runat="server"> </form> </body> </HTML> 3. Explain Cookies in .Net? Cookie are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine. C# // Add this on the beginning of your .vb code file using System;
10
if (Request.Browser.Cookies) { // Cookies supported } else { // Web browser not supports cookies } 8. How to check if client web browser not saved a cookie because of its privacy settings Code above will tell you does web browser supports cookie technology, but your visitor could disable cookies in web browser's privacy settings. In that case, Request.Browser.Cookies will still return true but your cookies will not be saved. Only way to check client's privacy settings is to try to save a cookie on the first page, and then redirect to second page that will try to read that cookie. You can eventually use the same page to save and read a cookie when perform a testing, but you must use Response.Redirect method after saving and before reading cookies. 9. Best practices with cookies in ASP.NET Cookies are just plain text, so usually are not used to store sensitive informations like passwords without prior encryption. If you want to enable "Remember me" option on web site it is recommended to encrypt a password before it is stored in a cookie. Cookies are often used for data like: when visitor last time loged in, what site color she likes, to keep referer id if we offer affiliate program etc. 10. Security issues about cookies in ASP.NET Because of security reasons, your web application can read only cookies related to your web domain. You can't read cookies related to other web sites. Web browser stores cookies from different sites separately. Cookie is just a plain text file on client's hard disk so it could be changed on different ways outside of your application. Because of that, you need to treat cookie value as potentially dangerous input like any other input from the visitor, including prevention of cross site scripting attacks. 11. What is a static class? A static class is a class which can not be instantiated using the new keyword. They also only contain static members, are sealed and have a private constructor. 12. What is static member? A static member is a method, field, property or event that can be called without creating an instance of its defining class. Static members are particularly useful for representing calculations and data that are independent of object state.
13. What is static function? A static function is another term for a static method. It allows you to execute the function without creating an instance of its defining class. They are similar to global functions. An example of a static function could be: ConvertFromFarenheitToCelsius with a signature as follows: public static double ConvertFromFarenheitToCelsius (string valToConvert) { //add code here } 13. What is static constructor? A static constructor has a similar function as a normal constructor i.e. it is automatically called the first time a class is loaded. The differences between a conventional constructor are that it cannot be overloaded, cannot have any parameters nor have any access modifiers and must be preceded by the keyword static. In addition, a class with a static constructor may only have static members. 14. How can we inherit a static member? When inheriting static members there is no need to instantiate the defining class using the new keyword. public class MyBaseClass{ MyBaseClass() { } public static void PrintName() { } } public class MyDerivedClass : MyBaseClass{ MyDerivedClass () { } public void DoSomething() { MyBaseClass.GetName(); } }
11
15. Can we use a static function with a non-static variable? No. 16. How can we access static variable? By employing the use of a static member field as follows: public class CashSales { //declare static member field private static int maxUnitsAllowed = 50; //declare method to return maximum number of units allowed public static int GetMaxUnitsAllowed () { Return maxUnitsAllowed; } } The static field can now be accessed by simply CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class.
5. What are virtual destructors? A constructor can not be virtual but a destructor may. Use virtual destructors when you want to implement polymorphic tearing down of an object. 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. 6. 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. 7. 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. 8. What is close method? How its different from Finalize & Dispose? Finalise is the process that allows the garbage collector to clean up any unmanaged resources before it is destroyed.The finalise method can not be called directly; it is automatically called by the CLR. In order to allow more control over the release of unmanaged resources the .NET framework provides a dispose method which unlike finalise can be called directly by code. Close method is same as dispose. It was added as a convenience. 9. What is boxing & unboxing? Boxing is the process of converting a value type to a reference type. More specifically it involves encapsulating a copy of the object and moving it from stack to heap. Unboxing is the reverse process. 10. What is check/uncheck? Checked: used to enable overflow checking for arithmetic and conversion functions. Unchecked: used to disable overflow checking for arithmetic and conversion functions. 11. What is the use of base keyword? Tell me a practical example for base keywords usage? - The keyword base is used to access members of the base class from inside a derived class. Key Points: Calling a method from the base class is possible even if it has been overriden by another method by using the keyword base. Also, when you are creating a instance of a derived class you can call the base classes contructor if so desired with this keyword, base. - There rules governing base class access are (or permissible in): In a constructor In an instance method Instance property accessor Attemps at using the keyword base in a static method will result in an error. Example:<%@ Page language="c#" %> <script language="C#" runat="server"> public class CSharp { public virtual string GetMessage() { return "<br>All your base are belong to us!";
doing
17. Why main function is static? Because it is automatically loaded by the CLR and initialised by the runtime when the class is first loaded. If it wasnt static an instance of the class would first need to be created and initialised. 17. How will you load dynamic assembly? How will create assemblies at run time? Load assembly: By using classes from the System.Reflection namespace. Assembly x = Assembly.LoadFrom( LoadMe.dll ); Createassembly; Use classes from System.CodeDom.Compiler; 18. What is Reflection? The System.Reflection namespace provides us with a series of classes that allow us to interrogate the codebase at run-time and perform functions such as dynamically load assemblies, return property info e.t.c. 19. If I have more than one version of one assembly, then how will I use old version (how/where to specify version number?) in my application? The version number is stored in the following format: . The assembly manifest can then contain a reference to which version number we want to use. 20. How do you create threading in.NET? What is the namespace for that? System.Threading; //create new thread using the thread classs constructor Thread myThread = new Thread(new ThreadStart (someFunction)); 21. What do you mean by Serialize and MarshalByRef? Serialization is the act of saving the state of an object so that it can be recreated (i.e deserialized) at a later date.The MarshalByRef class is part of the System.Runtime.Remoting namespace and enables us to access and use objects that reside in different application domains. It is the base class for objects that need to communicate across application domains. MarshalByRef objects are accessed directly within their own application domain by using a proxy to communicate. With MarshalByValue the a copy of the entire object is passed across the application domain CONSTRUCTORS BASIC 1. 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. 2. What is Private Constructor? and its use? Can you create instance of a class which has Private Constructor? 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. 3. 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
12
// 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); }
Friends CSF = new Friends(); // Friend's method GetMessage calls base classes method Response.Write(CSF.GetMessage()); } </script> You can call a base classes contructor from within a derived classes contructor as follows (below is the derived classes constructor): public DerivedClassesConstructor() : base() { } 12. Will it go to finally block if there is no exception happened? 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. 13. 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.
4. Difference between OLEDB Provider and SqlClient ? 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. 5. 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. 6. 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();
14. Whats 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; ADO.NET 1. 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 2. How would u connect to database using .NET? SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" + "Initial Catalog=northwind"); nwindConn.Open(); 3. 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;
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. 7. Which method do you invoke on the DataAdapter control to load your generated dataset with data? Fill() 8. Explain different methods and Properties of DataReader which you have used in your project? - Read - GetString - GetInt32 while(myReader.Read()) Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); myReader.Close(); 9. What happens when we issue Dataset.ReadXml command? Reads XML schema and data into the DataSet.
13
becasue the which he have using is allready changed so he cannot do the change becasue change apply to another data that is changed by first user. 24. Why is ADO.NET serialization slower than ADO ? ADO uses binary serialization while ADO.NET uses text based serialization. Since the text takes more space, it takes longer to write it out. 25. How to check if the Dataset has records ? if ds.Tables(0).Rows.Count= 0 then 'No record else 'record found 26. What is the significance of CommandBehavior.CloseConnection ? To avoid having to explicitly close the connection associated with the command used to create either a SqlDataReader or and OleDbDataReader, pass the CommandBehavior.CloseConnection argument to the ExecuteReader method of the Connection. dr= cmd.ExecuteReader(CommandBehavior.CloseConnection); The associated connection will be closed automatically when the Close method of the Datareader is called. This makes it all the more important to always remember to call Close on your datareaders 27. Which method do you invoke on the DataAdapter control to load your generated dataset with data? The Fill() method. 28. What is Dataset and Diffgram? When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a DataSet from XML using the ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml method, you can select that the contents be read or written as a DiffGram. For more information, see Loading a DataSet from XML and Writing a DataSet as XML Data. While the DiffGram format is primarily used by the .NET Framework as a serialization format for the contents of a DataSet, you can also use DiffGrams to modify data in tables in a Microsoft SQL Server 2000 database. 29. What is typed dataset ? A typed dataset is very much similar to a normal dataset. But the only difference is that the sehema is already present for the same. Hence any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset. Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema. 30. How can you provide an alternating color scheme in a Repeater control? AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties. 31. What are good ADO.NET object(s) to replace the ADO Recordset object? There are alot...but the base once are SqlConnection, OleDbConnection, etc... 32. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? A DataSet can represent an entire relational database in memory, complete with tables, relations, and views. A DataSet is designed to work without any continuing connection to the original data source. Data in a DataSet is bulk-loaded, rather than being loaded on demand. There's no concept of cursor types in a DataSet. DataSets have no current record pointer You can use For Each loops to move through the data. You can store many edits in a DataSet, and write them to the original data source in a single operation. Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources. 33. What are the differences between Datalist DataGrid and datarepeater ? DataList Has table appearence by default Has no autoformat option has no default paging & sorting options can define separators between elements using template DataGrid Has a grid appearence by default has a autoformat option has default paging and sorting has no separator between elements DataRepeater simple,read-only output, has no built in support for selecting or editing items, has no DEFAULT APPEARENCE, has no default paging. 34. What are Databases in ADO.NET? Ado.net provide set of classes to connect and process tables in databases. It can connect to all the available databases. it provides 2 namespaces one for sqlserve 7.0 and above and for all other kind it uses oledb for all purpose. 35. What is ADO.NET ADO.Net is a framework provide classes , namespaces, interfaces and collection to help interect with database. to open connection , run queries, insert ,delete and update data residing in database. It is connection less way to connect to database. Data can be processed in datasets/ datatables. By this many users can connect to the database without overloading database. 36. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so its not as fastest and efficient as SqlServer.NET.
14
DataAdapter is a disconnected mode, it is automaticaly open the connection get data from data source and through the fill method fill dataset here DataSet contain the table, automaticaly disconnect the connection from the database. DataCommand work as connected mode, it always use the connection open() and close(), it works with DataReader, ExecuteScaler and ExecuteNonQuery. datareader: read data from database, it line by line & forword execution. executenonquery: use for insert, update, delete. executescaler: it return only single value like that.... Exp. \\\"select count(*) from TableName\\\" 53. What is LINQ? what is use of LINQ? - LINQ stands for Language Integrated Query. - It's a asp.net 3.5 component - It's a new datasource control known as linqdatasource control - It defines operators that allow code to query in a consistent manner over DB,objects and XML 54. What is the datagrid? how we can make the connection with excel? string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\exceltest.xls;" + "Extended Properties=Excel 8.0;"; OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [sheet1$]", strConn); DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet, "ExcelInfo"); GridView1.DataSource = myDataSet.Tables["ExcelInfo"].DefaultView; GridView1.DataBind(); 55. What are the 2 parts of ADO.net? - The Dataset object - Managed Providers MORE ABOUT ASP.NET 1. ASP.net and ASP differences?
37. How to copy the contents from one table to another table and how to delete the source table in ADO. select * into #globaltemp from #temp 38. What is Pull Model and Push Model in ADO.Net? What are the situations when we use one over the other? Pull model is used to pick-out the data from the data base and push model is used to insert data only at the top position of table in database 39. Explain the Use of connection pooling in ADO.NET. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections. When a new connection requests come in, the pool manager checks if the pool contains any unused connections and returns one if available. If all connections currently in the pool are busy and the maximum pool size has not been reached, the new connection is created and added to the pool. When the pool reaches its maximum size all new connection requests are being queued up until a connection in the pool becomes available or the connection attempt times out. 40. What are the main classes/Components of ADO.NET? Component of ADO.NET ARE 1. CONNECTION OBJECT 2. COMMAND OBJECT 3. DATAREADER 4. DATAADAPTER 5. DATAVIEW 41. What is the use of executescalar()? ExecuteScaler function of ado.net command object returns one ie leftmost value as result. It is generally used when the outcome of a query is single value like count, avg, sum etc. 42. What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed. 43. What is ODP.NET? ODP : Oracle Data Provider. It provide to access the data from Oracle. Data can fetch very fast compare to oledb.And it provides many more which are not in .Net for example XML data type, array parameters, RAC optimizations, and statement caching. Name space is Oracle.DataAccess 44. Difference between datagrid and data table? DataGrid : Using DataGrid we display the records, here we can do Paging, Sorting, Editing and all DataTable : DataTable is In-Memory representation, while using DataSet we can use DataTable to update the dataset. 45. How do you update a Dataset in ADO.Net and How do you update database through Dataset using update method 46. What is ADO? ADO is ActiveX data object. It is for database connections 47. Diferrence between DataGrid and Repeater DataReader is used only to display data(ReadOnlyMode), while in datagrid has ability to paging,sorting,selection. 48. Explain database connectivity (i.e.Insert, Update, Delete, Show statements) of asp.net using SQL-Server SqlConnection cn=new SqlConnection(\\\"server=., Initial Catalog=pubs,Integered Security=True\\\") SqlCommand cmd = new SqlCommand (StpreProcedure/Query, cn); cmd.ExecuteNonQuery(); 50. What is the diff b/w ADO & ADO.NET? There are some major difference between ADO and ADO.Net 1 As in ADO we had client and server side cursors they are no more present in ADO.Net. Note it's a disconnected model so they are more applicable. 2 Locking is not supported due to disconnected model. 3 All data is persisted in Xml as compared to ADO where data was persisted in binary format also. 51. How can i insert or fetch data into datagrid? Using ExecuteReader u can display data in datagrid.. dim con as SqlConnection=new SqlConnection(\\\"server=localhost;uid=;pwd=;database=Pubs\\\") dim MyCmd as sqlCommand(\\\"select * from Customers\\\",con) con.open() DataGrid1.datasource=MyCmd.ExecuteNonReader() con.close() 52. What is the DataAdapter, DataCommand, DataSet?
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 It can span across servers, It can survive server Session - weren't transferable across servers crashes, can work with browsers that don't support cookies its an integral part of OS under the .net framework. It shares many of the same objects built on top of the window & IIS, it was always a that traditional applications would use, and all separate entity & its functionality was limited. .net objects are available for asp.net's consumption. Garbage Collection Declare variable with datatype In built graphics support Cultures
2. How ASP and ASP.NET page works? Explain about ASP.Net page life cycle? ASP is interpreted. ASP.NET Compiled event base programming. Control events for text button can be handled at client javascript only. Since we have server controls events can handle at server side. More error handling. ASP .NET has better language support, a large set of new controls and XML based components, and better user authentication. ASP .NET provides increased performance by running compiled code. ASP .NET code is not fully backward compatible with ASP. ASP .NET also contains a new set of object oriented input controls, like programmable list boxes, validation controls. A new data grid control supports sorting, data paging, and everything you expect from a dataset control. The first request for an ASP.NET page on the server will compile the ASP .NET code and keep a cached copy in memory. The result of this is greatly increased performance. ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP .NET. To overcome this problem, ASP .NET uses a new file extension ".aspx". This will make ASP .NET applications able to run side by side with standard ASP applications on the same server. PreInit (New to ASP.NET 2.0) The entry point of the page life cycle is the pre-initialization phase called PreInit. This is the only event where programmatic access to master pages and themes is allowed. Note that this event is not recursive, meaning that it is accessible only for the page itself and not for any of its child controls. Init Next is the initialization phase called Init. The Init event is fired reclusively for the page itself and for all the child controls in the hierarchy (which is created during the creation of the compiled class, as explained earlier). Note that against many developers beliefs, the event is fired in a bottom to up manner and not an up to bottom within the hierarchy. This means that following up with our previous example, the Init event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. You can test this behavior yourself by adding a custom or user control to the page. Override the
15
The Control State is also serialized and stored in the same __VIEWSTATE hidden field. The Control State cannot be set off. Render This is a recursive event much like the Init event. During this event, the HTML that is returned to the client requesting the page is generated. Unload This is a recursive event much like the Init event. This event unloads the page from memory, and releases any used resources. 3. Order of events in an asp.net page? Control Execution Lifecycle?
Phase Initialize Load state What a control needs to do Method or event to override Initialize settings needed during the lifetime of Init event (OnInit method) the incoming Web request. view At the end of this phase, the ViewState property LoadViewState method 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. (if is
Process Process incoming form data and update LoadPostData method postback data properties accordingly. IPostBackDataHandler implemented) Load Perform actions common to all requests, such as Load event setting up a database query. At this point, server (OnLoad method) controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data.
Raise change events in response to state RaisePostDataChangedEvent changes between the current and previous method (if IPostBackDataHandler postbacks. is implemented) Handle the client-side event that caused the RaisePostBackEvent method(if postback and raise appropriate events on the IPostBackEventHandler is server. implemented) Perform any updates before the output is PreRender rendered. Any changes made to the state of the (OnPreRender method) control in the prerender phase can be saved, while changes made in the rendering phase are lost. The ViewState property of a control is SaveViewState method 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. Generate output to be rendered to the client. Render method event
Render Dispose
Perform any final cleanup before the control is Dispose method torn down. References to expensive resources such as database connections must be released in this phase. Perform any final cleanup before the control is UnLoad event torn down. Control authors generally perform method) cleanup in Dispose and do not handle this event. (On UnLoad
Unload
Note : To override an EventName event, override the OnEventName method (and call base. OnEventName). 4. 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. 5. What is the difference between Web User Control and Web Custom Control? 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
16
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 13. 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. 14. 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. 15. What are the contents of cookie? Cookie is a small amount of data and it contains page-specific information(usually user ID) the server sends to the client along with page output. Cookies can contain only strings. 16. How do you create a permanent cookie? Making a persistent cookie(Permanent) Dim Objcookie as new HTTPCookie("Mycookie")Dim Date as Datetime = Datatime.nowObjcookie.Expires = now.addhours(1) 17. What is ViewState? What does the "EnableViewState" property do? Why would I want it on or off? View state is a property of Web Forms page and each control of the page to save their values so it can be used between round trips to the server. When the page is processed, the current state of the page and controls is inserted into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page. EnableViewState indicates whether the page maintains its view state, and the view state of any server controls it contains, when the current page request ends. The benefits of using ViewState are it automatically store values between multiple requests for the same page, it is saved as a hidden field of the page and no server resources required. It is better to disable ViewState if a control or a page contain large amount of data. Saving such an amount can affect the form load. Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. 18. 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. 19. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? Application_Start:----generally placed in global.asax page. As the first user visits the start page of a Web application, this event is occurred.this event is used to initialize the objects and data tht a user want to make available to all current sessions of the visited web applications. Session_Start:----generally placed in global.asax page.For each user visiting the web application, it creartes a new instances of session variables used by the visitor. 20. Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform? 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 sites web.config file (s): browserCaps clientTarget pages customErrors globalization authorization authentication
A separate copy of the control is Only a single copy of the control is required, required in each application in the global assembly cache Cannot be added to the Toolbox in Can be added to the Toolbox in Visual Visual Studio Studio Good for static layout Good for dynamic layout
6. 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. 7. Difference between ASP Session and ASP.NET Session? ASP.Net session supports cookie less session & it can span across multiple servers. 8. 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: <sessionState cookieless="true" /> 9. 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\Paramet ers\Port Set the mode attribute of the <sessionState> 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): <sessionState mode="StateServer" stateConnectionString="tcpip=localhost: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. 10. What method do you use to explicitly kill a users session? Abandon () 11. 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 12. 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.
17
Client Certificate authentication IIS supports the use of digital certificates and the secure sockets layer (SSL). In this scenario, either the server or the client has a certificate a digital identification that they have obtained from a third-party source. The certification is passed to your application with requests. It can be mapped to a Windows user account and granted appropriate permissions. Different types of security in asp.net are 1.Code Access Security 2.Evidence Based Security 3.Role Based Security 4.Declarative and Imperative security 5.Cryptography 27. How .Net has implemented security for web applications? To secure Web application, .NET uses two functions: Authentication and Authorization. Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. Authorization limits access rights by granting or denying specific permissions to an authenticated identity. 28. How to do Forms authentication in asp.net? You need to create an entry in Web.Config authentication mode=Forms forms name=.TheCookie loginUrl=/login/login.aspx protection=All timeout=70 path=// /authentication 29. Explain authentication levels in .net ? Authentication can be declared only at the machine, site, or application level. 30. Explain autherization levels in .net ? Authorization controls client access to URL resources. It can be declared at any level: machine, site, application, subdirectory, or page. 31. 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. 32. How can you handle Exceptions in ASP.NET? - You can handle Exceptions using Try Catch Finally block. Also in Global.asax you can create an application-wide error handler Application_Error or create a handler in a page for the Page_Error event. Application_Error and Page_Error methods are called if an unhandled exception occurs anywhere in your page or application. - You can also use the Page class property ErrorPage that gets or sets the error page to which the requesting browser is redirected in the event of an unhandled page exception. - It works only when customErrors mode is on in Web.Config or Machine.Config. The sub-element error of customErrors element in Web.Config can be used to define one custom error redirect associated with an HTTP status code and defaultRedirect attribute is used to specify the default URL to direct a browser to if an error occurs. When defaultRedirect is not specified, a generic error is displayed instead. 33. 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? 34. How can you handle UnManaged Code Exceptions in ASP.NET? Unmanaged code can include both C++-style SEH Exceptions and COM-based HRESULTS. COM handles errors through HRESULT. If an exception occurs in unmanaged code, the COM HRESULT is mapped to the appropriate exception class, which is returned to .NET, where it can be handled like any other exception. User-defined exception classes can specify whatever HRESULT is appropriate. These exception classes can dynamically change the HRESULT to be returned when the exception is generated by setting the HResult field on the exception object. Additional information about the exception is provided to the client through the IErrorInfo interface, which is implemented on the .NET object in the unmanaged process 35. What are the different authentication modes in the .NET environment? Form, Window, Passport, None 36. What is the difference between application and cache variables? ASP.NET allows you to save values using application state (an instance of the HttpApplicationState class) for each active Web application. Application state is a global storage mechanism accessible from all pages in the Web application and is thus useful for storing information that needs to be maintained between server round trips and between pages.
18
The memory occupied by variables stored in application state is not released until the value is either removed or replaced. Application state is a key-value dictionary structure created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it. Cache data can persist for a long time, but not across application restarts. It can hold both large and small amounts of data effectively. Also, data can expire based on time set by the application code or other dependencies; this feature is not available in the Application object. 37. What is the difference between control and component? Components implement the System.ComponentModel.IComponent interface by deriving from the SystemComponent.Model.Component base class. Component is generally used for an object that is reusable and can interact with other objects. A .NET Framework component additionally provides features such as control over external resources and design-time support. A control is a component that provides user-interface capabilities. Controls draw themselves and shown in the visual area. The .NET Framework provides two base classes for controls: one for client-side Windows Forms controls and the other for ASP.NET server controls. These are System.Windows.Forms.Control and System.Web.UI.Control. System.Windows.Forms.Control derives from Component base class and itself provides UI capabilities. System.Web.UI.Control implements IComponent and provides the infrastructure on which it is easy to add UI functionality. <authentication mode="Windows|Forms|Passport|None"> <forms name="name" loginUrl="url" protection="All|None|Encryption|Validation" timeout="30" path="/" > requireSSL="true|false" slidingExpiration="true|false"> <credentials passwordFormat="Clear|SHA1|MD5"> <user name="username" password="password"/> </credentials> </forms> <passport redirectUrl="internal"/> </authentication>
Attribute mode Windows Option Description Controls the default authentication mode for an application. 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. Specifies ASP.NET forms-based authentication as the default authentication mode. Specifies Microsoft Passport authentication as the default authentication mode. Specifies no authentication. Only anonymous users are expected or applications can handle events to provide their own authentication.
43. How do you implement postback with a text box? What is postback and usestate? Make AutoPostBack property to true 44. How can you debug an ASP page, without touching the code? By enabling debugging using a <%@ Page Debug="true" %> directive in the ASPX file or a <compilation debug="true"> statement in Web.config, the generated code can be viewed. The code is stored in a CS or VB file (usually in the \%SystemRoot%\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files). 45. Directives for ASP.NET Web Pages Directives specify settings that are used by the page and user-control compilers when the compilers process ASP.NET Web Forms pages (.aspx files) and user control (.ascx) files. ASP.NET treats any directive block (<%@ %>) that does not contain an explicit directive name as an @ Page directive (for a page) or as an @ Control directive (for a user control). For syntax information and descriptions of the attributes that are available for each directive, use the links that are listed in the following table. Directive Description @ Assembly Links an assembly to the current page or user control declaratively. @ Control Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls). @ Implements Indicates that a page or user control implements a specified .NET Framework interface declaratively. @ Import Imports a namespace into a page or user control explicitly. @ Master Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files. @ MasterType Defines the class or virtual path used to type the Master property of a page. @ OutputCache Controls the output caching policies of a page or user control declaratively. @ Page Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files. @ PreviousPageType Creates a strongly typed reference to the source page from the target of a cross-page posting. @ Reference Links a page, user control, or COM control to the current page or user control declaratively. @ Register Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control. 46. 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='' 47. How can u handle Exceptions in Asp.Net? using system.exceptions namespace try { //set of code } Catch (Exception1 e) { //error display } Catch (Exception2 e) { //error display } finally { //compulsory execution will be done here } 48. How can u handle UnManaged Code Exceptions in ASP.Net? The Unmanaged code supports the SHE (Structured Exception Handling) type and COM based exception handling (return S_OK or E_NOINTERFACE). Progm# unmanaged Void my Trans _found (unsigned int u, pexecption_Pointrers pexp) { Count<< in my trans_ func\n; Throw Onmyexception (u, pexp); }
38. 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. 40. 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. 41. Which two properties are there on every validation control? ControlToValidate, ErrorMessage 42. How do you use css in asp.net? Within the <HEAD> section of an HTML document that will use these styles, add a link to this external CSS style sheet that follows this form: <LINK REL="STYLESHEET" TYPE="text/css" HREF="MyStyles.css"> MyStyles.css is the name of your external CSS style sheet.
19
Application state is a key-value dictionary structure created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it. Cache data can persist for a long time, but not across application restarts. It can hold both large and small amounts of data effectively. Also, data can expire based on time set by the application code or other dependencies; this feature is not available in the Application object. 58. What is the difference between control and component? Components implement the System.ComponentModel.IComponent interface by deriving from the SystemComponent.Model.Component base class. Component is generally used for an object that is reusable and can interact with other objects. ASP.NET Framework component additionally provides features such as control over external resources and design-time support. A control is a component that provides user-interface capabilities. Controls draw themselves and shown in the visual area. The .NET Framework provides two base classes for controls: one for client-side Windows Forms controls and the other for ASP.NET server controls. These are System.Windows.Forms.Control and System.Web.UI.Control. System.Windows.Forms.Control derives from Component base class and itself provides UI capabilities. System.Web.UI.Control implements IComponent and provides the infrastructure on which it is easy to add UI functionality. 59. You ve defined one page_load event in aspx page and same page_load event in code behind how will prog run? In this case, Page_Load () method of aspx.cs takes precedence over the Page_Load() method of aspx file. 60. Where would you use an IHttpModule, and what are the limitations of any approach you might take in implementing one of ASP.NET? most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the requesting a customHTTP module 61. Can you edit data in the Repeater control? NO 62. Which template must you provide, in order to display data in a Repeater control? Item Template. 63. How can you provide an alternating color scheme in a Repeater control? Use ALTERNATINGITEMSTYLE and ITEMSTYLE, attributes or Templates. 64. 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? Bind() 65. 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\<version>\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). 66. What is the use of sessionstate tag in the web.config file? Configuring session state: Session state features can be configured via the <sessionState> 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: <sessionState timeout="40"/> 67. 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.
<%@ 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 51. What is the Global ASA(X) File? Global asax file is used to handle application, session level events and to initializes application and session level variables. 52. 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 its 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; 53. Which is the namespace used to write error message in event Log File? system.Daignostics 54. What are the page level transaction and class level transaction? - ASP.NET transaction support allows pages to participate in ongoing Microsoft .NET Framework transactions. Transaction support is exposed via an @Transaction directive that indicates the desired level of support: Required, RequiresNew, Supported, NotSupported, Disabled. - The Transaction attribute is applied at the class level too to indicate that all class methods should be run in the context of a transaction. If an unhandled exception is thrown during the execution of a class method, the transaction is aborted. Otherwise, the transaction is committed. using System.EnterpriseServices; [Transaction] public class TransactionAttribute_Cl : ServicedComponent { } 55. What are different transaction options? Required - Shares a transaction, if one exists, and creates a new transaction, if necessary. RequiresNew- Creates the component with a new transaction, regardless of the state of the current context. Supported- Shares a transaction, if one exists. NotSupported- Indicates that the object does not run within the scope of transactions. When a request is processed, its object context is created without a transaction, regardless of whether there is a transaction active. Disabled - Ignores any transaction in the current context 56. What is the namespace for encryption? System.Security.Cryptography 57. What is the difference between application and cache variables? ASP.NET allows you to save values using application state (an instance of the HttpApplicationState class) for each active Web application. Application state is a global storage mechanism accessible from all pages in the Web application and is thus useful for storing information that needs to be maintained between server round trips and between pages. The memory occupied by variables stored in application state is not released until the value is either removed or replaced.
20
1. What are design patterns ? Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a problem context and the proposed solution for the same. Design patterns existed in some or other form right from the inception stage of software development. Let's say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns. 2. When not to use Design Patterns Do not use design patterns in any of the following situations. When the software being designed would not change with time. When the requirements of the source code of the application are unique. If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design. 3. When to use Design Patterns Design Patterns are particularly useful in one of the following scenarios. When the software application would change in due course of time. When the application contains source code that involves object creation and event notification. 4. Benefits of Design Patterns The following are some of the major advantages of using Design Patterns in software development. Flexibility Adaptability to change Reusability 5. Which are the three main categories of design patterns ? There are three basic classifications of patterns Creational, Structural, and Behavioral patterns. Creational Patterns Abstract Factory : Creates an instance of several families of classes Builder : Separates object construction from its representation Factory Method : Creates an instance of several derived classes Prototype : A fully initialized instance to be copied or cloned Singleton : A class in which only a single instance can exist Note : The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States). Structural Patterns : Adapter : Match interfaces of different classes . Bridge : Separates an object's abstraction from its implementation. Composite : A tree structure of simple and composite objects. Decorator : Add responsibilities to objects dynamically. Flyweight : A fine-grained instance used for efficient sharing. Proxy : An object representing another object. Note : To remember structural pattern best is (ABCDFFP) Behavioral Patterns : Mediator : Defines simplified communication between classes. Memento : Capture and restore an object's internal state. Interpreter : A way to include language elements in a program. Iterator : Sequentially access the elements of a collection. Chain of Resp : A way of passing a request between a chain of objects. Command : Encapsulate a command request as an object. State : Alter an object's behavior when its state changes. Strategy : Encapsulates an algorithm inside a class. Observer : A way of notifying change to a number of classes. Template Method : Defer the exact steps of an algorithm to a subclass. Visitor : Defines a new operation to a class without change. Note: Just remember Music....... 2 MICS On TV (MMIICCSSOTV). 6. Can you explain factory pattern ? Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it's meant to construct and create something. In software architecture world factory pattern is meant to centralize creation of objects. Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client. There are two issues with the code below : First we have lots of 'new' keyword scattered in the client. In other ways the client is loaded with lot of object creational activities which can make the client logic very complicated. Second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type called as 'InvoiceWithFooter' we need to reference the new class in the client and recompile the client also.
21
Figure 1. Different types of invoice Taking these issues as our base we will now look in to how factory pattern can help us solve the same. Below figure 'Factory Pattern' shows two concrete classes 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'. The first issue was that these classes are in direct contact with client which leads to lot of 'new' keyword scattered in the client code. This is removed by introducing a new class 'ClsFactoryInvoice' which does all the creation of objects. The second issue was that the client code is aware of both the concrete classes i.e. 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'. This leads to recompiling of the client code when we add new invoice types. For instance if we add 'ClsInvoiceWithFooter' client code needs to be changed and recompiled accordingly. To remove this issue we have introduced a common interface 'IInvoice'. Both the concrete classes 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader' inherit and implement the 'IInvoice' interface. The client references only the 'IInvoice' interface which results in zero connection between client and the concrete classes ( 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'). So now if we add new concrete invoice class we do not need to change any thing at the client side. In one line the creation of objects is taken care by 'ClsFactoryInvoice' and the client disconnection from the concrete classes is taken care by 'IInvoice' interface.
Figure 4. Factory class which generates objects Note : The above example is given in C# . Even if you are from some other technology you can still map the concept accordingly. You can get source code from the CD in 'FactoryPattern' folder. 7. Can you explain abstract factory pattern ? Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class. All other things related to factory pattern remain same as discussed in the previous question. A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client.
Figure 2. Factory pattern Below are the code snippets of how actually factory pattern can be implemented in C#. In order to avoid recompiling the client we have introduced the invoice interface 'IInvoice'. Both the concrete classes 'ClsInvoiceWithOutHeaders' and 'ClsInvoiceWithHeader' inherit and implement the 'IInvoice' interface.
Figure 5. Abstract factory unifies related factory patterns Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (AbstractFactory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface. For instance in figure 'Implementation of abstract factory' both the concrete classes 'product1' and 'product2' inherits from one interface i.e. 'common'. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit.
Figure 3. Interface and concrete classes We have also introduced an extra class 'ClsFactoryInvoice' with a function 'getInvoice()' which will generate objects of both the invoices depending on 'intInvoiceType' value. In short we have centralized the logic of object creation in the 'ClsFactoryInvoice'. The client calls the 'getInvoice' function to generate the invoice classes. One of the most important points to be noted is that client only refers to 'IInvoice' type and the factory class 'ClsFactoryInvoice' also gives the same type of reference. This helps the client to be complete detached from the concrete classes, so now when we add new classes and invoice types we do not need to recompile the client.
Figure 6. Implementation of abstract factory Now let's have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes 'ClsFactoryButton' and 'ClsFactoryText'. Both these classes inherit from common interface 'InterfaceRender'. Both the factories 'ClsFactoryButton' and 'ClsFactoryText' inherits from the common factory 'ClsAbstractFactory'. Figure 'Example for AbstractFactory' shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( ClsAbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface 'InterfaceRender'. So the 'ClsAbstractFactory' class provides a common interface for both factories 'ClsFactoryButton' and 'ClsFactoryText'.
22
separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.
To understand what we mean by construction and representation lets take the example of the below 'Tea preparation' sequence. You can see from the figure 'Tea preparation' from the same preparation steps we can get three representation of tea's (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk).
Figure 7. Example for abstract factory Note: We have provided a code sample in C# in the 'AbstractFactory' folder. People who are from different technology can compare easily the implementation in their own language. We will just run through the sample code for abstract factory. Below code snippet 'Abstract factory and factory code snippet' shows how the factory pattern classes inherit from abstract factory.
Figure 12. Tea preparation Now let's take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either 'PDF' or 'EXCEL' format. Figure 'Request a report' shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.
Figure 8. Abstract factory and factory code snippet Figure 'Common Interface for concrete classes' how the concrete classes inherits from a common interface 'InterFaceRender' which enforces the method 'render' in all the concrete classes.
Figure 9. Common interface for concrete classes The final thing is the client code which uses the interface 'InterfaceRender' and abstract factory 'ClsAbstractFactory' to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.
Figure 13. Request a report Now let's take a different view of the problem as shown in figure 'Different View'. The same flow defined in 'Request a report' is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.
Figure 10. Client, interface and abstract factory 8. Can you explain builder pattern? Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to
Figure 14. Different View We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns. Builder : Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
23
Figure 19. Client, builder, director and product Figure 15. Builder class hierarchy Figure 'Builder classes in actual code' shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for 'PDF' (ReportPDF) and other for 'EXCEL' (ReportExcel). These two custom builders define there own process according to the report type. The output is something like this. We can see two report types displayed with their headers according to the builder.
Figure 20. Final output of builder 9. Can you explain prototype pattern ? Prototype pattern falls in the section of creational pattern. It gives us a way to create new objects from the existing instance of the object. In one sentence we clone the existing object with its data. By cloning any changes to the cloned object does not affect the original object value. If you are thinking by just setting objects we can get a clone then you have mistaken it. By setting one object to other object we set the reference of object BYREF. So changing the new object also changed the original object. To understand the BYREF fundamental more clearly consider the figure 'BYREF' below. Following is the sequence of the below code: In the first step we have created the first object i.e. obj1 from class1. In the second step we have created the second object i.e. obj2 from class1. In the third step we set the values of the old object i.e. obj1 to 'old value'. In the fourth step we set the obj1 to obj2. In the fifth step we change the obj2 value. Now we display both the values and we have found that both the objects have the new value.
Figure 16. Builder classes in actual code Now let's understand how director will work. Class 'clsDirector' takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure 'Director in action' shows how the method 'MakeReport' calls the individual process to generate the report product by PDF or EXCEL.
Figure 21. BYREf The conclusion of the above example is that objects when set to other objects are set BYREF. So changing new object values also changes the old object value. Figure 17. Director in action The third component in the builder is the product which is nothing but the report class in this case. There are many instances when we want the new copy object changes should not affect the old object. The answer to this is prototype patterns. Lets look how we can achieve the same using C#. In the below figure 'Prototype in action' we have the customer class 'ClsCustomer' which needs to be cloned. This can be achieved in C# my using the 'MemberWiseClone' method. In JAVA we have the 'Clone' method to achieve the same. In the same code we have also shown the client code. We have created two objects of the customer class 'obj1' and 'obj2'. Any changes to 'obj2' will not affect 'obj1' as it's a complete cloned copy.
Figure 18. The report class Now let's take a top view of the builder project. Figure 'Client,builder,director and product' shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.
Figure 22. Prototype in action Note : You can get the above sample in the CD in 'Prototype' folder. In C# we use the 'MemberWiseClone' function while in JAVA we have the 'Clone' function to achieve the same.
24
10. Can you explain shallow copy and deep copy in prototype patterns ? There are two types of cloning for prototype patterns. One is the shallow cloning which you have just read in the first question. In shallow copy only that object is cloned, any objects containing in that object is not cloned. For instance consider the figure 'Deep cloning in action' we have a customer class and we have an address class aggregated inside the customer class. 'MemberWiseClone' will only clone the customer class 'ClsCustomer' but not the 'ClsAddress' class. So we added the 'MemberWiseClone' function in the address class also. Now when we call the 'getClone' function we call the parent cloning function and also the child cloning function, which leads to cloning of the complete object. When the parent objects are cloned with their containing objects it's called as deep cloning and when only the parent is clones its termed as shallow cloning.
Figure 25. Menu and Commands Command pattern moves the above action in to objects. These objects when executed actually execute the command. As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in 'clsExecuteExit' , open action is wrapped in 'clsExecuteOpen', print action is wrapped in 'clsExecutePrint' and so on. All these classes are inherited from a common interface 'IExecute'.
Figure 23. Deep cloning in action 11. Can you explain singleton pattern ? There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern :Define the constructor as private. Define the instances and methods as static. Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and methods using the static keyword as shown in the below code snippet figure 'Singleton in action'. The static keyword ensures that you only one instance of the object is created and you can all the methods of the class with out creating the object. As we have made the constructor private, we need to call the class directly.
Figure 26. Objects and Command Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action. So we have added all the actions in one collection i.e. the arraylist. We have exposed a method 'getCommand' which takes a string and gives back the abstract object 'IExecute'. The client code is now neat and clean. All the 'IF' conditions are now moved to the 'clsInvoker' class.
Figure 24. Singleton in action Note : In JAVA to create singleton classes we use the STATIC keyword , so its same as in C#. You can get a sample C# code for singleton in the 'singleton' folder. 12. Can you explain command patterns? Command pattern allows a request to exist as an object. Ok let's understand what it means. Consider the figure 'Menu and Commands' we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of 'IF' condition which makes the coding more cryptic.
Figure 27. Invoker and the clean client 13. What is Interpreter pattern ? Interpreter pattern allows us to interpret grammar in to code solutions. Ok, what does that mean?. Grammars are mapped to classes to arrive to a solution. For instance 72 can be mapped to 'clsMinus' class. In one line interpreter pattern gives us the solution of how to write an interpreter which can read a grammar and execute the same in the code. For instance below is a simple example where we can give the date format grammar and the interpreter will convert the same in to code solutions and give the desired output.
25
Figure 1. Date Grammar Let's make an interpreter for date formats as shown in figure 'Date Grammar'. Before we start lets understand the different components of interpreter pattern and then we will map the same to make the date grammar. Context contains the data and the logic part contains the logic which will convert the context to readable format.
Figure 5. Expression and Context classes Figure 2. Context and Logic Let's understand what is the grammar in the date format is. To define any grammar we should first break grammar in small logical components. Figure 'Grammar mapped to classes' show how different components are identified and then mapped to classes which will have the logic to implement only that portion of the grammar. So we have broken the date format in to four components Month, Day, Year and the separator. For all these four components we will define separate classes which will contain the logic as shown in figure 'Grammar mapped to classes'. So we will be creating different classes for the various components of the date format. Now that we have separate expression parsing logic in different classes, let's look at how the client will use the iterator logic. The client first passes the date grammar format to the context class. Depending on the date format we now start adding the expressions in a collection. Finally we just loop and call the 'Evaluate' method. Once all the evaluate methods are called we display the output.
Figure 3. Grammar mapped to classes As said there are two classes one is the expression classes which contain logic and the other is the context class which contain data as shown in figure 'Expression and Context classes'. We have defined all the expression parsing in different classes, all these classes inherit from common interface 'ClsAbstractExpression' with a method 'Evaluate'. The 'Evaluate' method takes a context class which has the data; this method parses data according to the expression logic. For instance 'ClsYearExpression' replaces the 'YYYY' with the year value,''ClsMonthExpression' replaces the 'MM' with month and so on.
Figure 6. Client Interpreter logic Note :- You can find the code for interpreter in 'Interpeter' folder. 14. Can you explain iterator pattern ? Iterator pattern allows sequential access of elements with out exposing the inside code. Let's understand what it means. Let's say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It's the most common and unknowingly used pattern. Whenever you use a 'foreach' (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.
26
In figure 'Iterator business logic' we have the 'clsIterator' class which has collection of customer classes. So we have defined an array list inside the 'clsIterator' class and a 'FillObjects' method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like 'getByIndex' ( which can look up using a particular index) , 'Prev' ( Gets the previous customer in the collection , 'Next' (Gets the next customer in the collection), 'getFirst' ( Gets the first customer in the collection ) and 'getLast' ( Gets the last customer in the collection). So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed. Below figures 'Client Iterator Logic' shows how the 'ObjIterator' object which is created from class 'clsIterator' is used to display next, previous, last, first and customer by index.
Figure 10. Scenario 1 Scenario 2 :- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.
Figure 11. Scenario 2 Scenario 3 :- If the user click the clear button it should clear the name text box and disable the add and clear button.
Figure 8. Client Iterator logic Note :- You can get a sample C# code in the 'Iterator' folder of the CD provided with this book. 15. Can you explain mediator pattern ? Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.
Figure 13. Scenario 3 Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI's. Below figure 'Complex interactions between components' depicts the logical complexity.
Figure 9. Mediator sample example Let's consider the figure 'Mediator sample example' which depicts a true scenario of the need of mediator pattern. It's a very user-friendly user interface. It has three typical scenarios. Scenario 1 :- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.
Figure 14. Complex interactions between components Ok now let me give you a nice picture as shown below 'Simplifying using mediator'. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
Figure 15. Simplifying using mediator Now let's look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure
27
changed the memento class snapshot is not changed. The 'Revert' method sets back the memento data to the main class.
Figure 16. Mediator class The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the 'TextChange' method of the mediator, when the user clicks add we call the 'ClickAddButton' and for clear click we call the 'ClickClearButton'. Figure 19. Customer class for memento The client code is pretty simple. We create the customer class. In case we have issues we click the cancel button which in turn calls the 'revert' method and reverts the changed data back to the memento snapshot data. Figure 'Memento client code' shows the same in a pictorial format.
Figure 17. Mediator client logic Note :- You can get the C# code for the above mediator example in the 'mediator' folder. 16. Can you explain memento pattern? Memento pattern is the way to capture objects internal state with out violating encapsulation. Memento pattern helps us to store a snapshot which can be reverted at any moment of time by the object. Let's understand what it means in practical sense. Consider figure 'Memento practical example', it shows a customer screen. Let's say if the user starts editing a customer record and he makes some changes. Later he feels that he has done something wrong and he wants to revert back to the original data. This is where memento comes in to play. It will help us store a copy of data and in case the user presses cancel the object restores to its original state.
Figure 20. Memento client code Note :- A sample code in C# for memento is available in the memento folder of the CD. 17. Can you explain observer pattern ? Observer pattern helps us to communicate between parent class and its associated or dependent classes. There are two important concepts in observer pattern 'Subject' and 'Observers'. The subject sends notifications while observers receive notifications if they are registered with the subject. Below figure 'Subject and observers' shows how the application (subject) sends notification to all observers (email, event log and SMS). You can map this example to publisher and subscriber model. The publisher is the application and subscribers are email, event log and sms.
Figure 18. Memento practical example Let's try to complete the same example in C# for the customer UI which we had just gone through. Below is the customer class 'clsCustomer' which has the aggregated memento class 'clsCustomerMemento' which will hold the snapshot of the data. The memento class 'clsCustomerMemento' is the exact replica ( excluding methods ) of the customer class 'clsCustomer'. When the customer class 'clsCustomer' gets initialized the memento class also gets initialized. When the customer class data is
Figure 21. Subject and Observers Let's try to code the same example which we have defined in the previous section. First let's have a look at the subscribers / notification classes. Figure 'Subscriber classes' shows the same in a pictorial format. So we have a common interface for all subscribers i.e. 'INotification' which has a 'notify' method. This interface 'INotification' is implemented by all concrete notification classes. All concrete notification classes define their own notification methodology. For the current scenario we have just displayed a print saying the particular notification is executed.
28
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. 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 2. Are Web Services a replacement for other distributed computing platforms? No. Web Services is just a new way of looking at existing implementation platforms. 3. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice? A: WebService will support only DataSet. 4. 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. 5. 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 <url or path> 6. What is a proxy in web service? How do I use a proxy server when invoking a Web service?
Figure 22. Subscriber classes As said previously there are two sections in an observer pattern one is the observer/subscriber which we have covered in the previous section and second is the publisher or the subject. The publisher has a collection of arraylist which will have all subscribers added who are interested in receiving the notifications. Using 'addNotification' and 'removeNotification' we can add and remove the subscribers from the arraylist. 'NotifyAll' method loops through all the subscribers and send the notification.
Figure 23. Publisher/Subject classes Now that we have an idea about the publisher and subscriber classes lets code the client and see observer in action. Below is a code for observer client snippet. So first we create the object of the notifier which has collection of subscriber objects. We add all the subscribers who are needed to be notified in the collection. Now if the customer code length is above 10 characters then tell notify all the subscribers about the same.
Figure 24. Observer client code WEBSERVICES AND 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. 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. Business integration Web services allow trading partners to engage in e-business leveraging the existing Internet infrastructure. Organizations can send electronic
29
us to intercept the SOAP customize the different components messages during the serialization of the .NET remoting framework. and deserialization stages. Ease-of-Programming Easy-to-create and deploy. Complex to program.
18.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 TCPChannelremoting 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. 19. Can you pass SOAP messages through remoting? 20. 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 doesnt 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) 21. 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. 23. Web Client class and its methods? 24. Flow of remoting? 25. WebFarm Vs webGardens A web farm is a multi-server scenario. So we may have a server in each state of US. If the load on one server is in excess then the other servers step in to bear the brunt. How they bear it is based on various models. 1. RoundRobin. (All servers share load equally) 2. NLB (economical) 3. HLB (expensive but can scale up to 8192 servers) 4. Hybrid (of 2 and 3). 5. CLB (Component load balancer). A web garden is a multi-processor setup. i.e., a single server (not like the multi server above). How to implement webfarms in .Net: Go to web.config and Here for mode = you have 4 options. a) Say mode=inproc (non web farm but fast when you have very few customers). b) Say mode=StateServer (for webfarm) c) Say mode=SqlServer (for webfarm) Whether to use option b or c depends on situation. StateServer is faster but SqlServer is more reliable and used for mission critical applications. How to use webgardens in .Net: Go to web.config and Change the false to true. You have one more attribute that is related to webgarden in the same tag called cpuMask. 26. What is the difference between a namespace and assembly name? A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under control of the developer. For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might be logically expected to have functionally related to file access. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality,
State Management
Provide support for both stateful and Web services work in a stateless stateless environments through environment Singleton and SingleCall objects Web services support only the Using binary communication, .NET datatypes defined in the XSD type Remoting can provide support for system, limiting the number of rich type system objects that can be serialized. Web services support .NET remoting requires the client be interoperability across platforms, built using .NET, enforcing and are ideal for heterogeneous homogenous environment. environments. Can also take advantage of IIS for Highly reliable due to the fact that fault isolation. If IIS is not used, Web services are always hosted in application needs to provide IIS plumbing for ensuring the reliability of the application. Provides extensibility by allowing Very extensible by allowing us to
Type System
Interoperability
Reliability
Extensibility
30
42. How can you automatically generate interface for the remotable object in .NET with Microsoft tools? Use the Soapsuds tool. 43 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. On the server, open the Web Services Description Language (WSDL) file. In the WSDL file, locate the <soap:address> element that corresponds to the service and change the location attribute for this element to port 8080. For example, if the location attribute specifies <http://MyServer/VDir/Service.wsdl> change this attribute to <http://MyServer:8080/VDir/Service.wsdl>. Run MSSOAPT.exe. 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). 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. Copy the WSDL file from the server to the client. Modify location attribute of the <soap:address> 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 <http://MyServer/VDir/Service.wsdl>, change it to <http://localhost:8080/VDir/Service.wsdl> and make note of "MyServer". On the client, run MSSOPT.exe. 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). In the Destination host box, enter the host specified in Step 2. In the Destination port box, enter the port specified in Step 2. Click OK. 44. What is a Web service? Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications. Beyond this basic definition, a Web service may also have two additional (and desirable) properties: First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems. 45. What is new about Web services? People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP. So, what is really new about Web services? The answer is XML. XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories. Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well. By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting. 46. I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action? If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services--where the end result looks like a stripped-down version of my.yahoo or my.excite.
34. What are channels in .NET Remoting? Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred. 35. What security measures exist for .NET Remoting in System.Runtime.Remoting? None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level. 36. What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end. 37. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable. 38. Whats SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode. 39. Whats Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease. 40. How do you define the lease of the object? By implementing ILease interface when writing the class code. 41. Can you configure a .NET Remoting object via XML file? Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
31
As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode). Here is a sample SOAP response from the weather service: <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getWeatherResponse xmlns:ns1="urn:examples:weatherservice" SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding"> <return xsi:type="xsd:int">65</return> </ns1:getWeatherResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> The response indicates a single integer return value (the current temperature). The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details. 50. What is WSDL? The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack. In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following: Information on all publicly available functions. Data type information for all XML messages. Binding information about the specific transport protocol to be used. Address information for locating the specified service. WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services. Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points. First, the <message> elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the <service> element specifies that the service is available via SOAP and is available at a specific URL. <?xml version="1.0" encoding="UTF-8"?> <definitions name="WeatherService" targetNamespace="http://www.ecerami.com/wsdl/WeatherService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.ecerami.com/wsdl/WeatherService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="getWeatherRequest"> <part name="zipcode" type="xsd:string"/> </message> <message name="getWeatherResponse"> <part name="temperature" type="xsd:int"/> </message> <portType name="Weather_PortType"> <operation name="getWeather"> <input message="tns:getWeatherRequest"/> <output message="tns:getWeatherResponse"/> </operation> </portType> <binding name="Weather_Binding" type="tns:Weather_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="getWeather"> <soap:operation soapAction=""/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:weatherservice" use="encoded"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:weatherservice" use="encoded"/> </output> </operation> </binding> <service name="Weather_Service"> <documentation>WSDL File for Weather Service</documentation> <port binding="tns:Weather_Binding" name="Weather_Port">
32
5.How CCW and RCW is working? CCW: When a COM application calls a NET object the CLR creates the CCW as a proxy since the COM application is unable to directly access the .NET object. RCW: When a .NET application calls a COM object the CLR creates the RCW as a proxy since the .NET application is unable to directly access the .COM object. 6.How will you register com+ services? The .NET Framework SDK provides the .NET Framework Services Installation Tool (Regsvcs.exe - a command-line tool) to manually register an assembly containing serviced components. You can also access these registration features programmatically with the ystem.EnterpriseServicesRegistrationHelper class by creating an instance of class RegistrationHelper and using the method InstallAssembly 7.What is use of ContextUtil class? ContextUtil is the preferred class to use for obtaining COM+ context information. 8. What is the new three features of COM+ services, which are not there in COM (MTS)? Role based security. Neutral apartment threading. New environment called context which defines the execution environment 9. Is the COM architecture same as .Net architecture? What is the difference between them? .Net architecture has superseded the old COM architecture providing a flexible rapid application development environment which can be used to create windows, web and console applications and web services. .NET provides a powerful development environment that can be used to create objects in any .NET compliant language. .NET addresses the previous problems of dll hell with COM by providing strongly named assemblies and side-by-side execution where two assemblies with the same name can run on the same box. 10. Can we copy a COM dll to GAC folder? No. It only stores .NET assemblies. 11. 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. 12.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. 13. 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. XML 1. Explain the concept of data island? An XML data island is XML data embedded into an HTML page. XML Data Islands only works with Internet Explorer browsers. You should use JavaScript and XML DOM to parse and display XML in HTML. 2. How to use XML DOM model on client side using JavaScript. What are the ways to create a tree view control using XML, XSL & JavaScript?Questions on XPathNavigator, and the other classes in System.XML Namespace? 3. What is Use of Template in XSL? 4. What is Well Formed XML and Valid XML 5. How you will do SubString in XSL 6. Can we do sorting in XSL ? how do you deal sorting columns dynamically in XML. 7. What is Async property of XML Means ? 8. What is XPath Query ? 9. Difference Between Element and Node. 10. What is CDATA Section. 11. DOM & SAX parsers explanation and difference 12. What is GetElementbyname method will do?
33
27. what is schema schema and DTD? A DTD is: The XML Document Type Declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition or DTD. The DTD can point to an external subset containing markup declarations, or can contain the markup declarations directly in an internal subset, or can even do both. A Schema is: XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents. In summary, schemas are a richer and more powerful of describing information than what is possible with DTDs. 28. What is the difference between SAX parser and DOM parser? DOM parser - reads the whole XML document and returns a DOM tree representation of xml document. It provides a convenient way for reading, analyzing and manipulating XML files. It is not well suited for large xml files, as it always reads the whole file before processing. SAX parser - works incrementally and generate events that are passed to the application. It does not generate data representation of xml content so some programming is required. However, it provides stream processing and partial processing which cannot be done alone by DOM parser. 29. Describe the differences between XML and HTML. It's amazing how many developers claim to be proficient programming with XML, yet do not understand the basic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below. Differences Between XML and HTML XML HTML User definable tags Defined set of tags designed for web display Content driven Format driven End tags required for well formed documents End tags not required Quotes required around attributes values Quotes not required Slash required in empty tags Slash not required 30. Describe the role that XSL can play when dynamically generating HTML pages from a relational database. Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules. Give a few examples of types of applications that can benefit from using XML. There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices. 31. What is DOM and how does it relate to XML? The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX. What is SOAP and how does it relate to XML? The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML. 32. Can you walk us through the steps necessary to parse XML documents? Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response.
34
38. What is SOAP? The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. 39. What is DOM? The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily. 40. Can you walk us through the steps necessary to parse XML file? DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder domBuilder = factory.newDocumentBuilder(); Document doc = domBuilder.parse(XMLFile); 40. Is it necessary to validate XML file against a DTD? Although XML does not require data to be validated against a DTD, many of the benefits of using the echnology are derived from being able tovalidate XML documents against business or technical architecture rules. 40. What is XPath? XPath stands for XML Path Language XPath is a syntax for defining parts of an XML document XPath is used to navigate through elements and attributes in an XML document XPath contains a library of standard functions XPath is a major element in XSLT XPath is designed to be used by both XSLT and XPointer XPath is a W3C Standard 41. What is XSL? XSLT - a language for transforming XML documents XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element. 42. What is a DTD and a Schema? The XML Document Type Declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition or DTD.The DTD can point to an external subset containing markup declarations, or can contain the markup declarations directly in an internal subset, or can even do both. A Schema is:XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents.Schemas are a richer and more powerful of describing information than what is possible with DTDs. 43. 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. <?xml version="1.0"?> <diffgr:diffgram 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"> <DataInstance> </DataInstance> <diffgr:before> </diffgr:before> <diffgr:errors> </diffgr:errors> </diffgr:diffgram> 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.
35
8. What are Ajax Extensions? The ASP.NET Ajax Extensions are set of Ajax-based controls that work in ASP.NET 2 (or above) based applications. Ofcourse,they also need the Ajax runtime which is actually the Ajax Framework 1.0. ASP.NET Ajax Extensions 1.0 have to be downloaded to run with ASP.NET 2.0 The new ASP.NET 3.5 Framework comes with the Ajax Library 3.5 (containing the Ajax Extensions 3.5). So in order to use the latest Ajax, simply download .NET 3.5 Framework. 9. What is the ASP.NET Control Toolkit? Besides the Ajax Framework (which is the Ajax engine) and Ajax Extensions (which contain the default Ajax controls), there is a toolkit called the Ajax Control Toolkit available for use & download (for free). This is a collection of rich featured, highly interactive controls, created as a joint venture between Microsoft & the Developer Community. 10. What is Dojo? Dojo is a third-party javascript toolkit for creating rich featured applications. Dojo is an Open Source DHTML toolkit written in JavaScript. It builds on several contributed code bases (nWidgets, Burstlib, f(m)), which is why we refer to it sometimes as a "unified" toolkit. Dojo aims to solve some long-standing historical problems with DHTML which prevented mass adoption of dynamic web application development. 11. How to handle multiple or concurrent requests in Ajax? For concurrent requests, declare separate XmlHttpRequest objects for each request. For example, for request to get data from an SQL table1, use something like this... xmlHttpObject1.Onreadystatechange = functionfromTable1(); and to get data from another table (say table2) at the same time, use xmlHttpObject2.Onreadystatechange = functionfromTable2(); Ofcourse, the XmlHttpObject needs to be opened & parameters passed too, like as shown below... xmlHTTPObject1.open("GET","http://"localhost// " + "Website1/Default1.aspx" true); Note that the last parameter "true" used above means that processing shall carry on without waiting for any response from the web server. If it is false, the function shall wait for a response. 12. How to create an AJAX website using Visual Studio? Using Visual Studio Web Developer Express 2005 & versions above it, Ajax based applications may easily be created. Note that the Ajax Framework & Ajax Extensions should be installed (In case of VS 2005). If using Visual Studio 2008 Web Developer Express or above, Ajax comes along with it (so no need of a separate installation). Steps: Start Visual Studio, Click on File -> New Website -> Under Visual Studio Installed templates -> Select ASP.NET Ajax-Enabled Site. Enter a location & select OK. 13. Can we override the EnablePartialRendering property of the ScriptManager class? Yes. But this has to be done before the init event of the page (or during runtime after the page has already loaded). Otherwise an InvalidOperationException will be thrown. 14. How to use multiple ScriptManager controls in a web page? No. It is not possible to use multiple ScriptManager control in a web page. In fact, any such requirement never comes in because a single ScriptManager control is enough to handle the objects of a web page. 15 Whats the difference between RegisterClientScriptBlock, RegisterClientScriptInclude and RegisterClientScriptResource? For all three, a script element is rendered after the opening form tag. Following are the differences: 1 - RegisterClientScriptBlock - The script is specified as a string parameter. 2 - RegisterClientScriptInclude - The script content is specified by setting the src attribute to a URL that points to a script file. 3 - RegisterClientScriptResource - The script content is specified with a resource name in an ssembly. The src attribute is automatically populated with a URL by a call to an HTTP handler that retrieves the named script from the assembly. 16. What are type/key pairs in client script registration? Can there be 2 scripts with the same type/key pair name? When a script is registered by the ScriptManager class, a type/key pair is created to uniquely identify the script. For identification purposes, the type/key pair name is always unique for dentifying a script. Hence, there may be no duplication in type/key pair names. 17. What is an UpdatePanel Control? An UpdatePanel control is a holder for server side controls that need to be partial postbacked in an ajax cycle. All controls residing inside the UpdatePanel will be partial postbacked. Below is a small example of using an UpdatePanel. As you see here after running the snippet above, there wont be a full postback exhibited by the web page. Upon clicking the button, the postback shall be partial. This means that contents outside the UpdatePanel wont be posted back to the web server. Only the contents within the UpdatePanel are refreshed. 18. How to control how long an Ajax request may last? Use the ScriptManager's AsyncPostBackTimeout Property. For example, if you want to debug a web page but you get an error that the page request has timed out, you may set where the value specified is in seconds.
36
25. Do I really need to learn JavaScript? Basically yes if you plan to develop new AJAX functionality for your web application. On the other hand, JSF components and component libraries can abstract the details of JavaScript, DOM and CSS. These components can generate the necessary artifacts to make AJAX interactions possible. Visual tools such as Java Studio Creator may also use AJAX enabled JSF components to create applications, shielding the tool developer from many of the details of AJAX. If you plan to develop your own JSF components or wire the events of components together in a tool it is important that you have a basic understanding of JavaScript. There are client-side JavaScript libraries (discussed below) that you can call from your in page JavaScript that abstract browser differences. Object Hierarchy and Inheritance in JavaScript is a great resource for a Java developer to learn about JavaScript objects.
26. What is the difference between proxied and proxyless calls? Proxied calls are made through stub objects that mimic your PHP classes on the JavaScript side. E.g., the helloworld class from the Hello World example. Proxyless calls are made using utility javascript functions like HTML_AJAX.replace() and HTML_AJAX.append(). 27. Should I use XML or text, JavaScript, or HTML as a return type? It depends. Clearly the 'X' in AJAX stands for XML, but several AJAX proponents are quick to point out that nothing in AJAX, per se, precludes using other types of payload, such as, JavaScript, HTML, or plain text. * XML - Web Services and AJAX seem made for one another. You can use client-side API's for downloading and parsing the XML content from RESTful Web Services. (However be mindful with some SOAP based Web Services architectures the payloads can get quite large and complex, and therefore may be inappropriate with AJAX techniqes.) * Plain Text - In this case server-generated text may be injected into a document or evaluated by client-side logic. * JavaScript - This is an extension to the plain text case with the exception that a server-side component passes a fragment of JavaScript including JavaScript object declarations. Using the JavaScript eval() function you can then create the objects on the client. JavaScript Object Notation (JSON), which is a JavaScript object based data exchange specification, relies on this technique. * HTML - Injecting server-generated HTML fragments directly into a document is generally a very effective AJAX technique. However, it can be complicated keeping the serverside component in sync with what is displayed on the client. Mashup is a popular term for creating a completely new web application by combining the content from disparate Web Services and other online API's. A good example of a mashup is housingmaps.com which graphically combines housing want-ads from craiglist.org and maps from maps.google.com. 28. Are there any frameworks available to help speedup development with AJAX? There are several browser-side frameworks available, each with their own uniqueness... 29. Is Adaptive Path selling Ajax components or trademarking the name? Where can I download it? Ajax isnt something you can download. Its an approach a way of thinking about the architecture of web applications using certain technologies. Neither the Ajax name nor the approach are proprietary to Adaptive Path. 30. Should I use an HTTP GET or POST for my AJAX calls? AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for a consistent web application architecture. 31. How do I debug JavaScript? There are not that many tools out there that will support both client-side and serverside debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers. * Firefox/Mozilla/Netscape - Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers. * Safari - Has a debugger which needs to be enabled. See the Safari FAQ for details. * Internet Explorer - There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful. While debuggers help a common technique knowing as "Alert Debugging" may be used. In this case you place "alert()" function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements. 32. How do I provide internationalized AJAX interactions? Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following: * Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type: * In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding see Comparing escape(), encodeURI(), and
37
47.What about applets and plugins ? Don't be too quick to dump your plugin or applet based portions of your application. While AJAX and DHTML can do drag and drop and other advanced user interfaces there still limitations especially when it comes to browser support. Plugins and applets have been around for a while and have been able to make AJAX like requests for years. Applets provide a great set of UI components and APIs that provide developers literally anything. Many people disregard applets or plugins because there is a startup time to initialize the plugin and there is no guarantee that the needed version of a plugin of JVM is installed. Plugins and applets may not be as capable of manipulating the page DOM. If you are in a uniform environment or can depend on a specific JVM or plugin version being available (such as in a corporate environment) a plugin or applet solution is great. One thing to consider is a mix of AJAX and applets or plugins. Flickr uses a combination of AJAX interactions/DHTML for labeling pictures and user interaction and a plugin for manipulating photos and photo sets to provide a great user experience. If you design your server-side components well they can talk to both types of clients. 48. Why did you feel the need to give this a name? I needed something shorter than Asynchronous JavaScript+CSS+DOM+XMLHttpRequest to use when discussing this approach with clients. 49. Techniques for asynchronous server communication have been around for years. What makes Ajax a new approach? Whats new is the prominent use of these techniques in real-world applications to change the fundamental interaction model of the Web. Ajax is taking hold now because these technologies and the industrys understanding of how to deploy them most effectively have taken time to develop. 50.Is Ajax a technology platform or is it an architectural style? Its both. Ajax is a set of technologies being used together in a particular way. 51.How does HTML_AJAX compare with the XAJAX project at Sourceforge? XAJAX uses XML as a transport for data between the webpage and server, and you don't write your own javascript data handlers to manipulate the data received from the server. Instead you use a php class and built in javascript methods, a combination that works very similiar to the HTML_AJAX_Action class and haSerializer combo. XAJAX is designed for simplicity and ease of use. HTML_AJAX allows for multiple transmission types for your ajax data - such as urlencoding, json, phpserialized, plain text, with others planned, and has a system you can use to write your own serializers to meet your specific needs. HTML_AJAX has a class to help generate javascript (HTML_AJAX_Helper) similiar to ruby on rail's javascript helper (although it isn't complete), and an action system similiar to XAJAX's "action pump" that allows you to avoid writing javascript data handlers if you desire. But it also has the ability to write your own data handling routines, automatically register classes and methods using a server "proxy" script, do different types of callbacks including grabbing remote urls, choose between sync and async requests, has iframe xmlhttprequest emulation fallback capabilities for users with old browsers or disabled activeX, and is in active development with more features planned (see the Road Map for details) HTML_AJAX has additional features such as client pooling and priority queues for more advanced users, and even a javascript utility class. Although you can use HTML_AJAX the same way you use XAJAX, the additional features make it more robust, extensible and flexible. And it is a pear package, you can use the pear installer to both install and keep it up to date. If you're asking which is "better" - as with most php scripts it's a matter of taste and need. Do you need a quick, simple ajax solution? Or do you want something that's flexible, extensible, and looking to incorporate even more great features? It depends on the project, you as a writer, and your future plans. 52. What browsers support AJAX? Internet Explorer 5.0 and up, Opera 7.6 and up, Netscape 7.1 and up, Firefox 1.0 and up, Safari 1.2 and up, among others. 53. Will HTML_AJAX integrate with other Javascript AJAX libraries such as scriptaculous ? How would this integration look like? HTML_AJAX doesn't have specific plans to integrate with other JavaScript libraries. Part of this is because external dependencies make for a more complicated installation process. It might make sense to offer some optional dependencies on a library like scriptaculous automatically using its visual effects for the loading box or something, but there isn't a lot to gain from making default visuals like that flashier since they are designed to be easily replaceable. 54. When should I use an Java applet instead of AJAX? Applets provide a rich experience on the client side and there are many things they can do that an AJAX application cannot do, such as custom data streaming, graphic manipulation, threading, and advanced GUIs. While DHTML with the use of AJAX has been able to push the boundaries on what you can do on the client, there are some things that it just cannot do. The reason AJAX is so popular is that it only requires functionality built into the browser (namely DHTML and AJAX capabilities). The user does not need to download and/or configure plugins. It is easy to incrementally update functionality and know that that functionality will readily available, and there are not any complicated deployment issues. That said, AJAX-based functionality does need to take browser differences into consideration. This is why we recommend using a JavaScript library such as Dojo which abstracts browser differences. So the "bottom line" is: If you are creating advanced UIs where you need more advanced features on the client where you want UI accuracy down to the pixel, to do complex computations on the client, use specialized networking techniques, and where you know that the applet plugin is available for your target audience, applets are the way
38
69. Why can/should AJAX be used? : AJAX is best suited for small (hopefully unobtrusive) updates to the current web page, based on information that is not available until it has been provided by the end user. 70. Describe the formats and protocols used/specified by AJAX The client web page is responsible for creating the XmlHttpRequest, and therefore the connection from the web page to some application on the server. Part of this connection identifies how the response can / should be provided to the client code via the use of a "callback" routine. The callback routine is invoked multiple times with a status code, indicating the reason for the invocation. If the request can be successfully completed by the server application, a responce should also be provided. 71.Describe some things that can't be done with AJAX Sending a request to a server outside of the domain from which the web page originated. 72. How should AJAX objects be created? In a browser general manner, if at all possible. 73. What kinds of applications is Ajax best suited for? We dont know yet. Because this is a relatively new approach, our understanding of where Ajax can best be applied is still in its infancy. Sometimes the traditional web application model is the most appropriate solution to a problem. 74. Are Finite State Machines (FSM's) appropriate for use with AJAX Possibly There are circumstances under which an FSM might be appropriate. It depends upon the complexity of the environment, and the number of machines that might need to be contacted in order to obtain the response to the request. 75. Identify and describe the state transitions that can/should occur within a transaction Reset : When the XmlHttpRequest object is created, no connection yet exists between the clent, and the server. Open : When the xmlHttp.open() is issued, the request is being prepared for transmission to the server Sent : When the xmlHttp.send() is issued, the request is transmitted to the server application Rcvd : When the xmlHttp callback routine is called, the readyState and status fields of the object define why the routine was called 76. What values exists for the XmlHttpRequest.readyState field, and what do they mean readyState values: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete 77. When is it appropriate to access, or use the other fields within the XmlHttpRequest object? The most important field is the readyState field. Once a value of 4 (i.e., complete) is received, then the next most important field is status. 78. Do Ajax applications always deliver a better experience than traditional web applications? Not necessarily. Ajax gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use Ajax to enhance the user experience of our applications, not degrade it. What JavaScript libraries and frameworks are available? There are many libraries/frameworks out there (and many more emerging) that will help abstract such things as all the nasty browser differences. Three good libraries are The Dojo Toolkit, Prototype, and DWR. * The Dojo Toolkit contains APIs and widgets to support the development of rich web applications. Dojo contains an intelligent packaging system, UI effects, drag and drop APIs, widget APIs, event abstraction, client storage APIs, and AJAX interaction APIs. Dojo solves common usability issues such as support for dealing with the navigation such as the ability to detect the browser back button, the ability to support changes to the URL in the URL bar for bookmarking, and the ability to gracefully degrade when AJAX/JavaScript is not fully support on the client. Dojo is the Swiss Army Knife of JavaScript libraries. It provides the widest range of options in a single library and it does a very good job supporting new and older browsers. * Prototype focuses on AJAX interactions including a JavaScript AJAX object that contains a few objects to do basic tasks such as make a request, update a portion of a document, insert content into a document, and update a portion of a document periodically. Prototype JavaScript library contains a set of JavaScript objects for representing AJAX requests and contains utility functions for accessing in page components and DOM manipulations. Script.aculo.us and Rico are built on top of Prototype and provide UI effects, support for drag and drop, and include common JavaScript centric widgets. If you are just looking to support AJAX interactions and a few basic tasks Prototype is great. If you are looking for UI effects Rico and Script.aculo.us are good options.
60. Is the XMLHttpRequest object part of a W3C standard? No. Or not yet. It is part of the DOM Level 3 Load and Save Specification proposal. 61. What kinds of applications is Ajax best suited for? We dont know yet. Because this is a relatively new approach, our understanding of where Ajax can best be applied is still in its infancy. Sometimes the traditional web application model is the most appropriate solution to a problem. 62. Does this mean Adaptive Path is anti-Flash? Not at all. Macromedia is an Adaptive Path client, and weve long been supporters of Flash technology. As Ajax matures, we expect that sometimes Ajax will be the better solution to a particular problem, and sometimes Flash will be the better solution. Were also interested in exploring ways the technologies can be mixed (as in the case of Flickr, which uses both). 63. Where can I find examples of AJAX? While components of AJAX have been around for some time (for instance, 1999 for XMLHttpRequest), it really didn't become that popular until Google took... 64. What is the XMLHttpRequest object? It offers a non-blocking way for JavaScript to communicate back to the web server to update only part of the web page. 65. Does Ajax have significant accessibility or browser compatibility limitations? Do Ajax applications break the back button? Is Ajax compatible with REST? Are there security considerations with Ajax development? Can Ajax applications be made to work for users who have JavaScript turned off? The answer to all of these questions is maybe. Many developers are already working on ways to address these concerns. We think theres more work to be done to determine all the limitations of Ajax, and we expect the Ajax development community to uncover more issues like these along the way. 66. Is the XMLHttpRequest object part of a W3C standard? No. Or not yet. It is part of the DOM Level 3 Load and Save Specification proposal. 67. What AJAX framework do you recommend for PHP applications? SAjax, NAjax, FAjax.All of them are ok, but it it best to make your own to suit your needs. What AJAX framework do you recommend for PHP applications? Answer SAjax, NAjax, FAjax.All of them are ok, but it it best to make your own to suit your needs.
39
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. 4. How to configure the sites in Web server (IIS)? 5. Advantages in IIS 6.0? 6. 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
79. Is AJAX code cross browser compatible? Not totally. Most browsers offer a native XMLHttpRequest JavaScript object, while another one (Internet Explorer) require you to get it as an ActiveX object.... 80. How do I create a thread to do AJAX polling? JavaScript does not have threads. JavaScript functions are called when an event happens in a page such as the page is loaded, a mouse click, or a form element gains focus. You can create a timer using the setTimeout which takes a function name and time in milliseconds as arguments. You can then loop by calling the same function as can be seen in the JavaScript example below. function checkForMessage() { // start AJAX interaction with processCallback as the callback function } // callback for the request function processCallback() { // do post processing setTimeout("checkForMessage()", 10000); }
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
40
Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index. Try to create indexes on columns that have integer values rather than character values. If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key. If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns. Create surrogate integer primary key (identity for example) if your table will not have many insert operations. Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY. If your application will be performing the same query over and over on the same table, consider creating a covering index on the table. You can use the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large Tables" trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index. You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. Try to schedule it to execute during CPU idle time and slow production periods. sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"
SQL T-SQL Optimization Tips Use views and stored procedures instead of heavy-duty queries. This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see. Try to use constraints instead of triggers, whenever possible. Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible. Use table variables instead of temporary tables. Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only. Try to use UNION ALL statement instead of UNION, whenever possible. The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist. Try to avoid using the DISTINCT clause, whenever possible. Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary. Try to avoid using SQL Server cursors, whenever possible. SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub-query or derived tables, if you need to perform row-by-row operations. Try to avoid the HAVING clause, whenever possible. The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query. If you need to return the total table's row count, you can use alternative way instead of SELECT COUNT(*) statement. Because SELECT COUNT(*) statement make a full table scan to return the total table's row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So, you can improve the speed of such queries in several times. Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement. This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement. Try to restrict the queries result set by using the WHERE clause. This can results in good performance benefits, because SQL Server will return to client only particular rows, not all rows from the table(s). This can reduce network traffic and boost the overall performance of the query. Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows. This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients. Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns. This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table's columns. This can reduce network traffic and boost the overall performance of the query. 1.Indexes 2.avoid more number of triggers on the table 3.unnecessary complicated joins 4.correct use of Group by clause with the select list 5.in worst cases De normalization Index Optimization tips Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. Try to use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be increased.
QUERIES 1. 2 tables Employee Phone empid empname empid salary phnumber mgrid 2. Select all employees who doesn't have phone? SELECT empname FROM Employee WHERE (empid NOT IN (SELECT DISTINCT empid FROM phone)) 3. Select the employee names who is having more than one phone numbers. SELECT empname FROM employee WHERE (empid IN (SELECT empid FROM phone GROUP BY empid HAVING COUNT(empid) > 1)) 4. Select the details of 3 max salaried employees from employee table. SELECT TOP 3 empid, salary FROM employee ORDER BY salary DESC 5. Display all managers from the table. (manager id is same as emp id) SELECT empname FROM employee WHERE (empid IN (SELECT DISTINCT mgrid FROM employee)) 6. Write a Select statement to list the Employee Name, Manager Name under a particular manager? SELECT e1.empname AS EmpName, e2.empname AS ManagerName FROM Employee e1 INNER JOIN Employee e2 ON e1.mgrid = e2.empid ORDER BY e2.mgrid 7. 2 tables emp and phone. emp fields are - empid, name Ph fields are - empid, ph (office, mobile, home). Select all employees who doesn't have any ph nos. SELECT * FROM employee LEFT OUTER JOIN phone ON employee.empid = phone.empid WHERE (phone.office IS NULL OR phone.office = ' ') AND (phone.mobile IS NULL OR phone.mobile = ' ') AND (phone.home IS NULL OR phone.home = ' ') 8. Find employee who is living in more than one city. Two Tables: Emp City Empid Empid empName City Salary 9. SELECT empname, fname, lname FROM employee WHERE (empid IN (SELECT empid FROM city GROUP BY empid HAVING COUNT(empid) > 1))
41
22. Find top salary among two tables SELECT TOP 1 sal FROM (SELECT MAX(sal) AS sal FROM sal1 UNION SELECT MAX(sal) AS sal FROM sal2) a ORDER BY sal DESC 23. Write a query to convert all the letters in a word to upper case SELECT UPPER('test') 24. Write a query to round up the values of a number. For example even if the user enters 7.1 it should be rounded up to 8. SELECT CEILING (7.1) 25. Write a SQL Query to find first day of month? SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay
Datepart year quarter month dayofyear day week weekday hour minute second millisecond Abbreviations yy, yyyy qq, q mm, m dy, y dd, d wk, ww dw hh mi, n ss, s ms
26. Table A contains column1 which is primary key and has 2 values (1, 2) and Table B contains column1 which is primary key and has 2 values (2, 3). Write a query which returns the values that are not common for the tables and the query should return one column with 2 records. SELECT tbla.a FROM tbla, tblb WHERE tbla.a <> (SELECT tblb.a FROM tbla, tblb WHERE tbla.a = tblb.a) UNION SELECT tblb.a FROM tbla, tblb WHERE tblb.a <> (SELECT tbla.a FROM tbla, tblb WHERE tbla.a = tblb.a) OR (better approach) SELECT a FROM tbla WHERE a NOT IN (SELECT a FROM tblb) UNION ALL SELECT a FROM tblb WHERE a NOT IN (SELECT a FROM tbla) 27. There are 3 tables Titles, Authors and Title-Authors (check PUBS db). Write the query to get the author name and the number of books written by that author, the result should start from the author who has written the maximum number of books and end with the author who has written the minimum number of books. SELECT authors.au_lname, COUNT(*) AS BooksCount FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id INNER JOIN titles ON titles.title_id = titleauthor.title_id GROUP BY authors.au_lname ORDER BY BooksCount DESC 28. UPDATE emp_master SET emp_sal = CASE WHEN emp_sal > 0 AND emp_sal <= 20000 THEN (emp_sal * 1.01) WHEN emp_sal > 20000 THEN (emp_sal * 1.02) END 29. List all products with total quantity ordered, if quantity ordered is null show it as 0. SELECT name, CASE WHEN SUM(qty) IS NULL THEN 0 WHEN SUM(qty) > 0 THEN SUM(qty) END AS tot FROM [order] RIGHT OUTER JOIN product ON [order].prodid = product.prodid GROUP BY name
42
8.What is sorting and what is the difference between sorting & clustered indexes? The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table. 9. What are statistics, under what circumstances they go out of date, how do you update them? Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with nonunique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version 10.What is fillfactor? What is the use of it ? What happens when we ignore it? When you should use low fill factor? When you create a clustered index, the data in the table is stored in the data pages of the database according to the order of the values in the indexed columns. When new rows of data are inserted into the table or the values in the indexed columns are changed, Microsoft SQL Server 2000 may have to reorganize the storage of the data in the table to make room for the new row and maintain the ordered storage of the data. This also applies to nonclustered indexes. When data is added or changed, SQL Server may have to reorganize the storage of the data in the nonclustered index pages. When a new row is added to a full index page, SQL Server moves approximately half the rows to a new page to make room for the new row. This reorganization is known as a page split. Page splitting can impair performance and fragment the storage of the data in a table. When creating an index, you can specify a fill factor to leave extra gaps and reserve a percentage of free space on each leaf level page of the index to accommodate future expansion in the storage of the table's data and reduce the potential for page splits. The fill factor value is a percentage from 0 to 100 that specifies how much to fill the data pages after the index is created. A value of 100 means the pages will be full and will take the least amount of storage space. This setting should be used only when there will be no changes to the data, for example, on a read-only table. A lower value leaves more empty space on the data pages, which reduces the need to split data pages as indexes grow but requires more storage space. This setting is more appropriate when there will be changes to the data in the table. SQL DATA TYPES 1. What are the data types in SQL
bigint datetime money smalldatetime tinyint Binary Decimal Nchar Smallint Varbinary bit float ntext smallmoney Varchar char image nvarchar text uniqueidentifier cursor int real timestamp
2. Difference between char and nvarchar / char and varchar data-type? char[(n)] - Fixed-length non-Unicode character data with length of n bytes. n must be a value from 1 through 8,000. Storage size is n bytes. The SQL-92 synonym for char is character. nvarchar(n) - Variable-length Unicode character data of n characters. n must be a value from 1 through 4,000. Storage size, in bytes, is two times the number of characters entered. The data entered can be 0 characters in length. The SQL-92 synonyms for nvarchar are national char varying and national character varying. varchar[(n)] - Variable-length non-Unicode character data with length of n bytes. n must be a value from 1 through 8,000. Storage size is the actual length in bytes of the data entered, not n bytes. The data entered can be 0 characters in length. The SQL-92 synonyms for varchar are char varying or character varying. 3.GUID datasize? 128bit 4. How GUID becoming unique across machines? To ensure uniqueness across machines, the ID of the network card is used (among others) to compute the number. What is the difference between text and image data type? Text and image. Use text for character data if you need to store more than 255 characters in SQL Server 6.5, or more than 8000 in SQL Server 7.0. Use image for binary large objects (BLOBs) such as digital images. With text and image data types, the data is not stored in the row, so the limit of the page size does not apply.All that is stored in the row is a pointer to the database pages that contain the data.Individual text, ntext, and image values can be a maximum of 2-GB, which is too long to store in a single data row.
43
time. If locking is not used, data within the database may become logically incorrect, and queries executed against that data may produce unexpected results. 2. What are the different types of locks? SQL Server uses these resource lock modes.
Lock mode Description Used for operations that do not change or update data (read-only operations), such as Shared (S) a SELECT statement. Used on resources that can be updated. Prevents a common form of deadlock that Update (U) occurs when multiple sessions are reading, locking, and potentially updating resources later. Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures Exclusive (X) that multiple updates cannot be made to the same resource at the same time. Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), Intent intent exclusive (IX), and shared with intent exclusive (SIX). Used when an operation dependent on the schema of a table is executing. The types Schema of schema locks are: schema modification (Sch-M) and schema stability (Sch-S). Bulk Update Used when bulk-copying data into a table and the TABLOCK hint is specified. (BU)
3. What is a dead lock? Give a practical sample? How you can minimize the deadlock situation? What is a deadlock and what is a live lock? How will you go about resolving deadlocks? Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process. A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. (A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.) 4.What is isolation level? An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. A lower isolation level increases concurrency, but at the expense of data correctness. Conversely, a higher isolation level ensures that data is correct, but can affect concurrency negatively. The isolation level required by an application determines the locking behavior SQL Server uses. SQL-92 defines the following isolation levels, all of which are supported by SQL Server: Read uncommitted (the lowest level where transactions are isolated only enough to ensure that physically corrupt data is not read). Read committed (SQL Server default level). Repeatable read. Serializable (the highest level, where transactions are completely isolated from one another).
Isolation level Read uncommitted Read committed Repeatable read Serializable Dirty read Yes No No No Nonrepeatable read Yes Yes No No Phantom Yes Yes Yes No
5.Uncommitted Dependency (Dirty Read) - Uncommitted dependency occurs when a second transaction selects a row that is being updated by another transaction. The second transaction is reading data that has not been committed yet and may be changed by the transaction updating the row. For example, an editor is making changes to an electronic document. During the changes, a second editor takes a copy of the document that includes all the changes made so far, and distributes the document to the intended audience. Inconsistent Analysis (Nonrepeatable Read) Inconsistent analysis occurs when a second transaction accesses the same row several times and reads different data each time. Inconsistent analysis is similar to uncommitted dependency in that another transaction is changing the data that a second transaction is reading. However, in inconsistent analysis, the data read by the second transaction was committed by the transaction that made the change. Also, inconsistent analysis involves multiple reads (two or more) of the same row and each time the information is changed by another transaction; thus, the term nonrepeatable read. For example, an editor reads the same document twice, but between each reading, the writer rewrites the document. When the editor reads the document for the second time, it has changed. Phantom Reads Phantom reads occur when an insert or delete action is performed against a row that belongs to a range of rows being read by a transaction. The transaction's first read of the range of rows shows a row that no longer exists in the second or succeeding read, as a result of a deletion by a different transaction. Similarly, as the result of an insert by a different transaction, the transaction's second or succeeding read shows a row that did not exist in the original read. For example, an editor makes changes to a document submitted by a writer, but when the changes are incorporated into the master copy of the document by the production department, they find that new unedited material has been added to the document by the author. This problem could be avoided if no one could add new material to the document until the editor and production department finish working with the original document. 6. nolock? What is the difference between the REPEATABLE READ and SERIALIZE isolation levels? Locking Hints - A range of table-level locking hints can be specified using the SELECT, INSERT, UPDATE, and DELETE statements to direct Microsoft SQL Server 2000 to the
44
as a system stored procedure, the user-created stored procedure will never be executed.) c. Automatically Executing Stored Procedures - One or more stored procedures can execute automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process. The procedure(s) cannot have any input parameters. d. User stored procedure 3. How do I mark the stored procedure to automatic execution? You can use the sp_procoption system stored procedure to mark the stored procedure to automatic execution when the SQL Server will start. Only objects in the master database owned by dbo can have the startup setting changed and this option is restricted to objects that have no parameters. USE master EXEC sp_procoption 'indRebuild', 'startup', 'true') 4.How can you optimize a stored procedure? 5. How will know whether the SQL statements are executed? When used in a stored procedure, the RETURN statement can specify an integer value to return to the calling application, batch, or procedure. If no value is specified on RETURN, a stored procedure returns the value 0. The stored procedures return a value of 0 when no errors were encountered. Any nonzero value indicates an error occurred. 6. Why one should not prefix user stored procedures with sp_? It is strongly recommended that you do not create any stored procedures using sp_ as a prefix. SQL Server always looks for a stored procedure beginning with sp_ in this order: The stored procedure in the master database. The stored procedure based on any qualifiers provided (database name or owner). The stored procedure using dbo as the owner, if one is not specified. Therefore, although the user-created stored procedure prefixed with sp_ may exist in the current database, the master database is always checked first, even if the stored procedure is qualified with the database name. What can cause a Stored procedure execution plan to become invalidated and/or fall out of cache? Server restart Plan is aged out due to low use DBCC FREEPROCCACHE (sometime desired to force it) 7. When do one need to recompile stored procedure? if a new index is added from which the stored procedure might benefit, optimization does not automatically happen (until the next time the stored procedure is run after SQL Server is restarted). 8. SQL Server provides three ways to recompile a stored procedure: The sp_recompile system stored procedure forces a recompile of a stored procedure the next time it is run. Creating a stored procedure that specifies the WITH RECOMPILE option in its definition indicates that SQL Server does not cache a plan for this stored procedure; the stored procedure is recompiled each time it is executed. Use the WITH RECOMPILE option when stored procedures take parameters whose values differ widely between executions of the stored procedure, resulting in different execution plans to be created each time. Use of this option is uncommon, and causes the stored procedure to execute more slowly because the stored procedure must be recompiled each time it is executed. You can force the stored procedure to be recompiled by specifying the WITH RECOMPILE option when you execute the stored procedure. Use this option only if the parameter you are supplying is atypical or if the data has significantly changed since the stored procedure was created. 10.How to find out which stored procedure is recompiling? How to stop stored procedures from recompiling?
NOLOCK
PAGLOCK READCOMMITTED
READPAST
READUNCOMMITTED Equivalent to NOLOCK. REPEATABLEREAD ROWLOCK SERIALIZABLE TABLOCK Perform a scan with the same locking semantics as a transaction running at the REPEATABLE READ isolation level. Use row-level locks instead of the coarser-grained page- and table-level locks. Perform a scan with the same locking semantics as a transaction running at the SERIALIZABLE isolation level. Equivalent to HOLDLOCK. Use a table lock instead of the finer-grained row- or page-level locks. SQL Server holds this lock until the end of the statement. However, if you also specify HOLDLOCK, the lock is held until the end of the transaction. Use an exclusive lock on a table. This lock prevents others from reading or updating the table and is held until the end of the statement or transaction. Use update locks instead of shared locks while reading a table, and hold locks until the end of the statement or transaction. UPDLOCK has the advantage of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it. Use an exclusive lock that will be held until the end of the transaction on all data processed by the statement. This lock can be specified with either PAGLOCK or TABLOCK, in which case the exclusive lock applies to the appropriate level of granularity.
TABLOCKX UPDLOCK
XLOCK
7.For example, if the transaction isolation level is set to SERIALIZABLE, and the table-level locking hint NOLOCK is used with the SELECT statement, key-range locks typically used to maintain serializable transactions are not taken. USE pubs GO SET TRANSACTION ISOLATION LEVEL SERIALIZABLE GO BEGIN TRANSACTION SELECT au_lname FROM authors WITH (NOLOCK) GO 8.What is escalation of locks? Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server. STORED PROCEDURES 1. What is Stored procedure? A stored procedure is a set of Structured Query Language (SQL) statements that you assign a name to and store in a database in compiled form so that you can share it between a number of programs. -They allow modular programming. -They allow faster execution. -They can reduce network traffic. -They can be used as a security mechanism. 2. What are the different types of Storage Procedure? a. Temporary Stored Procedures - SQL Server supports two types of temporary procedures: local and global. A local temporary procedure is visible only to the connection that created it. A global temporary procedure is available to all connections. Local temporary procedures are automatically dropped at the end of the current session. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends. Temporary procedures named with # and ## can be created by any user. b. System stored procedures are created and stored in the master database and have the sp_ prefix.(or xp_) System stored procedures can be executed from any database without having to qualify the stored procedure name fully using the database name master. (If any user-created stored procedure has the same name
11. I have Two Stored Procedures SP1 and SP2 as given below. How the Transaction works, whether SP2 Transaction succeeds or fails? CREATE PROCEDURE SP1 AS BEGIN TRAN INSERT INTO MARKS (SID,MARK,CID) VALUES (5,6,3) EXEC SP2 ROLLBACK GO CREATE PROCEDURE SP2 AS BEGIN TRAN INSERT INTO MARKS (SID,MARK,CID) VALUES (100,100,103) commit tran GO Both will get roll backed. 12.CREATE PROCEDURE SP1 AS BEGIN TRAN INSERT INTO MARKS (SID,MARK,CID) VALUES (5,6,3) BEGIN TRAN INSERT INTO STUDENT (SID,NAME1) VALUES (1,'SA') commit tran
45
22. What is a Function & what are the different user defined functions? Function is a saved Transact-SQL routine that returns a value. User-defined functions cannot be used to perform a set of actions that modify the global database state. User-defined functions, like system functions, can be invoked from a query. They also can be executed through an EXECUTE statement like stored procedures. Scalar Functions:Functions are scalar-valued if the RETURNS clause specified one of the scalar data types Inline Table-valued Functions:If the RETURNS clause specifies TABLE with no accompanying column list, the function is an inline function. Multi-statement Table-valued Functions:If the RETURNS clause specifies a TABLE type with columns and their data types, the function is a multi-statement tablevalued function. 23. What are the difference between a function and a stored procedure? Functions can be used in a select statement where as procedures cannot Procedure takes both input and output parameters but Functions takes only input parameters Functions cannot return values of type text, ntext, image & timestamps where as procedures can Functions can be used as user defined datatypes in create table but procedures cannot ***Eg:-create table <tablename>(name varchar(10),salary getsal(name)) Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function gets executed and the return Type is returned as the result set. 24. How to debug a stored procedure?
TRIGGERS 1.What is Trigger? What is its use? What are the types of Triggers? What are the new kinds of triggers in sql 2000? Triggers are a special class of stored procedure defined to execute automatically when an UPDATE, INSERT, or DELETE statement is issued against a table or view. Triggers are powerful tools that sites can use to enforce their business rules automatically when data is modified. The CREATE TRIGGER statement can be defined with the FOR UPDATE, FOR INSERT, or FOR DELETE clauses to target a trigger to a specific class of data modification actions. When FOR UPDATE is specified, the IF UPDATE (column_name) clause can be used to target a trigger to updates affecting a particular column. You can use the FOR clause to specify when a trigger is executed: AFTER (default) - The trigger executes after the statement that triggered it completes. If the statement fails with an error, such as a constraint violation or syntax error, the trigger is not executed. AFTER triggers cannot be specified for views. INSTEAD OF -The trigger executes in place of the triggering action. INSTEAD OF triggers can be specified on both tables and views. You can define only one INSTEAD OF trigger for each triggering action (INSERT, UPDATE, and DELETE). INSTEAD OF triggers can be used to perform enhance integrity checks on the data values supplied in INSERT and UPDATE statements. INSTEAD OF triggers also let you specify actions that allow views, which would normally not support updates, to be updatable. An INSTEAD OF trigger can take actions such as: Ignoring parts of a batch. Not processing a part of a batch and logging the problem rows. Taking an alternative action if an error condition is encountered. In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder. Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. 2. When should one use "instead of Trigger"? Example CREATE TABLE BaseTable ( PrimaryKey int IDENTITY(1,1), Color nvarchar(10) NOT NULL, Material nvarchar(10) NOT NULL, ComputedCol AS (Color + Material) ) GO --Create a view that contains all columns from the base table. CREATE VIEW InsteadView AS SELECT PrimaryKey, Color, Material, ComputedCol FROM BaseTable GO --Create an INSTEAD OF INSERT trigger on tthe view. CREATE TRIGGER InsteadTrigger on InsteadView INSTEAD OF INSERT AS BEGIN
46
modifications to maintain all data integrity. All internal data structures, such as B-tree indexes or doubly-linked lists, must be correct at the end of the transaction. Isolation - Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either sees data in the state it was in before another concurrent transaction modified it, or it sees the data after the second transaction has completed, but it does not see an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed. Durability - After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure. 2. After one Begin Transaction a truncate statement and a RollBack statements are there. Will it be rollbacked? Since the truncate statement does not perform logged operation how does it RollBack? It will rollback. ** Given a SQL like Begin Tran Select @@Rowcount Begin Tran Select @@Rowcount Begin Tran Select @@Rowcount Commit Tran Select @@Rowcount RollBack Select @@Rowcount RollBack Select @@Rowcount 3. What is the value of @@Rowcount at each stmt levels? Ans : 0 zero. @@ROWCOUNT - Returns the number of rows affected by the last statement. @@TRANCOUNT - Returns the number of active transactions for the current connection. Each Begin Tran will add count, each commit will reduce count and ONE rollback will make it 0.
2. Does the View occupy memory space? No 3. Can u drop a table if it has a view? Views or tables participating in a view created with the SCHEMABINDING clause cannot be dropped. If the view is not created using SCHEMABINDING, then we can drop the table. 4. Why doesn't SQL Server permit an ORDER BY clause in the definition of a view? SQL Server excludes an ORDER BY clause from a view to comply with the ANSI SQL-92 standard. Because analyzing the rationale for this standard requires a discussion of the underlying structure of the structured query language (SQL) and the mathematics upon which it is based, we can't fully explain the restriction here. However, if you need to be able to specify an ORDER BY clause in a view, consider using the following workaround: USE pubs GO CREATE VIEW AuthorsByName AS SELECT TOP 100 PERCENT * FROM authors ORDER BY au_lname, au_fname GO The TOP construct, which Microsoft introduced in SQL Server 7.0, is most useful when you combine it with the ORDER BY clause. The only time that SQL Server supports an ORDER BY clause in a view is when it is used in conjunction with the TOP keyword. (Note that the TOP keyword is a SQL Server extension to the ANSI SQL-92 standard.) TRANSACTIONS AND OTHERS 1.What is Transaction? A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction: Atomicity - A transaction must be an atomic unit of work; either all of its data modifications are performed or none of them is performed. Consistency - When completed, a transaction must leave all data in a consistent state. In a relational database, all rules must be applied to the transaction's
OTHER 4. What are the constraints for Table Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity. SQL Server 2000 supports five classes of constraints. NOT NULL CHECK UNIQUE PRIMARY KEY FOREIGN KEY 5. There are 50 columns in a table. Write a query to get first 25 columns Ans: Need to mention each column names. 6. How to list all the tables in a particular database? USE pubs GO sp_help 7. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors? Cursors allow row-by-row processing of the result sets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors. How to avoid cursor: Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 -- 5000 hike Salary between 40000 and 55000 -- 7000 hike Salary between 55000 and 65000 -- 9000 hike In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below: UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.
47
8. What is Dynamic Cursor? Suppose, I have a dynamic cursor attached to table in a database. I have another means by which I will modify the table. What do you think will the values in the cursor be? Dynamic cursors reflect all changes made to the rows in their result set when scrolling through the cursor. The data values, order, and membership of the rows in the result set can change on each fetch. All UPDATE, INSERT, and DELETE statements made by all users are visible through the cursor. Updates are visible immediately if they are made through the cursor using either an API function such as SQLSetPos or the Transact-SQL WHERE CURRENT OF clause. Updates made outside the cursor are not visible until they are committed, unless the cursor transaction isolation level is set to read uncommitted. 9. What is DATEPART? Returns an integer representing the specified datepart of the specified date. 10. Difference between Delete and Truncate? TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. (1) But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log. (2) Because TRUNCATE TABLE is not logged, it cannot activate a trigger. (3) The counter used by an identity for new rows is reset to the seed for the column. If you want to etain the identity counter, use DELETE instead. Of course, TRUNCATE TABLE can be rolled back. 11.Given a scenario where two operations, Delete Stmt and Truncate Stmt, where the Delete Statement was successful and the truncate stmt was failed. Can u judge why? **
21. What is the use of trace utility? ** 22. What is the use of shell commands? xp_cmdshell Executes a given command string as an operating-system command shell and returns any output as rows of text. Grants nonadministrative users permissions to execute xp_cmdshell. 23. What is use of shrink database? Microsoft SQL Server 2000 allows each file within a database to be shrunk to remove unused pages. Both data and transaction log files can be shrunk. 24. If the performance of the query suddenly decreased where you will check?
25.What is a pass-through query? Microsoft SQL Server 2000 sends pass-through queries as un-interpreted query strings to an OLE DB data source. The query must be in a syntax the OLE DB data source will accept. A Transact-SQL statement uses the results from a pass-through query as though it is a regular table reference. This example uses a pass-through query to retrieve a result set from a Microsoft Access version of the Northwind sample database. SELECT * FROM OpenRowset('Microsoft.Jet.OLEDB.4.0', 'c:\northwind.mdb';'admin'; '', 'SELECT CustomerID, CompanyName FROM Customers WHERE Region = ''WA'' ') 26. How do you differentiate Local and Global Temporary table? You can create local and global temporary tables. Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions. Prefix local temporary table names with single number sign (#table_name), and prefix global temporary table names with a double number sign (##table_name). SQL statements reference the temporary table using the value specified for table_name in the CREATE TABLE statement: CREATE TABLE #MyTempTable (cola INT PRIMARY KEY) INSERT INTO #MyTempTable VALUES (1) 27.How the Exists keyword works in SQL Server? USE pubs SELECT au_lname, au_fname FROM authors WHERE exists (SELECT * FROM publishers WHERE authors.city = publishers.city) When a subquery is introduced with the keyword EXISTS, it functions as an existence test. The WHERE clause of the outer query tests for the existence of rows returned by the subquery. The subquery does not actually produce any data; it returns a value of TRUE or FALSE. 28. ANY? USE pubs SELECT au_lname, au_fname FROM authors WHERE city = ANY (SELECT city FROM publishers) 29. to select date part only SELECT CONVERT(char(10),GetDate(),101) --to select time part only SELECT right(GetDate(),7) 30. How can I send a message to user from the SQL Server? You can use the xp_cmdshell extended stored procedure to run net send command. This is the example to send the 'Hello' message to JOHN: EXEC master..xp_cmdshell "net send JOHN 'Hello'" To get net send message on the Windows 9x machines, you should run the WinPopup utility. You can place WinPopup in the Startup group under Program Files. 31. What is normalization? Explain different levels of normalization? Explain Third normalization form with an example? The process of refining tables, keys, columns, and relationships to create an efficient database is called normalization. This should eliminates unnecessary duplication and provides a rapid search path to all necessary information. Some of the benefits of normalization are: Data integrity (because there is no redundant, neglected data) Optimized queries (because normalized tables produce rapid, efficient joins) Faster index creation and sorting (because the tables have fewer columns) Faster UPDATE performance (because there are fewer indexes per table) Improved concurrency resolution (because table locks will affect less data) Eliminate redundancy There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third normal
12. What are global variables? Tell me some of them? Transact-SQL global variables are a form of function and are now referred to as functions. ABS - Returns the absolute, positive value of the given numeric expression. SUM AVG AND 13. What is DDL? Data definition language (DDL) statements are SQL statements that support the definition or declaration of database objects (for example, CREATE TABLE, DROP TABLE, and ALTER TABLE). You can use the ADO Command object to issue DDL statements. To differentiate DDL statements from a table or stored procedure name, set the CommandType property of the Command object to adCmdText. Because executing DDL queries with this method does not generate any recordsets, there is no need for a Recordset object. 14. What is DML? Data Manipulation Language (DML), which is used to select, insert, update, and delete data in the objects defined using DDL 15. What are keys in RDBMS? What is a primary key/ foreign key? There are two kinds of keys. A primary key is a set of columns from a table that are guaranteed to have unique values for each row of that table. Foreign keys are attributes of one table that have matching values in a primary key in another table, allowing for relationships between tables. 16. What is the difference between Primary Key and Unique Key? Both primary key and unique key enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. 17. Define candidate key, alternate key, composite key? A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key. 18. What is the Referential Integrity? Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value. 19. What are defaults? Is there a column to which a default can't be bound? A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.
48
d) 4th Normal Form (4NF) A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies. This applies primarily to key-only associative tables, and appears as a ternary relationship, but has incorrectly merged 2 distinct, independent relationships. Eg: This could be any 2 M:M relationships from a single entity. For instance, a member could know many software tools, and a software tool may be used by many members. Also, a member could have recommended many books, and a book could be recommended by many members.
Software member Book
Eliminate duplicative columns from the same table. Clearly, the Subordinate1Subordinate4 columns are duplicative. What happens when we need to add or remove a subordinate?
Bob Mary Jim Subordinates Jim, Mary, Beth Mike, Jason, Carol, Mark Alan
e) The correct solution, to cause the model to be in 4th normal form, is to ensure that all M:M relationships are resolved independently if they are indeed independent.
Software membersoftware member memberBook book
This solution is closer, but it also falls short of the mark. The subordinates column is still duplicative and non-atomic. What happens when we need to add or remove a subordinate? We need to read and write the entire contents of the table. Thats not a big deal in this situation, but what if one manager had one hundred employees? Also, it complicates the process of selecting data from the database in future queries. Solution:
Subordinate Jim Mary Beth Mike Jason Carol Mark Alan
f) 5th Normal Form (5NF)(PJNF) A table is in 5NF, also called "Projection-Join Normal Form", if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table. g) Domain/key normal form (DKNF). A key uniquely identifies each row in a table. A domain is the set of permissible values for an attribute. By enforcing key and domain restrictions, the database is assured of being freed from modification anomalies. DKNF is the normalization level that most designers aim to achieve. ** Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database. 32. If a database is normalized by 3 NF then how many number of tables it should contain in minimum? How many minimum if 2NF and 1 NF? 33.What is denormalization and when would you go for it? As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced. 34. How can I randomly sort query results? To randomly order rows, or to return x number of randomly chosen rows, you can use the RAND function inside the SELECT statement. But the RAND function is resolved only once for the entire query, so every row will get same value. You can use an ORDER BY clause to sort the rows by the result from the NEWID function, as the following code shows: SELECT * FROM Northwind..Orders ORDER BY NEWID() 35. sp_who Provides information about current Microsoft SQL Server users and processes. The information returned can be filtered to return only those processes that are not idle. 36. Have you worked on Dynamic SQL? How will You handled (Double Quotes) in Dynamic SQL? 37.How to find dependents of a table? Verify dependencies with sp_depends before dropping an object 38. What is the difference between a CONSTRAINT AND RULE? Rules are a backward-compatibility feature that perform some of the same functions as CHECK constraints. CHECK constraints are the preferred, standard way to restrict the values in a column. CHECK constraints are also more concise than rules; there can only be one rule applied to a column, but multiple CHECK constraints can be applied. CHECK constraints are specified as part of the CREATE TABLE statement, while rules are created as separate objects and then bound to the column. 39.How to call a COM dll from SQL Server 2000? sp_OACreate - Creates an instance of the OLE object on an instance of Microsoft SQL Server Syntax sp_OACreate progid, | clsid, objecttoken OUTPUT [ , context ] context - Specifies the execution context in which the newly created OLE object runs. If specified, this value must be one of the following: 1 = In-process (.dll) OLE server only 4 = Local (.exe) OLE server only 5 = Both in-process and local OLE server allowed Examples A. Use Prog ID - This example creates a SQL-DMO SQLServer object by using its ProgID. DECLARE @object int DECLARE @hr int DECLARE @src varchar(255), @desc varchar(255) EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT IF @hr <> 0 BEGIN EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT SELECT hr=convert(varbinary(4),@hr), Source=@src, Description=@desc
a) Second Normal Form (2NF) * Create separate tables for sets of values that apply to multiple records. * Relate these tables with a foreign key. Records should not depend on anything other than a table's primary key (a compound key, if necessary). For example, consider a customer's address in an accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of storing the customer's address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table. b) Third Normal Form (3NF) * Eliminate fields that do not depend on the key. Values in a record that are not part of that record's key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table. For example, in an Employee Recruitment table, a candidate's university name and address may be included. But you need a complete list of universities for group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate Universities table and link it to the Candidates table with a university code key. Another Example :
MemberId 1 2 Name John Smith Dave Jones Company ABC MCI CompanyLoc Alabama Florida
The Member table satisfies first normal form - it contains no repeating groups. It satisfies second normal form - since it doesn't have a multivalued key. But the key is MemberID, and the company name and location describe only a company, not a member. To achieve third normal form, they must be moved into a separate table. Since they describe a company, CompanyCode becomes the key of the new "Company" table. The motivation for this is the same for second normal form: we want to avoid update and delete anomalies. For example, suppose no members from the IBM were currently stored in the database. With the previous design, there would be no record of its existence, even though 20 past members were from IBM! Member Table
MemberId 1 2 Name John Smith Dave Jones CID 1 2
Company Table
CId 1 2 Name ABC MCI Location Alabama Florida
c) Boyce-Codd Normal Form (BCNF) A relation is in Boyce/Codd normal form if and only if the only determinants are candidate key. Its a different version of 3NF, indeed, was meant to replace it. [A determinant is any attribute on which some other attribute is (fully) functionally dependent.]
49
53. What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. 54. What are the properties of the Relational tables? Relational tables have six properties: Values are atomic. Column values are of the same kind. Each row is unique. The sequence of columns is insignificant. The sequence of rows is insignificant. Each column must have a unique name. 55.What is De-normalization? De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. 56.What is a Linked Server? Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Stored Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server. 57. What is Collation? Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case sensitivity, accent marks, kana character types and character width. ( 58. What is sub-query? Explain properties of sub- query? Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword. A subquery is a SELECT statement that is nested within another T- SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a resultset. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used. 59.What is User Defined Functions? What kind of User-Defined Functions can be created? User-Defined Functions allow defining its own T-SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type. Different Kinds of User-Defined Functions created are: Scalar User-Defined Function A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. Inline Table-Value User-Defined Function An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user- defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, nonupdateable view of the underlying tables. Multi-statement Table- Value User-Defined Function A Multi-Statement Table- Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL select command or a group of them gives us the capability to in essence create a parameterized, nonupdateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.
44. What is the system function to get the current user's user id? USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME(). 45.What are the series of steps that happen on execution of a query in a Query Analyzer? 1) Syntax checking 2) Parsing 3) Execution plan 46. Which event (Check constraints, Foreign Key, Rule, trigger, Primary key check) will be performed last for integrity check? Identity Insert Check Nullability constraint Data type check Instead of trigger Primary key Check constraint Foreign key DML Execution (update statements) After Trigger ** 47. How will you show many to many relation in sql? Create 3rd table with 2 columns which having one to many relation to these tables. 48. When a query is sent to the database and an index is not being used, what type of execution is taking place? A table scan. 49. What is #, ##, @, @@ means? @@ - System variables @ - user defined variables 50. What is the difference between a Local temporary table and a Global temporary table? How is each one denoted? Local temporary table will be accessible to only current user session, its name will be preceded with a single hash (#mytable) Global temporary table will be accessible to all users, & it will be dropped only after ending of all active connections, its name will be preceded with double hash (##mytable) 51.What is covered queries in SQL Server? 52. What is HASH JOIN, MERGE JOIN?
50
70.Which command using Query Analyzer will give you the version of SQL server and operating system? SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition'). 71. What is SQL Server Agent? SQL Server agent plays an important role in the day- to- day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts. 72. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible? Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels. 73. What is Log Shipping? Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval. 74. Name 3 ways to get an accurate count of the number of records in a table? SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2 74. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF? When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers. 75. What is the difference between a Local and a Global temporary table? temporary table exists only for the duration of a connection or, if defined inside a A local compound statement, for the duration of the compound statement. A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time. 76. What is the STUFF function and how does it differ from the REPLACE function? STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string. 77. What is CHECK Constraint? A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity 78. What is NOT NULL Constraint? A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. 79. How to get @@ERROR and @@ROWCOUNT at the same time? If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the error- checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR 80. What is a Scheduled Jobs or What is a Scheduled Tasks? Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during
51
that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop- down menu). If this option is turned on it will display query execution plan in separate window when query is ran again. SQL SERVER 2008 1. What are the basic functions for master, msdb, model, tempdb and resource databases? The master database holds information for all databases located on the SQL Server instance and is theglue that holds the engine together. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care.database The msdb stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping. The tempdb holds temporary objects such as global and local temporary tables and stored procedures. is essentially a template database used in the creation of any new user database The model created in the instance. The resource Database is a read- only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata. 2. What is Service Broker? Service Broker is a message- queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable. 3. Where SQL server user names and passwords are stored in SQL server? They get stored in System Catalog Views sys.server_principals and sys.sql_logins. 4. What is Policy Management? Policy Management in SQL SERVER 2008 allows you to define and nforce policies for configuring and managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes. 5. What is Replication and Database Mirroring? Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients which are known as the principal database. Updates made by clients to the principal database are applied on the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database. 6. What are Sparse Columns? A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values. 7. What does TOP Operator Do? The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETES statements. 8. What is CTE? CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in hat it is not stored as an object and lasts only for the duration of the query. 9. What is MERGE Statement? MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once.
86. How to implement one-to-one, one-to-many and many-to- many relationships while designing tables? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One- to- Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. 87. What is an execution plan? When would you use it? How would you view the execution plan? An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one
52
nodes called a node set. XPath can use both an unabbreviated and an abbreviated syntax. The following is the unabbreviated syntax for a location path: /axisName::nodeTest[predicate]/axisName::nodeTest[predicate] 19. What is NOLOCK? Using the NOLOCK query optimizer hint is generally considered good practice in order to improve concurrency on a busy system.When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. Ther e are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will ait for the updates to complete. The result to your system is delay (blocking). 20. How would you handle error in SQL SERVER 2008? SQL Server now supports the use of TRY...CATCH constructs for providing rich error handling. TRY...CATCH lets us build error handling at the level we need, in the way we need to, by setting a region where if any error occurs, it will break out of the region and head to an error handler. The basic structure is as follows: BEGIN TRY <code> END TRY BEGIN CATCH <code> END CATCH So i any error occurs in the TRY block, execution is diverted to the CATCH block, and the error can be dealt. 21. What is RAISEERROR? error message and initiates error processing for the session. RaiseError generates an RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRYCATCH construct. 22. How to rebuild Master Databse? Master database is system database and it contains information about running servers configuration. When SQL Server 2005 is installed it usually creates master, model, msdb, tempdb resource and distribution system database by default. Only Master database is the one which is absolutely must have database. Without Master database SQL Server cannot be started. This is the reason it is extremely important to backup Master database. To rebuild the Master database, Run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server. 23. What is XML Datatype? data type lets you store XML documents and fragments in a SQL Server database.An XML fragment is an XML instance that is missing a single top-level element. You can type and store XML instances in them. The create columns and variables of the xml data type and associated methods help integrate XML into the relational framework of SQL Server. 24. What is Data Compression? In SQL SERVE 2008 Data Compression comes in two flavors: Row Compression Page Compression Row Compression: changes the format of physical storage of data. It minimize the metadata (column information, length, offsets etc) associated with each record. Numeric data types and fixed length strings are stored in variable-length storage format, just like Varchar. Page Compression: Page compression allows common data to be shared between rows for a given page. Its uses the following techniques to compress data: Row compression. Prefix Compression. For every column in a page duplicate prefixes are identified. These prefixes are saved in compression information headers (CI) which resides after page header. A reference number is assigned to the se prefixes and that reference number is replaced where ever those prefixes are being used. Dictionary Compression. Dictionary compression searches for duplicate values throughout the page and stores them in CI. The main difference between prefix and dictionary compression is that prefix is only restricted to one column while dictionary is applicable to the complete page. 25. What is use of DBCC Commands? The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for SQL Server. DBCC commands are used to perform following tasks. Maintenance tasks on database, index, or filegroup. Tasks that gather and display various types of information.
53
37. What are Ranking Functions? Ranking functions return a rank ing value for each row in a partition. All the ranking functions are non-deterministic. Different Ranking functions are: ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>) Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition. RANK () OVER ([<partition_by_clause>] <order_by_clause>) Returns the rank of each row within the partition of a result set. DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>) Returns the rank of rows within the partition of a result set, without any gaps in the ranking. 38. What is the difference between UNION and UNION ALL? UNION: The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected. UNION ALL:The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table. 39. What is B-Tree? The database server uses a B- tree structure to organize index information. B-Tree generally has following types of index pages or nodes: root node: A root node contains node pointers to branch nodes which can be only one. branch nodes: A branch node contains pointers to leaf nodes or other branch nodes which can be two or more. A leaf node contains in leaf nodes index items and horizontal pointers to other leaf nodes which can be many. TOOLS 1.Have you ever used DBCC command? Give an example for it. The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for Microsoft SQL Serve 2000. These statements check the physical and logical consistency of a database. Many DBCC statements can fix detected problems. Database Console Command statements are grouped into these categories.
Statement category Maintenance statements Miscellaneous statements Perform Maintenance tasks on a database, index, or filegroup. Miscellaneous tasks such as enabling row-level locking or removing a dynamiclink library (DLL) from memory.
Status statements Status checks. Validation statements Validation operations on a database, table, index, catalog, filegroup, system tables, or allocation of database pages.
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc.
2. How do you use DBCC statements to monitor various aspects of a SQL server installation? ** 3. What is the output of DBCC Showcontig statement? Displays fragmentation information for the data and indexes of the specified table. 4.How do I reset the identity column? You can use the DBCC CHECKIDENT statement, if you want to reset or reseed the identity column. For example, if you need to force the current identity value in the jobs table to a value of 100, you can use the following: USE pubs GO DBCC CHECKIDENT (jobs, RESEED, 100) GO 5. About SQL Command line executables
Utilities bcp console isql sqlagent sqldiag sqlmaint sqlservr vswitch dtsrun dtswiz isqlw itwiz odbccmpt osql rebuildm sqlftwiz
54
6. What is DTC? The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction manager that allows client applications to include several different sources of data in one transaction. MS DTC coordinates committing the distributed transaction across all the servers enlisted in the transaction. 7. What is DTS? Any drawbacks in using DTS? Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets you extract, transform, and consolidate data from disparate sources into single or multiple destinations. 8. What is BCP? The bcp utility copies data between an instance of Microsoft SQL Server 2000 and a data file in a user-specified format. C:\Documents and Settings\sthomas>bcp usage: bcp {dbtable | query} {in | out | queryout | format} datafile [-m maxerrors] [-f formatfile] [-e errfile] [-F firstrow] [-L lastrow] [-b batchsize] [-n native type] [-c character type] [-w wide character type] [-N keep non-text native] [-V file format version] [-q quoted identifier] [-C code page specifier] [-t field terminator] [-r row terminator] [-i inputfile] [-o outfile] [-a packetsize] [-S server name] [-U username] [-P password] [-T trusted connection] [-v version] [-R regional enable] [-k keep null values] [-E keep identity values] [-h "load hints"] 9. How can I create a plain-text flat file from SQL Server as input to another application? One of the purposes of Extensible Markup Language (XML) is to solve challenges like this, but until all applications become XML-enabled, consider using our faithful standby, the bulk copy program (bcp) utility. This utility can do more than just dump a table; bcp also can take its input from a view instead of from a table. After you specify a view as the input source, you can limit the output to a subset of columns or to a subset of rows by selecting appropriate filtering (WHERE and HAVING) clauses. More important, by using a view, you can export data from multiple joined tables. The only thing you cannot do is specify the sequence in which the rows are written to the flat file, because a view does not let you include an ORDER BY clause in it unless you also use the TOP keyword. If you want to generate the data in a particular sequence or if you cannot predict the content of the data you want to export, be aware that in addition to a view, bcp also supports using an actual query. The only "gotcha" about using a query instead of a table or view is that you must specify queryout in place of out in the bcp command line. For example, you can use bcp to generate from the pubs database a list of authors who reside in California by writing the following code: bcp "SELECT * FROM pubs..authors WHERE state = 'CA'" queryout c:\CAauthors.txt -c -T -S 10. What are the different ways of moving data/databases between servers and databases in SQL Server? There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data. 11. How will I export database? Through DTS - Import/Export wizard Backup - through Complete/Differential/Transaction Log 12. How to export database at a particular time, every week? Backup Schedule DTS Schedule Jobs - create a new job 13. How do you load large data to the SQL server database? bcp 14. How do you transfer data from text file to database (other than DTS)? bcp 15. What is OSQL and ISQL utility? The osql utility allows you to enter Transact-SQL statements, system procedures, and script files. This utility uses ODBC to communicate with the server. The isql utility allows you to enter Transact-SQL statements, system procedures, and script files; and uses DB-Library to communicate with Microsoft SQL Server 2000. All DB-Library applications, such as isql, work as SQL Server 6.5level clients when connected to SQL Server 2000. They do not support some SQL Server 2000 features. The osql utility is based on ODBC and does support all SQL Server 2000 features. Use osql to run scripts that isql cannot run.
16. What Tool you have used for checking Query Optimization? What is the use of profiler in sql server? What is the first thing u look at in a SQL Profiler? SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures is hampering performance by executing too slowly. Use SQL Profiler to: Monitor the performance of an instance of SQL Server. Debug Transact-SQL statements and stored procedures. Identify slow-executing queries. Test SQL statements and stored procedures in the development phase of a project by single-stepping through statements to confirm that the code works as expected. Troubleshoot problems in SQL Server by capturing events on a production system and replaying them on a test system. This is useful for testing or debugging purposes and allows users to continue using the production system without interference. Audit and review activity that occurred on an instance of SQL Server. This allows a security administrator to review any of the auditing events, including the success and failure of a login attempt and the success and failure of permissions in accessing statements and objects. Permissions 1. A user is a member of Public role and Sales role. Public role has the permission to select on all the table, and Sales role, which doesnt have a select permission on some of the tables. Will that user be able to select from all tables? ** 2. If a user does not have permission on a table, but he has permission to a view created on it, will he be able to view the data in table? Yes. 3. Describe Application Role and explain a scenario when you will use it? ** 4. After removing a table from database, what other related objects have to be dropped explicitly? (view, SP) 5. You have a SP names YourSP and have the a Select Stmt inside the SP. You also have a user named YourUser. What permissions you will give him for accessing the SP. ** 6. Different Authentication modes in Sql server? If a user is logged under windows authentication mode, how to find his userid? There are Three Different authentication modes in sqlserver. 1.Windows Authentication Mode 2.SqlServer Authentication Mode 3.Mixed Authentication Mode system_user system function in sqlserver to fetch the logged on user name. 7. Give the connection strings from front-end for both type logins(windows,sqlserver)? This are specifically for sqlserver not for any other RDBMS Data Source=MySQLServer;Initial Catalog=NORTHWIND;Integrated Security=SSPI (windows) Data Source=MySQLServer;Initial Catalog=NORTHWIND;Uid= ;Pwd= (sqlserver) 8. What are three SQL keywords used to change or set someones permissions? Grant, Deny and Revoke ADMIN 1.Explain the architecture of SQL Server? SQL Server was originally developed by Sybase in the mid-1980s and licensed to Microsoft until 1997. Even today, most of the core technology in SQL Server is the same as Sybase Adaptive Server Enterprise. Architecturally, Sybase and Microsoft are very similar, and both use the Transact-SQL dialect of SQL that is copyrighted by Sybase. To this day, Sybase receives a royalty for every copy of SQL Server sold. Key architecture points: 1. Multi-threaded, scales to multiple processors 2. Main databases are master, model, tempdb 3. Each database has at least one data segment and one log segment 4. Transaction log is used for rollback and recovery 2. Different types of Backups? -A full database backup is a full copy of the database. -A transaction log backup copies only the transaction log. -A differential backup copies only the database pages modified after the last full database backup. -A file or filegroup restore allows the recovery of just the portion of a database that was on the failed disk. 3. What are jobs in SQL Server? How do we create one? What is tasks? Using SQL Server Agent jobs, you can automate administrative tasks and run them on a recurring basis.
55
Use Arabic for all variations of Arabic, which use the Arabic character set (code page 1256). Use Japanese_Unicode for the Unicode version of Japanese (code page 932), which has a different sort order from Japanese, but the same code page (932). 10. What is the STUFF Function and how does it differ from the REPLACE function? STUFF - Deletes a specified length of characters and inserts another set of characters at a specified starting point. SELECT STUFF('abcdef', 2, 3, 'ijklmn') GO Here is the result set: --------aijklmnef REPLACE - Replaces all occurrences of the second given string expression in the first string expression with a third expression. SELECT REPLACE('abcdefghicde','cde','xxx') GO Here is the result set: -----------abxxxfghixxx 11. What does it mean to have quoted_identifier on? What are the implications of having it off? When SET QUOTED_IDENTIFIER is OFF (default), literal strings in expressions can be delimited by single or double quotation marks. When SET QUOTED_IDENTIFIER is ON, all strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers. SET QUOTED_IDENTIFIER must be ON when creating or manipulating indexes on computed columns or indexed views. If SET QUOTED_IDENTIFIER is OFF, CREATE, UPDATE, INSERT, and DELETE statements on tables with indexes on computed columns or indexed views will fail. The SQL Server ODBC driver and Microsoft OLE DB Provider for SQL Server automatically set QUOTED_IDENTIFIER to ON when connecting. When a stored procedure is created, the SET QUOTED_IDENTIFIER and SET ANSI_NULLS settings are captured and used for subsequent invocations of that stored procedure. When executed inside a stored procedure, the setting of SET QUOTED_IDENTIFIER is not changed. SET QUOTED_IDENTIFIER OFF GO -- Attempt to create a table with a reserved keyword as a name -- should fail. CREATE TABLE "select" ("identity" int IDENTITY, "order" int) GO SET QUOTED_IDENTIFIER ON GO -- Will succeed. CREATE TABLE "select" ("identity" int IDENTITY, "order" int) GO 12. What is the purpose of UPDATE STATISTICS? Updates information about the distribution of key values for one or more statistics groups (collections) in the specified table or indexed view. 13.Fundamentals of Data warehousing & olap? 14.What do u mean by OLAP server? What is the difference between OLAP and OLTP? What is a tuple? A tuple is an instance of data within a relational database. Services and user Accounts maintenance 1. sp_configure commands? Displays or changes global configuration settings for the current server. 2. What is the basic functions for master, msdb, tempdb databases? Microsoft SQL Server 2000 systems have four system databases: master - The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. master is the database that records the existence of all other databases, including the location of the database files. tempdb - tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database. By default, tempdb autogrows as needed while SQL Server is running. If the size defined for tempdb is small, part of your system processing load may be taken up with autogrowing tempdb to the size needed to support your workload each time to restart SQL Server. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb. model - The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of
Windows collation options: Use Latin1_General for the U.S. English character set (code page 1252). Use Modern_Spanish for all variations of Spanish, which also use the same character set as U.S. English (code page 1252).
56
also provides a way to offload query processing from the main computer (the source server) to read-only destination servers. 8. What are the main steps you take care for enhancing SQL Server performance? ** 9. You have to check whether any users are connected to sql server database and if any user is connected to database, you have to disconnect the user(s) and run a process in a job. How do you do the above in a job? ** 9. How can I convert data in a Microsoft Access table into XML format? The following applications can help you convert Access data into XML format: Access 2002, ADO 2.5, and SQLXML. Access 2002 (part of Microsoft Office XP) enables you to query or save a table in XML format. You might be able to automate this process. ADO 2.5 and later enables you to open the data into a recordset, then persist the recordset in XML format, as the following code shows: rs.Save "c:\rs.xml", adPersistXML You can use linked servers to add the Access database to your SQL Server 2000 database so you can run queries from within SQL Server to retrieve data. Then, through HTTP, you can use the SQLXML technology to extract the Access data in the XML format you want. 10.@@IDENTITY ? Ans: Returns the last-inserted identity value. 11. If a job is fail in sql server, how do find what went wrong? Have you used Error handling in DTS?