Tuesday, August 23, 2011

Using Themes in Asp.Net - Example

Using Themes
The Web pages that belong to the same Web site will invariably contain controls that have many properties in common across pages. This includes properties for setting things like background color, font size, foreground color, and other styles. You can manually set the properties for every control on every page in your site. However, that is time consuming, error prone (as you might overlook some settings), and difficult to change (as a change would have to sweep across your entire site). Instead, you can use ASP.NET themes.

ASP.NET themes consist of the following set of elements:

Skins: Skins are files with .skin extensions that contain common property settings for buttons, labels, text boxes, and other controls. Skin files resemble control markups, but contain only the properties you want to define as part of the theme to be applied across pages.

Cascading Style Sheets (CSS ): These are files with .css extensions that contain the style property definitions for HTML markup elements and other custom style classes. A style sheet is linked to a page, master page, or entire site. ASP.NET applies the styles to the page.

Images and other resources: Images (such as a corporate logo) along with other resources can be defined inside a theme. This allows you to switch out the images when you switch themes for a site.

Creating a Theme:

You create themes inside the ASP.NET special folder, App_Themes. This folder sits in your ASP.NET application root. The folder contains separate folders for each theme in your site. You then add the corresponding skins, style sheets, and images to the theme folders.

You need to apply the theme to your site. You can do so at the individual page level by adding the Theme or StyleSheetTheme attribute to the @ Page directive and setting the attribute’s value to the name of your theme (folder name).

Alternatively, you can apply the theme to an entire Web application by adding the

<pages theme="”themeName”">


element or the

<pages stylesheettheme="”themeName”">


element to the Web.config file. This will automatically apply the theme to all pages in your site.

Creating a Skin File

Skin files serve to define default settings for server control appearance attributes. Each server control has attributes for things like font, background color, width, height, and more. Many of these appearance attributes are common among the controls on your site.

A skin file differs from a style sheet in that the skin file uses the attributes of the actual control and not just a set of standard HTML style elements. Skin files contain two types of skins: default and named skins:

Default skins: A default skin automatically applies to all controls of the same type when a theme is applied to a page. A skin is considered a default skin if it does not have a SkinID attribute.

Named skins: A named skin is a control skin with a SkinID property set to a specific name value. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the ASP.NET control’s SkinID property.

Eg: Default Skins


<asp:Button runat="server" BackColor="#FF3300" BorderStyle="Solid" Font-Bold="True" />


Eg: Named Skins


<asp:Button SkinId="BlueButton" runat="server" BackColor="Blue" BorderStyle="Solid" Font-Bold="True" />


Adding Images to Your Theme
Themes also allow you to switch out the images on your site. This is done through the skin file.

<asp:Image runat="server" SkinId="RedLogo"

ImageUrl="~/App_Themes/RedTheme/RedHead.JPG" />


Adding a Cascading Style Sheet to Your Theme:

A CSS contains style rules that are applied to elements in a Web page. CSS styles define how elements are displayed and where they are positioned on the page.

To add a CSS to your Web site, right-click the name of your theme in Solution Explorer and select Add New Item. You can then select the Style Sheet item template.

body

{
background-color:Black;
}


When the theme is applied to a page, ASP.NET adds a reference to the style sheet to the head element of the page. In the HTML, this reference looks something like the following:

    <link href="SiteStyles.css" rel="themeName/stylesheet" type="text/css" />


Applying a Theme Programmatically:

To apply a theme programmatically, set the page’s Theme property in the Page_PreInit method.
protected void Page_PreInit(object sender, EventArgs e)

{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "RedTheme";
break;
case "Pink":
Page.Theme = "PinkTheme";
break;
}
}



Tuesday, July 12, 2011

Using client-side state management in Asp.Net

ASP.NET provides several techniques for storing state information on the client. These include the following:

View state: ASP.NET uses view state to track values in controls between page requests. You can also add your own custom values to the view state.

Control state: Control state allows you to persist information about a control that is not part of the view state. This is useful to custom control developers. If view state is disabled for a control or the page, the control state will still function.

