Вы находитесь на странице: 1из 16

DataList or Repeater

<asp:DataList ID="DataList1" runat="server"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem,"surname")%> </ItemTemplate>

SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].Conn ectionString); SqlCommand comm = new SqlCommand("select * from patient", conn); SqlDataAdapter da = new SqlDataAdapter(comm); DataSet ds = new DataSet(); da.Fill(ds); DataList1.DataSource = ds; DataList1.DataBind(); Explain the steps to deploy a web application a. Add a websetup project to the application solution. b. Customize it to make UI changes, registry entries, installation path etc information c. You can alternatively, publish the website by right clicking on the application project and create a virtual directory of it in IIS. What is Role-based security? Application that provide access to its data based on credentials check, verify the users role and hands over the access on the basis of such roles. Managed code finds out the role of a principal through a Principal object. This further contains a reference to an Identity object. User accounts -> represent people Group accounts -> represent certain categories of users and the rights they own. In .NET Framework:- Identity objects represent users, Roles represent memberships and security. A security principal represents a user and their roles which tells about their authority in the application. Role-based security is mostly used in custom authentication. Way to set the default policy to the application is: AppDomain appDomain = AppDomain.CreateDomain("test"); appDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

Define Assembly. An Assembly is a collection, either an executable (.exe) or a dynamic link library (.dll), that forms a logical unit of functionality and built to efficiently work together. .NET Framework can be used to compile assemblies. What does an assembly contain? An assembly contains following information: Assembly manifest: Information about the assembly. Type metadata: Information about the types. IL Code Resource files. An assembly manifest contains the following information: Identity of the assembly Types and resources Files Security permissions Define private assembly and a shared assembly. A private assembly is stored in the applications directory and used by a single application. A share assembly can be used by multiple applications and is stored in the Global assembly cache, a repository of assemblies maintained by the .Net Framework. Explain the steps to create a .NET Assembly. Add a project from templates called Class Library Optionally in property pages of this project set the output type to Class Library.. Explain the steps to add assemblies to the Global Assembly Cache. a. sn -k StrongNameFile.snk creates a strong key b. [assembly:AssemblyKeyFile("StrongNameFile.snk")] tag the assembly wid he string key. c. gacutil /i AssemblyName.dll install the assembly to GAC. What are Strong Named Assemblies? Explain steps to create them. They are the assemblies which can be uniquely identified by attaching the strong name to the dll name. It gives a unique name to each assembly of various versions. This allows solving the DLL hell problem. sn -k StrongNameFile.snk creates a strong key b. [assembly:AssemblyKeyFile("StrongNameFile.snk")] tag the assembly wid he string key

What is Authentication in ASP.NET? Authentication is the process of verifying users details and find if the user is a valid user to the system or not. This process of authentication is needed to provide authority to the user. ASP.NET implements authentication through authentication providers. What is Authorization in ASP.NET? Authorization is a process that takes place based on the authentication of the user. Once authenticated, based on users credentials, it is determined what rights des a user have. In ASP.NET, there are two ways to authorize access to a given resource: a. File authorization b. URL authorization Explain the methods of windows-based authentication Anonymous authentication gives access to read-only areas of the Web site which do not need any username and password. Basic Authentication It is done through IIS. This is based on the windows user accounts. When using Basic authentication, the browser lets the user to enter the username and password. Digest authentication allows sending hash or digesting over the network rather than the plain text as in the case of basic authentication. Integrated Windows authentication- It is based on users having Windows domain accounts. This type of authentication prevents from pasing the password across the network. It is considered to be the best authentication system over intranet. Explain collection in .NET and describe how to enumerate through the members of a collection. There are various collection types in .NET which are used for manipulation of data. Collections are available in System.Collections namespace IEnumerator is the base interface for all enumerators. Enumerators can only read the data from the data collections but not modify them. Reset and MoveNext are the methods used with enumerators which bring it back to the first position and move it to the next element position respectively. Current returns the current object. What are the ways of handling exceptions in ASP.NET? There are three ways to handle exceptions in ASP.NET Try/catch/finally block. Using Events like Page_Error and Application_Error Using Custom error page

Why is exception handling important for an application? Exception handling is used to prevent application from being stuck due to unusual occurrences. If the exceptions are handled properly, the application will never get terminated abruptly. Define Error Events. ASP.NET supports events that occur when any unhandled exception occurs in an application. These events are called as Error Events. ASP.NET provides two such events to handle exceptions Page_Error : This is page event and is raised when any unhandled exception occur in the page. Application_Error: This is application event and is raised for all unhandled exceptions in the ASP.NET application and is implemented in global.asax

The Error events have two methods to handle the exception: GetLastError: Returns the last exception that occurred on the server. ClearError: This method clear error and thus stop the error to trigger subsequent error event.

