Search This Blog

Wednesday, August 17, 2011

Block IP address from any accessing website (asp.net)


One way direct web.config file put following code

<configuration>
<system.web>
<system.webServer>
    <security>
      <ipSecurity allowUnlisted="true">
       
        <clear/>
       
       
        <add ipAddress="192.168.1.8"/>
       
        <add ipAddress="192.168.1.8" subnetMask="255.255.255.0"/>
       
      ipSecurity>
    security>
    <modules runAllManagedModulesForAllRequests="true"/>
  system.webServer>
system.web>
configuration>

Other way
xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
       <appSettings/>
       <connectionStrings/>
       <system.web>
              <httpModules>
                     <add name="SecurityHttpModule" type="SecurityHttpModule"/>
              httpModules>
              <compilation debug="true" targetFramework="4.0"/>
              <authentication mode="Windows"/>
              <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>system.web>
configuration>


And add on App_Code folder one HTTP module class file like “SecurityHttpModule.cs”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

///

/// HTTP module to restrict access by IP address
///

public class SecurityHttpModule : IHttpModule
{
       public SecurityHttpModule() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        //HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = GetIPAddress();
        if (IsValidIpAddress(ipAddress))
        {
            //context.Response.StatusCode = 403;  // (Forbidden)
            Response.Redirect("Default2.aspx");
        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return (ipAddress == "192.168.1.3");
    }

    public void Dispose() { /* clean up */ }


    public static string GetIPAddress()
    {
        string hostName = Dns.GetHostName();
        IPAddress address = Dns.Resolve(Dns.GetHostName()).AddressList[0];
        return address.ToString();
    }
   
}


ASP.NET 4.0 Interview questions


1) What is new in Asp.Net

ASP.Net 4.0 has many improvements from previous versions such as
Web.config File Refactoring
Extensible Output Caching
Auto-Start Web Applications
Permanently Redirecting a Page by introducing a new method RedirectPermanent()
Shrinking Session State to shrink session data
Extensible Request Validation to avoid cross-site scripting (XSS) attacks by adding custom request-validation logic.
Object Caching and Object Caching Extensibility by introducing a new assembly "System.Runtime.Caching.dll"

ASP.Net 4.0 also introduced many new features such as
jQuery Included with Web Forms and MVC: Built in JQuery support
Content Delivery Network Support: Enables you to easily add ASP.NET Ajax and jQuery scripts to your Web applications. We can refence JQuery script over http like
<...script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js">
New Meta tags under HTML Head tag
Enabling View State for Individual Controls
Extended Browser Capabilities
ASP.NET Chart Control to create visually compelling charts for complex statistical or financial analysis
New Field Templates for URLs and E-mail Addresses

2) What is machine.config file and how do you use it in ASP.Net 4.0?

Machine.Config file is found in the "CONFIG" subfolder of your .NET Framework install directory (c:\WINNT\Microsoft.NET\Framework\{Version Number}\CONFIG on Windows 2000 installations). It contains configuration settings for machine-wide assembly binding, built-in remoting channels, and ASP.NET.

In .the NET Framework 4.0, the major configuration elements(that use to be in web.config) have been moved to the machine.config file, and the applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty or to contain just the following lines.
How will you specify what version of the framework your application is targeting?

In Asp.Net 4 a new element "targetFramework" of compilation tag (in Web.config file) lets you specify the framework version in the webconfig file as
3) How is Caching extended in asp.Net 4.0?
OutPut Cache in earlier versions of ASP.Net has a limitation - generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.
ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.
4) How do you implement custom output caching?
Create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown below:
                          type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>

                   

                 

               



Then specify the newly created and configured custom cache provider as below:

<%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %>



5) What is permanent redirecting and how do you implement it?

ASP.Net 4.0 introduced a new URL redirection method RedirectPermanent() which avoids round trips.

You can implement this as shown below:

RedirectPermanent("/newpath/newpage.aspx");



