Monday, May 12, 2014

ASP.NET Interview Questions And Answers Part-3

ASP.NET Interview Questions And Answers Part-3



How to identify which control caused Postback?

 



Below code will help you to identify the control which caused the postback.The name of the control which caused the postback will be set in__EVENTTARGET by __doPostBack JavaScript function before the form issubmitted.

 


string ctrlname = page.Request.Params.Get(“__EVENTTARGET”);

if (ctrlname != null && ctrlname != string.Empty)


return this.Page.FindControl(ctrlname);

 



How to Encrypt/Decrypt the web.config file in .NET?

 




public static void mEncryptWebConfig(string appPath, string protectedSection, stringdataProtectionProvider)


System.Configuration.Configuration webConfig =WebConfigurationManager.OpenWebConfiguration(appPath);

ConfigurationSection webConfigSection = webConfig.GetSection(protectedSection); if (!webConfigSection.SectionInformation.IsProtected)


webConfigSection.SectionInformation.ProtectSection(dataProtectionProvider); �

webConfig.Save();


public static void mDecryptWebConfig(string appPath, string protectedSection)


System.Configuration.Configuration webConfig =WebConfigurationManager.OpenWebConfiguration(appPath);

ConfigurationSection webConfigSection = webConfig.GetSection(protectedSection); if (webConfigSection.SectionInformation.IsProtected)


webConfigSection.SectionInformation.UnprotectSection();

webConfig.Save();

Can we set Master page dynamically at runtime?

 




Yes. Set the MasterPageFile property only during the PreInit page event—that is, before the runtime begins working on the request (since the rendering of the page with the master page occurs prior to the Init event)protected void Page_PreInit(object sender, EventArgs e)


MasterPageFile = “simple2.master”;

If you try to set the MasterPageFile property in Init or Load event handlers, an exception is raised.Note: The Master property represents the current instance of the master page object, is a read-only property, and can’t be set programmatically. The Master property is set by the runtime after loading the content of the file referenced by the MasterPageFile property.The above code needs to add in every page of the site. Instead, it is easy enough to add that code to a base page class that you can inherit from for you pages in the site. In case if you do not already have the base page, you can use the following web.config settings to have a base class without having to modify the existing aspx pages.<system.web>

<!– … –>

<pages pageBaseType=”MyWeb.UI.MyPageBase” />

<!– … –>

</system.web>
How to update web.config programatically?

 



Below is sample code to update web.config:protected void EditConfigButton_Click(object sender, EventArgs e)


Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(“~”);

AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection(“appSettings”); �

//Edit

if (objAppsettings != null)

objAppsettings.Settings["test"].Value = “newvalueFromCode”;

objConfig.Save();

 



How to implement singleton design pattern in C#?

 




The intent of the Singleton pattern as defined in Design Patterns is to “ensure a class has only one instance, and provide a global point of access to it”. The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application. 

Below is sample implementation:


/// <summary>

/// Thread-safe singleton example created at first call

/// </summary>

public sealed class Singleton


private static readonly Singleton _instance = new Singleton();


private Singleton()


public static Singleton Instance


get


return _instance;



How to provide security in .NET web services?



 



Following are few authentication technics to secure a .NET Web Services
  1. Windows-Based Security
    1. Basic Windows Authentication

    2. Digest Windows Authentication

    3. Integrated Windows Authentication


  2. Custom Authentication
    1. Log-in Method

    2. SOAP Headers

    3. SOAP header with cookie

    4. SOAP Extensions

    5. SOAP extension with encryption


I listed three Windows-based and five custom authentication techniques for Web services. Obviously, there are many more permutations and variations on this theme. Table 1 lists the authentication options I discussed, and the main points to consider when choosing an authentication mechanism:


  • Is the password sent in clear text and therefore requires HTTPS?

  • What are the platform requirements on both the client and the server side?

  • When does authentication take place, on the first call only, or on every call? What are the throughput implications of that?

Table 1: Comparing Windows-based and custom authentication techniques for Web services.






































Authentication MethodPassword Sent in Clear TextRequires WindowsAuthenticate on First Call Only

Basic Authentication



Yes



No



Yes



Digest Authentication



No



No



Yes



Integrated Authentication



No



Client/Server



Yes



Log-in method



Yes



No



Yes



SOAP header



Yes



No



No



SOAP header with cookie



Yes



No



Yes



SOAP extension



Yes



Client/Server



Depends



SOAP extension with encryption



No



Client/Server



Depends




 



Following three patterns govern the ASP.NET Page Framework.
  1. Front Controller Pattern

  2. Page Controller Pattern

  3. Model View Controller Pattern