Why is exception handling important for an application? Exception handling is used to prevent application from being stuck due to unusual occurrences. If the exceptions are handled properly, the application will never get terminated abruptly. What is the difference between value types and reference types? -Value types are inherited from system.valuetypes -Reference types are inherited system.object. -Value types are stored in a stack -Reference types are stored on heap -When variables are passed by values as parameters, then no change can be made to them when retrieved.

-When variables are passed by reference, their address is passed due to which a change in their values can be reflected back in the calling function. -In .NET, when you pass a variable by value, the syntax would be: (ByVal a as datatype)-and when passed by reference (ByRef a as datatype

Caching 1.Page Output caching 2.Page Fragmet Caching 2.Data Caching Page Output caching <%@ OutputCache Duration="10" VaryByParam="None"%> (Duration=10 second) protected void Page_Load(object sender, EventArgs e) { Cache["name"] = "sarav"; } protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = Cache["name"].ToString(); } When we clicked the buton the cache value sarav will be display in textbox 10 seconds only

Sometimes in our application in some pages the output generally doesn't change for a specific period of time. For example in a HR website, the salary details of an employee doesn't change very frequently and it changes only once in a month. Generally it changes only on the 1st day of every month. So during a month the salary details page will show the same details for a particular employee. So in this case isn't it a good idea to cache the page somewhere in the server to avoid business calculation processing, calls to database and page rendering logic every time the employee wants to see his salary details.
Page Fragmet Caching <%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="CategoryDropDownList" %>

To store a fragment of a page which is known as Page fragment caching ASP.NET provides a mechanism for caching portions of pages, called page fragment caching. To cache a portion of a page, you must first encapsulate the portion of the page you want to cache into a user control. In the user control source file, add an OutputCache directive specifying the Duration and VaryByParam attributes. When that user control is loaded into a page at runtime, it is cached, and all subsequent pages that reference that same user control will retrieve it from the cache..

Data Caching : Caching of data can dramatically improve the performance of an application by reducing database contention and round-trips. Simply data caching store the required data in cache so that web server did not send request to DB server every time for each and every request which increase the web site performance. For data caching we need to cached those data which is accessible to all or which is very common data. The data cache is a full-featured cache engine that enables you to store and retrieve data between multiple HTTP requests and multiple sessions within the same application . There are Three Different way to add data or object into cache. But based upon the situation we have to access it. These methods are Cache[], Cache.add(), cache.insert(). Tracing Tracing is an activity of recording the diagnostic information related to a specific web page that is being executed on the web server. In this discussion we will consider ASP.NET related tracing technique. 1.Page Level 2.Application Level Page Level Tracing

Aspx
<%@ Page Trace="true"> Aspx.cs Page_load() {

Trace.IsEnabled = True } Application Level tracing


When you are working with page level Tracing, you need to know probable page that is to be traced. If your application is complex and if you want to trace you might not be aware exact page that is to be traced. To avoid this problem we, .NET platform, provides a facility to enable the tracing at application level.

Web.Config
<trace enabled="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" localOnly="true" />

ASP.NET Life Cycle PreInit: All the Pre and Post events are introduced as part of .NET Framework 2.0. This event is fired before the Init method is fired. Most common functionalities implemented in this method include (i)Check the IsPostBack property (ii)Set the master page dynamically Init: This event is raised after all controls in the page are initialized and any skin settings have been applied. This event is used to read or initialize control properties. It can be used to register events for some controls for which the events are not specified in the aspx page. InitComplete: Use this event for processing tasks that require all initialization to be complete. PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance. Load: The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections. Control events: Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event. LoadComplete: Use this event for tasks that require that all other controls on the page be loaded. PreRender: This is the last event raised before the HTML code is generated for the page. The PreRender event also occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls. SaveStateComplete: Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. Use this event to perform tasks that require view state to be saved, but that do not make any changes to controls. Render: This is the stage where the HTML code for the page is rendered. The Page object calls the Render method of each control at this stage. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser. UnLoad: This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks How to call the Master Page Master Page <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <asp:contentplaceholder id="cp3" runat="server"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" BackColor="Red" OnClick="Button1_Click" /> </asp:contentplaceholder > ASPX File Call the master page <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main" %> . //HTML conttrols and tags should not be used if we are calling maste page . . How to call the User Control WebUserControl.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> <table style="width: 217px"> <tr> <td> <asp:TextBox ID="TextBox1" runat="server" BackColor="#C0C0FF" Value="hai" Width="102px"></asp:TextBox> </td> <td> <asp:Button ID="Button1" runat="server" BackColor="Yellow" Text="Button" OnClick="Button1_Click" /> </td> </tr> </table> ASPX File <%@ Register TagPrefix="UCL" TagName="Login" Src="~/WebUserControl.ascx" %> <UCL:Login ID="LoginCont1" runat="Server"/>

