ASP.NET Exclusive Interview Questions and Answers (348) - Page 5

  • A joint initiative from DotNetFunda.Com and Questpond.
  • A one stop place on the internet to get trusted and proven Interview Questions (based on more than a decade of experience in this field) to ensure the success of the candidates.
  • You will find almost all Interview questions from Questpond here and this list is growing day by day with all latest and updated interview questions.

348 records found.

Get 650+ Questpond's Interview videos on discount

What is SQL Cache Dependency in ASP.NET 2.0?

SQL cache dependencies is a new feature in ASP.NET 2.0 which can automatically invalidate a cached data object (such as a Dataset) when the related data is modified in the database. So for instance if you have a dataset, which is tied up to, a database tables any changes in the database table will invalidate the cached data object which can be a dataset or a data source.


How do we enable SQL Cache Dependency in ASP.NET 2.0?

Below are the broader steps to enable a SQL Cache Dependency:-
• Enable notifications for the database.
• Enable notifications for individual tables.
• Enable ASP.NET polling using “web.config” file
• Finally use the Cache dependency object in your ASP.NET code
Enable notifications for the database.
Before you can use SQL Server cache invalidation, you need to enable notifications for the database. This task is performed with the aspnet_regsql.exe command-line utility, which is located in the c:\[WinDir]\Microsoft.NET\Framework\[Version] directory.
aspnet_regsql -ed -E -d Northwind



-ed :- command-line switch
-E: - Use trusted connection
-S: - Specify server name it other than the current computer you are working on
-d: - Database Name


So now, let us try to understand what happens in the database because of “aspnet_regsql.exe”. After we execute the “aspnet_regsql -ed -E -d Northwind” command you will see one new table and four new stored procedures created.





SQL Cache table created for notification


 


Essentially, when a change takes place, a record is written in this table. The SQL Server polling queries this table for changes.




New stored procedures created




Just to make brief run of what the stored procedures do.



“AspNet_SqlCacheRegisterTableStoredProcedure” :- This stored procedure sets a table to support notifications. This process works by adding a notification trigger to the table, which will fire when any row is inserted, deleted, or updated.



“AspNet_SqlCacheUnRegisterTableStoredProcedure”:- This stored procedure takes a registered table and removes the notification trigger so that notifications won't be generated.



“AspNet_SqlCacheUpdateChangeIdStoredProcedure”:- The notification trigger calls this stored procedure to update the AspNet_SqlCacheTablesFor ChangeNotification table, thereby indicating that the table has changed.
Asp Net_Sql Cache Query Registered Tables Stored Procedure:- This extracts just the table names from the AspNet_SqlCacheTablesForChangeNotification table. It is used to get a quick look at all the registered tables.
AspNet_SqlCachePollingStoredProcedure:- This will get the list of changes from the AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling.


 


Enabling notification for individual tables



Once the necessary stored procedure and tables are created then we have to notify saying which table needs to be enabled for notifications.
That can be achieved by two ways:-

• aspnet_regsql -et -E -d Northwind -t Products
• Exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName'
Registering tables for notification internally creates triggerfor the tables. For instance, for a “products” table the following trigger is created. So any modifications done to the “Products” table will update the “AspNet_SqlCacheNotification’ table.


Continues the same question in the next part.


How do we enable SQL Cache Dependency in ASP.NET 2.0? contd.

Continuation of the previous question

CREATE TRIGGER

dbo.[Products_AspNet_SqlCacheNotification_Trigger] ON

[Products]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
EXEC dbo.AspNet_SqlCacheUpdateChangeIdStoredProcedure
N'Products‘
END


“AspNet_SqlCacheTablesForChangeNotification” contains a single record for every table you're monitoring. When you make a change in the table (such as inserting, deleting or updating a record), the change Id column is incremented by 1.ASP.NET queries this table repeatedly keeps track of the most recent changed values for every table. When this value changes in a subsequent read, ASP.NET knows that the table has changed.



Entries in the Cache notification table



Enable ASP.NET polling using “web.config” file
Now that all our database side is configured in order to get the SQL Cache working in the ASP.NET side we need to do some configuration in the web.config file.
We need to set two attributes in the “web.config” file:-
• Set “Enabled” attribute to true to set the caching on.
• Set the poll time attribute to the number of milliseconds between each poll
Below is the snapshot of the web.config file.






 


 


 


 


 


 


 


 


 


 


 




Web.config file modifications for SQL cache



Finally use the Cache dependency object in your ASP.NET code
Now comes the final step to use our cache dependency with programmatic data caching, a data source control, and output caching.
For programmatic data caching, we need to create a new SqlCacheDependency and supply that to the Cache.Insert() method. In the SqlCacheDependency constructor, you supply two strings. The first is the name of the database you defined in the element in the section of the web.config file e.g: Northwind. The second is the name of the linked table e.g: Products.


 

private static void CacheProductsList(List<ClsProductItem> products)

{SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind", "Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);}
private static List<ClsProductItem> GetCachedProductList()
{return HttpContext.Current.Cache["ProductsList"] as List<ClsProductItem>;}

ClsProductItem is business class, and here we are trying to cache a list of ClsProductItem instead of DataSet or DataTable.
The following method is used by an ObjectDataSource Control to retrieve List of Products


 