Or

6) What is RedirectPermanent in ASP.Net 4.0?

In earlier Versions of .Net, Response.Redirect was used, which issues an HTTP 302 Found or temporary redirect response to the browser (meaning that asked resource is temporarily moved to other location) which inturn results in an extra HTTP round trip. ASP.NET 4.0 however, adds a new RedirectPermanent that Performs a permanent redirection from the requested URL to the specified URL. and returns 301 Moved Permanently responses.

e.g. RedirectPermanent("/newpath/newpage.aspx");



7) How do you implement ViewState for a control?



In ASP.NET 4, Web server controls include a ViewStateMode property that lets you disable view state by default and then enable it only for the controls that require it in the page.

The ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit. Enabled enables view state for that control and for any child controls that are set to Inherit or that have nothing set. Disabled disables view state, and Inherit specifies that the control uses the ViewStateMode setting from the parent control. 

   

      Disabled:
 


     

        Enabled:  

     

 



8) How will the IDs for controls be managed in ASP.Net 4.0?

In ASP.Net 4.0 we can specify how to generate control ids using 'ClientIDMode' attribute instead of generating dynamically like container_controlidXXX.



9) What are the different ClientIDModes we can set and how will they work?

The new ClientIDMode property lets you specify more precisely how the client ID is generated for controls. You can set the ClientIDMode property for any control, including for the page. Possible settings are the following:

AutoID

This is equivalent to the algorithm for generating ClientID property values that was used in earlier versions of ASP.NET.



Static

This specifies that the ClientID value will be the same as the ID without concatenating the IDs of parent naming containers. This can be useful in Web user controls. Because a Web user control can be located on different pages and in different container controls, it can be difficult to write client script for controls that use the AutoID algorithm because you cannot predict what the ID values will be.



Predictable

This option is primarily for use in data controls that use repeating templates. It concatenates the ID properties of the control's naming containers, but generated ClientID values do not contain strings like "ctlxxx". This setting works in conjunction with the ClientIDRowSuffix property of the control. You set the ClientIDRowSuffix property to the name of a data field, and the value of that field is used as the suffix for the generated ClientID value. Typically you would use the primary key of a data record as the ClientIDRowSuffix value. 



Inherit

This setting is the default behavior for controls; it specifies that a control's ID generation is the same as its parent.



10) What is QueryExtender Control?

QueryExtender Control is an add-on to the DataSource Controls: EntityDataSource and LinqDataSource. QueryExtender is used to filter the data returned by these controls. As the QueryExtender control relies on LINQ, the filter is applied on the database server before the data is sent to the page, which results in very efficient operations.

E.g.:

TableName="Products"> 

 

 

 

      SearchType="StartsWith"> 

     

   

 





11) What is Microsoft Ajax Library.



Microsoft Ajax Library is a client-only JavaScript library that is compatible with all modern browsers, including Internet Explorer, Google Chrome, Apple Safari, and Mozilla Firefox.Because the Microsoft Ajax Library is a client-only JavaScript library, you can use the library with both ASP.NET Web Forms and ASP.NET MVC applications. You can also create Ajax pages that consist only of HTML.



12) What are the Changes in CheckBoxList and RadioButtonList Control ?



In ASP.NET 4, the CheckBoxList and RadioButtonList controls support two new values for the RepeatLayout property, OrderedList(The content is rendered as li elements within an ol element) and UnorderedList(The content is rendered as li elements within a ul element.)



13) Whats Application Warm-Up Module?



We can set-up a Warm-Up module for warming up your applications before they serve their first request.Instead of writing custom code, you specify the URLs of resources to execute before the Web application accepts requests from the network. This warm-up occurs during startup of the IIS service (if you configured the IIS application pool as AlwaysRunning) and when an IIS worker process recycles. During recycle, the old IIS worker process continues to execute requests until the newly spawned worker process is fully warmed up, so that applications experience no interruptions or other issues due to unprimed caches.