Now the above textbox and button of user control

will be display here

What is Globalization and Localization in ASP.NET? Localization is the process of adapting a software application for a specific locale. Globalization is the process of identifying the localizable resources of the application. You can provide support for Localization and Globalization to the application using System.Globalization, System.Resources and System.Threading namespaces. The developer can define culture specific information using the System.Globalization namespace. The System.Resources namespace contains ResourceManager class that allows access to resources either from the main assembly or from the Satellite Assemblies. The System.Threading namespace supports for multithreaded programming. A web form has two culture values, Culture and UICulture. Culture value is used for date and number formatting and UICulture values are used to determine culture specific resources. You can set culture and UICulture values in the application as follows. Using <globalization> element of Web.Config. Using @Page directive in the Page. In Code-Behind Page e.g. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ("en-GB"); Thread.CurrentThread.CurrentUICulture=new CultureInfo("en-GB"); Explain the purpose of CultureInfo class. What namespace contains it? System.Globalization namespace contains CultureInfo class. This class provides information about a specific culture, i.e. datetime format, currency, language etc. Steps to implement localizability to the user interface. Implementation consists of basically translating the UI. Web.config <globalization uiCulture=" en-GB" culture="en-GB" /> ASPX

For setting culture in pages use the following: <%@ Page UICulture="en" Culture=" en-GB"%> Explain why Serialization. An object is stored in a file, a database or even in the memory. However, data to be transferred over a network needs to be in a linear form for which serialization and deserialization are used. Advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object later by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization. Explain about Serialization in .NET. Explain binary serialization and XML serialization System.Runtime.Serialization namespace provides Serialization in .NET. The IFormatter interface in the namespace contains Serialize and De-serialize methods that save and load data of a stream. So we need stream as a container for the serialized object(s) and a formatter that serializes these objects onto the stream to implement serialization in .net. Binary serialization is a mechanism that creates exact binary copy of the object onto the storage media by writing the data to the output stream such that it can be used to re-construct the object automatically. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format for storage or transport. This XML stream conforms to a specific XML Schema definition language (XSD) document. What is Formatters? Explain the binary formatter and the SOAP formatter. A formatter determines the serialization format for objects. .NET framework provides Binary formatter and SOAP formatter which inherit from the IFormatter interface The Binary Formatter It provides binary encoding for compact serialization for storage or socket-based network streams. It is not appropriate for data to be passed through a firewall. The SOAP Formatter

10

It provides formatting that can be used to enable objects to be serialized using the SOAP protocol. The class is used for serialization through firewalls or diverse systems

Explain the significance of static method Static methods are used when we want only one copy of that method to perform action and remain active at a single point in time. Imagine a scenario where you need a class to connect to the database once and remain as it is for the entire application. public static class MyDbConnection { public static void ConnectToDb() { } } public void SomeMethod() { } You dont want different instances of this class to be created and connect to the database again and again, hence make a static method in a static class. Advantages and disadvantages of using multithreading Advantages: Simultaneous access to multiple applications Reduced number of required servers Improved performance and concurrency Simplified coding of remote procedure calls and conversations Disadvantages: Code writing, debugging, managing concurrency, testing, porting existing code is difficult in multithreading and multicontexting. MyDbConnection.ConnectToDb(); //code to connect to database

11

Programmers need to remove static variables and replace any code that is not thread-safe to introduce threading into a previously non threaded application.

What do you understand by side-by-site execution of assembly? This means multiple version of same assembly to run on the same computer. This feature enables to deploy multiple versions of the component. Explain how to use the finally statement by providing sample code using C#.NET. Finally statement is executed always irrespective of any condition or error occurring in a method. It is often used to cleanup code. E.g.: public void MyMethod() { try { //code to connect to database //code to perform action } catch (Exception ex) { } finally { } } Demonstrate how to access unmanaged code using Interop //code to disconnect database. //handle exception

12