public static List<ClsProductItem> GetProductsList(int catId, string sortBy)

{//Try to Get Products List from the Cache

List<ClsProductItem> products = GetCachedProductList();
if (products == null)
{
//Products List not in the cache, so query the Database layer
ClsProductsDB db = new ClsProductsDB(_connectionString);
DbDataReader reader = null;
products = new List<ClsProductItem>(80);
if (catId > 0)
{
//Return Product List from the Data Layer
reader = db.GetProductsList(catId);
}
else
{
//Return Product List from the Data Layer
reader = db.GetProductsList();
}
//Create List of Products -List if ClsProductItem-
products = BuildProductsList(reader);
reader.Close();

//Add entry to products list in the Cache
CacheProductsList(products);

}
products.Sort(new ClsProductItemComparer(sortBy));

if (sortBy.Contains("DESC")) products.Reverse();
return products;

}

To perform the same trick with output caching, you simply need to set the SqlDependency property with the database dependency name and the table name, separated by a colon:


<%@ OutputCache Duration="600" SqlDependency="Northwind:Products" VaryByParam="none" %>
The same technique works with the SqlDataSource and ObjectDataSource controls:

<asp:SqlDataSource EnableCaching="True" SqlCacheDependency="Northwind:Products" ... />


Note: - ObjectDataSource doesn't support built in caching for Custom types such as the one in our example. It only supports this feature for DataSets and DataTables.

Just to make a sample check run the SQL Server profiler and see that does the SQL actually hit the database after the first run.


What is Post Cache substitution?

Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.
Post-cache substitution can be achieved by two means:
• Call the new Response.WriteSubstitution method, passing it a reference to the desired substitution method callback.
• Add a <asp:Substitution> control to the page at the desired location, and set its methodName attribute to the name of the callback method.




 


 


 


 


 


 


 


 


 


 



Writesubstitution” in action



You can see we have a static function here “GetDateToString()”. We pass the response substitution callback to the “WriteSubstitution” method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it’s content is never cached.
Ok the above example was by using “WriteSubstitution” now lets try to see how we can do by using “<asp:substitution>” control. You can get the “<asp:substitution>” control from the editor toolbox.




 


 


 


 


 


 


 


 


 



Substitution Control


 



 


 


 


 


 


 


 


 


 


 


 



Substitution in Action




Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the “methodname” attribute of the substitution control.


Why do we need methods to be static for Post Cache substitution?

ASP.NET should be able to call this method even when there is not an instance of your page class available. When your page is served from the cache, the page object is not created. Therefore, ASP.NET skips the page life cycle when the page is coming from cache, which means it will not create any control objects or raise any control events. If your dynamic content depends on the values of other controls, you will need to use a different technique, because these control objects will not be available to your callback.


What is a "theme" in ASP.NET?

A "theme" is a collection of property settings that allow you to define
the look of pages and controls, and then apply the look consistently
across pages in a Web application, across an entire Web application, or
across all Web applications on a server.
What are the 3 levels at which a theme can be applied for a web application?

1. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.
2. At the application level - Can be applied to all pages in an application by setting the element in the application configuration file.
3. At the web server level - Define the element in machine.config file. This will apply the theme to all the web applications on that web server.
Can a Master Page have more than one ContentPlaceHolder?

Yes, a Master Page can have more than one ContentPlaceHolder.
What is a ContentPlaceHolder?

ContentPlaceHolder is a region where replaceable content will appear.
How do you bind a Content Page to a Master Page?

MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.
What are the 3 levels at which content pages can be attached to Master Page?

1. At the page level - You can use a page directive in each content page to
bind it to a master page

2. At the application level - By making a setting in the pages element of
the application's configuration file (Web.config), you can specify that
all ASP.NET pages (.aspx files) in the application automatically bind to
a master page.

3. At the folder level - This strategy is like binding at the application
level, except that you make the setting in a Web.config file in one
folder only. The master-page bindings then apply to the ASP.NET pages in
that folder.
At what stage of page processing master page and content page are merged?

During the initialization stage of page processing, master page and content page are merged.
Can you dynaimically assign a Master Page?

Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code sample below.
void Page_PreInit(Object sender, EventArgs e)
{ this.MasterPageFile = "~/MasterPage.master"; }
Can you access non public properties and non public methods of a master page inside a content page?

No, the properties and methods of a master page must be public in order to access them on the content page.
From the content page code how can you reference a control on the master page?

Use the FindControl() method as shown in the code sample below.
void Page_Load()
{ // Gets a reference to a TextBox control inside // a ContentPlaceHolder ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{ TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1"); if(TxtBox != null) { TxtBox.Text = "TextBox Present!"; } } // Gets a reference to a Label control that not in // a ContentPlaceHolder Label Lbl = (Label)Master.FindControl("Label1"); if(Lbl != null) { Lbl.Text = "Lable Present"; } }
Can you access controls on the Master Page without using FindControl() method?

Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{ MyMasterPage MMP = this.Master; MMP.MyTextBox.Text = "Text Box Found"; }
How to share data in a class between web forms which is present in folder?

This can be achieved by creating a class of type static in folder name "app_code".

More ASP.NET Interview Questions & Answers here

Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Exclusive Interview Questions and Answers Categories