When ASP.NET determines which HttpHandler to pass a request to, it uses something similar to a Front Controller. Front Controller is characterized by a single handler for all requests (like System.Web.UI.Page). Once the request reaches the Page class, though, the Page Controller pattern takes over.


 


Within the ASP.NET implementation of Page Controller, there are elements of the Model View Controller pattern. Model View Controller separates the model (business objects, data, and processes) from the view (the display of information). The controller responds to user input and updates the model and view. Roughly speaking, an ASPX page represents the View while its codebehind file represents a hybrid Model-Controller. If you were to pull all business and data-related code out of the codebehind and leave only event handling code, this would turn the codebehind into a pure Controller while the new class containing the business logic would be the Model.

 




How can I create an non zero base indexed array?



 



Yes, It’s possible to create the arrays that have non-zero based index.You can dynamically create your own arrays by calling Array’s static CreateInstance method. There are several overloads of this method, but they all allow you to specify the type of the elements in the array, the number of dimensions in the array, the lower bounds of each dimension, and the number of elements in each dimension.But keep in mind that nonzero-based arrays are not CLS (Common Language Specification)-compliant.The following code demonstrates how to dynamically create a two-dimensional array of System.Decimal values.

 


public sealed class Program


public static void Main()


// We want a 2-dim array [2001..2010][1..4]

Int32[] lowerBounds = 2001, 1 ;

Int32[] lengths = 10, 4 ;

Decimal[,] quarterlyIncome =

(Decimal[,])Array.CreateInstance(typeof(Decimal), lengths, lowerBounds);


Console.WriteLine(“0,4 1, 9 2, 9 3, 9, 4, 9”,

“Year”, “Q1″, “Q2″, “Q3″, “Q4″);


Int32 firstYear = quarterlyIncome.GetLowerBound(0);

Int32 lastYear = quarterlyIncome.GetUpperBound(0);

Int32 firstQuarter = quarterlyIncome.GetLowerBound(1);

Int32 lastQuarter = quarterlyIncome.GetUpperBound(1);


for (Int32 year = firstYear; year <= lastYear; year++)


Console.Write(year + ” “);

for (Int32 quarter = firstQuarter; quarter <= lastQuarter; quarter++)


Console.Write(“0,9:c “, quarterlyIncome[year, quarter]);


Console.WriteLine();



The first dimension represents calendar years and goes from 2001 to 2010, inclusive. The second dimension represents quarters and goes from 1 to 4, inclusive.


 


Output:


 

 




Why can’t I serialize hashtables?



 




The thing about XML Serialization is that it’s not just about creating a stream of bytes. It’s also about creating an XML Schema that this stream of bytes would validate against. There’s no good way in XML Schema to represent a dictionary. This limitation is not only Hashtable, the XmlSerializer cannot process classes implementing the IDictionary interface due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement theIDictionary interface.
How form based authentication works in ASP.NET?

 


Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie. However, ASP.NET version 2.0 supports cookieless forms authentication, which results in the ticket being passed in a query string.If the user requests a page that requires authenticated access and that user has not previously logged on to the site, then the user is redirected to a configured loginUrl under authentication section of web.config.This processing is handled by the FormsAuthenticationModule class, which is an HTTP module that participates in the regular ASP.NET page-processing cycle and intercepts every request to the website. If it fails to find valid authentication ticket, it will redirect to the logon page.The logon page prompts the user to supply credentials, typically a user name and password. These credentials are then passed to the server and validated against a user store, such as a SQL Server database or XML. After the user’s credentials are authenticated, we have to issue Forms authentication ticket before we redirected the user to the originally requested page. If you redirect the user without issuing Forms authentication ticket, FormsAuthenticationModule will again takes the user to login page as it fails to find valid ticket.

We can issue Forms authentication ticket in multiple ways beside on requirement


  1. Using FormsAuthentication.RedirectFromLoginPage

    [CODE=cs]

  2. if (objUserBLL.Validate(txtUser.Text, txtPassword.Text))


  3. FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);


  4. [/CODE]


    1. Using FormsAuthentication.SetAuthCookie

      [CODE=cs]

    2. if (objUserBLL.Validate(txtUser.Text, txtPassword.Text))


    3. string Role = objUserBLL.GetUserRole(txtUser.Text);

    4. if (Role.Equals(“JobSeeker”))


    5. FormsAuthentication.SetAuthCookie(txtUser.Text, false);

    6. Response.Redirect(“~/JobSeeker/Dashboard.aspx”);


    7. else if (Role.Equals(“Recruiter”))


    8. FormsAuthentication.SetAuthCookie(txtUser.Text, false);

    9. Response.Redirect(“~/Recruiter/Dashboard.aspx”);


    10. 20.


      [/CODE]



      ASP.NET Interview Questions And Answers Part-3

No comments:

Post a Comment