a) Use System.Runtime.InteropServices. b) Use DllImport to declare the unmanaged procedure. c) Map the data types of the procedures parameters to equivalent .NET types. d) Call the unmanaged procedure. e) Test it Explain WebMethod Attribute in Asp.Net Web Service. Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. The WebMethod attribute tells .NET that a particular public method should be exposed as a web-callable method. The WebMethod attribute has six associated properties to document and change the behavior of your web method. They are: Description MessageName EnableSession CacheDuration TransactionOption BufferResponse The first two properties are used to document a web method, while the others affect its behavior. Web services are not the best solution for certain performance-intensive applications, because applications that invoke Web services experience network delays. Also, data transfers are typically larger because data is transmitted in text-based XML formats. SOAP supports an extensive set of types like the primitive types, DataSet, DateTime, XmlNode and others. SOAP can also transmit arrays of these types and objects of user-defined types. When a program invokes a Web method, the request and all relevant information are packaged in a SOAP message and sent to the server on which the Web service resides. A Web service receives a SOAP message and parses its contents (contained in a SOAP envelope) to determine the method that the client wishes to execute and the method's arguments. After a Web service parses a SOAP message, the proper method is called and the response is sent back to the client in another SOAP message. The client parses the response to retrieve the result. Classes that are used to specify Web method return types and parameter types must provide a public default or parameterless constructor. Properties and instance variables that should be serialized in XML format must be declared public. Properties that should be serialized must provide both get and set accessors. Read-only properties are not serialized. Data that is not serialized simply receives its default value when an object of the class is deserialized.

13

Elements :WSDL Messages The < message > element defines the data elements of an operation. Each message can consist of one or more parts. The parts can be compared to the parameters of a function call in a traditional programming language. WSDL Types The < types > element defines the data type that are used by the web service. For maximum platform neutrality, WSDL uses XML Schema syntax to define data types. WSDL Bindings The < binding > element defines the message format and protocol details for each port. What are the benefits of UDDI? Service consumers can use UDDI to discover services that suit their requirements and to obtain the service metadata needed to consume those services. Service providers can use UDDI to advertise the services they offer.

Industry groups may deploy a UDDI registry to support public or private exchanges. What is Windows Communication Foundation, WCF? WCF helps in building applications to communicate with each other. It is a framework that helps in managing distributed computing. WCF has a layered architecture. It is a part of the .Net Framework 3.0 Explain the components of WCF - Service class, Hosting environment, END point. WCF Service is composed of three components: Service class: It implements the service needed. Host environment: is an environment that hosts the developed service. Endpoints: are the connection points for the clients to connect to the service. Clients find the end points through three components like service contract, binding, and address.

Difference between WCF and Web Services WCF can create services similar in concept to ASMX, but has much more capabilities. WCF is much more efficient than ASP.Net coz it is implemented on pipeline. WCF is more secure, reliable. As WCF is implemented on a different pipeline it does not have all Http capabilities (Http session, cache etc). What are different bindings supported by WCF? a. BasicHttpBinding b. WSHttpBinding

14

c. WSDualHttpBinding d. WSFederationHttpBinding e. NetTcpBinding f. NetNamedPipeBinding g. NetMsmqBinding h. NetPeerTcpBinding i. MsmqIntegrationBinding Different transaction isolation levels in WCF Read Uncommitted: - Also known as Dirty isolation level. It makes sure that corrupt Data cannot be read. This is the lowest isolation level Read Committed: - It ensures not to read the data that has been changed by any other application and is not yet committed. It is the default level. Repeatable Read: - It stops the usage of dirt read and non-repeatable read. It states that data fetched through a query will be locked and will not be updated by any other transaction. Serializable: - It does not allow any modification and addition of new data till the transaction is completed. This is considered to be a very restrictive level. Snapshot: - It raises error on modifying a data that has already been changed by any transaction. What is duplex contract in WCF? Duplex contract: It enables clients and servers to communicate with each other. The calls can be initiated independently of the other one. The duplex contract is one the message patterns available to Windows Communication Foundation (WCF) services. It comprises of two one-way contracts. How do you provide secured communication in ASP.NET? ASP.NET provides secured communication using Secure Sockets Layer. The application to use SSL need to have an encryption key called a server certificate configured in IIS. When a user requests a secured page, the server generates an encryption key for the users session. The encrypted response is then sent along with encryption key generated. In the client side, the response is then decrypted using same encryption key. THREADING To perform concurrent processing. Eg: static void Main() { new Thread(Go).Start(); Go(); }

// Call Go() on a new thread // Call Go() on the main thread

static void Go() { // Declare and use a local variable - 'cycles' for (int cycles = 0; cycles < 5; cycles++)

15

Console.Write('?'); Console.Read();

How does multi-threading work in .NET? There are two main ways of multi-threading which .NET encourages:To start your own threads with ThreadStart delegates, you should create a new thread "manually" for long-running tasks. Using the ThreadPool class either directly (using ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as Stream.BeginRead, or calling BeginInvoke on any delegate). Use the thread pool only for brief jobs. Benefits of using the Thread Pool. Thread creation and destruction overhead is negated, Better performance and better system stability. It is better to use a thread pool in cases where the number of threads is very large. Limitations of using the Thread Pool. A thread pool executes on a single processor. But they are theoretically associated to server farms in which a master process distributes tasks to worker processes on different computers to increase the overall throughput. However, parallel problems are highly open to this approach.

16

Вам также может понравиться