Hidden fields: Like view state, HTML hidden fields store data without displaying that data to the user’s browser. This data is presented back to the server and is available when the form is processed.

Cookies: Cookies store a value in the user’s browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on an entire Web site.

Query strings: Query strings are values stored at the end of the URL. These values are visible to the user through his or her browser’s address bar. Use query strings when you want a user to be able to e-mail or instant message state data within a URL.

ViewState: View state is the default mechanism used by ASP.NET to store user-specific request and response data between page requests. The data being stored is typically specific to the controls on the page. View state stores object data that is not already represented as HTML in the page response. This ensures that data set on the server is preserved between round trips to the client and the server.

The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag. When an ASP.NET page is processed, the current state of the page and its controls is hashed into a string and saved in the page as an HTML hidden field called __ViewState.


Reading and Writing Custom View State Data:
You can use view state to add and retrieve custom values that you need persisted between page requests.

Adding data to the view state is great when you need the information passed back to the server as part of the page post. However, the content of the view state is for that page only. The view state does not transfer from one Web page to another. Therefore, it is useful only for temporarily storing values between requests to a single page.

Eg:
Place a button and write the following code on its click event.

ViewState["a"] = Convert.ToInt32(ViewState["a"]) + 1;
Response.Write("viewstate value = "+ViewState["a"]);


Hidden Fields
Hidden fields in HTML are simply input fields that are embedded in a page’s HTML, not displayed to the user (unless the user chooses to view the page’s source), and then sent back to the server on the page post.

Like view state, hidden fields only store information for a single page. Therefore, they are not useful for storing session data that is used between page requests. Unlike view state, hidden fields have no built-in compression, encryption, hashing, or chunking. Therefore users can view or modify data stored in hidden fields.

Eg: place a HiddenField and set its initial value into zero. Place a button too and write the following on its click event.

HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();
Response.Write("Hidden value = "+HiddenField1.Value);

Cookies : A cookie is a small amount of data that you write to the client to be stored and then passed with requests to your site.

You write persistent cookies to a text file on the client machine. These cookies are meant to survive the user shutting down the browser and reopening it at a later time. You can also write temporary cookies to the memory of the client’s browser. These cookies are used only during the given Web session. They are lost when the browser closes.

Reading and Writing Cookies

Eg:

    protected void btnCreate_Click(object sender, EventArgs e)
{
HttpCookie c = new HttpCookie("mycookie");
c.Value = "Jobin John";
c.Expires = DateTime.Now.AddDays(3);
Response.Cookies.Add(c);
}
protected void btnRead_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
Response.Write(c.Value);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}
}

Storing Multiple Values in a Cookie: The size of your cookie is dependent on the browser. Each cookie can be up to a maximum of 4 KB in length. In addition, you can typically store up to 20 cookies per site.


protected void btnCreate_Click(object sender, EventArgs e)
{
HttpCookie c = new HttpCookie("mycookie");
c["site"] = "http://www.certifications4you.com/";
c["date"] = DateTime.Now.ToString();
c.Expires = DateTime.Now.AddDays(3);
Response.Cookies.Add(c);
}
protected void btnRead_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];

if (c != null)
{
Response.Write(c["site"]+"<br>"+c["date"]);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}
}

Query Strings
Query string values are appended to the end of the page URL. They are set off with a question mark (?) followed by the query string term (or parameter name) followed by an equal sign (=) and the given parameter’s value. You can append multiple query string parameters using the ampersand (&).

Values sent to your page via the query string can be retrieved on the server through the Page.Request.QueryString property

Eg:
Add two Login.aspx and Home asp.x. place three buttons in the
Login.aspx:
Response.Redirect("home.aspx?user="+txtUserName.Text;

string username=Request.QueryString["user"].ToString();
Response.Write(username);

on Home.aspx's page load:
Response.Redirect("home.aspx?user="+txtUserName.Tex+"&pass="+txtPassword.Text);
string username=Request.QueryString["user"].ToString();
string password=Request.QueryString["pass"].ToString();
Response.Write(username+ " " +password);

Thursday, July 7, 2011

TargetInvocationException was unhandled by user code - Solution

I had been working with an Asp.Net Dynamic Data Web Application, I got an error while debugging the application.

TargetInvocationException was unhandled by user code : Exception has been thrown by the target of an invocation.



This error was because of the wrong filename in the entity connection string. I have fixed this and got it working.

If connection string is not exist in web.config, we will get the same error while debugging.

Note : always check the inner exception details when you are facing this error. This will help you to track out the actual exception caused the error.

Monday, July 4, 2011

Customizing QueryableFilterRepeater Control - Aligning controls

Hi all, Here is a simple solution for customizing the QueryableFilterRepeater control. By default this control adds the filter controls without any alignment, so we should do it manually.
                <table>
<tr>
<td style="width:100%;">
<asp:QueryableFilterRepeater runat="server" ID="FilterRepeater">
<ItemTemplate>
<div class="SearchColumn">
<asp:Label runat="server" Text='<%# Eval("DisplayName") %>' OnPreRender="Label_PreRender" />
<asp:DynamicFilter runat="server" ID="DynamicFilter" OnFilterChanged="DynamicFilter_FilterChanged" />
</div>
</ItemTemplate>
</asp:QueryableFilterRepeater>
</td>
</tr>
</table>

here is the css class used.
div.SearchColumn
{
float:left;
width:48%;
margin:2px 2px 2px 2px;
}

Sunday, June 26, 2011

.Net Interview Questions - OOP

What is Object Oriented Programming (OOP)?
Object-oriented programming (OOP) is a programming language model organized around objects. At this poing you may have a question in your mind, what is an object? its simple, an object can be anything which has some attributes and hehaviour. For example, hope now you are infront of a computer monitor, the monitor itself is an object, it has a lot of attributes like Make, Size, Type etc...

In OOP we use classes and objects to represent our data and logic. For example consider the following C# example.

public class Monitor
{
public string Make
{
set;
get;
}

public int Height
{
set;
get;
}

//etc......

}
The above class defines a structure of the computer monitor. An object of this class can represent a computer monitor.
OOP Concepts


  1. Data Abstraction : The act of representing essential features without showing the back ground details.

  2. Data Encapsulation: The wrapping up of data together into a single unit.

  3. Inheritance: The act of inheriting properties of an object into another.

  4. Polymorphism: The ability of a data to behave in multiple forms.

Possible questions about OOP concepts from a .NET stand point are:



  1. What is Data Abstraction? ans: see above definition

  2. What is Encapsulation? ans: see above definition

  3. What is inheritance? ans: see above definition

  4. What is Polymorphism? ans: see above definition

  5. Does .Net support multiple inheritance? ans: no

  6. Example for polymorphism? ans:function overloading, overriding and operator overloading

  7. Real world example for data abstraction? ans: when we press the start switch of a car or bike will get started, we might not need to know the internal process. we gave an input and we got an outcome.

  8. What is a class and an object? ans: class is a blueprint for creating objects. An object is an instance of a class and it have the properties and behaviours defined in the class.

Namespace in C# and its Advantages

Namespaces are a way of grouping type names and reducing the chance of name collisions. A namespace can contain both other namespaces and types. The namespace keyword is used to declare a scope.

We can organize our types based on their bahaviour and functionalities. For example consider the following example. Suppose you have a collection of songs, how will you store it in your computer? normally one do this by creating root folder named "Songs" then create sub folders based on song types, then create subfolders for albums etc....

Have a look on the following C# example to understand the advantages of the namespace.

namespace Songs
{
public class Songs
{
public void PlayAll()
{
Console.WriteLine("Playing all songs..");
}
}
namespace English
{
public class Titanic
{
public void Play()
{
Console.WriteLine("Playing titanic..");
}
}
}
namespace Malayalam
{
public class Urumi
{
public void Play()
{
Console.WriteLine("Playing urumi.....");
}
}
}
}