Archive

Archive for June, 2011

How to handle usercontrol events in aspx page?

June 10, 2011 4 comments

Raise a event from usercontrol to aspx page 

ASP.Net  applications with user controls need to commucinate with usercontrols and aspx page. We can sent parameter as properties to usercontrol from aspx page and also we can access the usercontrol controls from aspx page. This post describing how we can communicate between aspx page and usercontrols. 

Multiple usercontrols in a single aspx page communication

 Here we consider the scenario, we have two usercontrols in a single page and need to communicate between usercontrols through aspx page. 

Usercontrol1

Create a usercontrol with name usercontrol1 and having login screen with login button. The usercontrol having two textboxes one for username, and other for pasword and a textbox for login. 

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs"
    Inherits="testWebApp.UserControl1" %>
<div>
    username
    <asp:TextBox ID="txtUserName" runat="server" />
    Password
    <asp:TextBox ID="txtPassword" runat="server" />
    <asp:Button ID="btnLogin" runat="server" onclick="btnLogin_Click" Text="Login" />
</div>
 

 UserControl 2

Create a usercontrol with name usercontrol2 and having single label control to display login name. 

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl2.ascx.cs" Inherits="testWebApp.UserControl2" %> 
<asp:Label ID="lblUserName" runat="server" Text="This is from UserControl2" />

 ASPX page

Create a aspx page with name main.aspx page and included above user controls and also created a label control for displaying current username

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="main.aspx.cs" Inherits="testWebApp.main" %>
 <%@ Register Src="~/UserControl1.ascx" TagName="uc1" TagPrefix="uc" %>
<%@ Register Src="~/UserControl2.ascx" TagName="uc2" TagPrefix="uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" ID="lblUserName" Text="This is from Aspx Page" />
        <uc:uc1 runat="server" ID="uc1" />
        <uc:uc2 runat="server" ID="uc2" />
    </div>
    </form>
</body>
</html>

 When we enter username and press enter, will raise a event from usercontrol to aspx page, means from usercontrol1 to main aspx. At the same time we need to display username in the aspx page. For achieving that first we store the username in the usercontrol itself as properties and raise a event from usercontrol to aspx page. To raise a event to parent page, declared a Event Handler and will call the event handler once the user press the button.

 Code behind of UserControl1 

public partial class UserControl1 : System.Web.UI.UserControl
    {
        public EventHandler loginClickArgs;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserName = txtUserName.Text;
            loginClickArgs(sender,e);
        }

        private string _username;
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }
    }
 

Codebehind main ASPX page 

To get event from usercontrol in aspx page, we need to initialise the event in the page load and create a funtion for curresponding event. The username entered in the usercontrol1 will get from the usercontrol1 properties. From here we assigned the label text by taking the value from usercontrol1.

     public partial class main : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            uc1.loginClickArgs += new EventHandler(login_Click);
        }

        private void login_Click(object sender, EventArgs e)
        {
            lblUserName.Text = "Hi " + uc1.UserName + ", Welcome to ASPX Page";
            uc2.UserName = uc1.UserName;
            uc2.displayMessage();
        }
    }
 

 Code behind userControl2

To call a function in usercontrol from aspx page, we need to declare a function as public in the usercontrol. If we need any dynamic parameter to the function, we need to create a properties in the usercontrol and set this from the aspx page. Here we are setting the username from the usercontrol1 to usercontrol2 from main aspx page. Then calling a public function displaymessage() in the usercontrol2 from the aspx page.

 public partial class UserControl2 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void displayMessage()
        {
            lblUserName.Text = "Hi " + UserName + ", This message from usercontrol";
        }

        private string _username;
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }
    } 

As a conclution, we have done following thing : we raise a event from a usercontrol to parent aspx page

(Event delegation from user control to aspx page in ASP.NET,C#), access the usercontrol event from aspx page, access the usercontrol variable from aspx page, call usercontrol’s public function from aspx page, setting a usercontrol’s variable from aspx page. That means we discussed all about usercontrol and aspx page communication.

How to change master page navigation style from aspx page?

June 8, 2011 2 comments

How to include site navigation in master page?

A Master page in most of the ASP.Net applications conatin common contents in the site like header,footer,left menus etc.. But some of the time we need to communicate with master page content from aspx page for changing style, displaying current user details etc. 

Here we are explaining how to change navigation div style in masterpage from the aspx page as per the page visits. Here we are having navigation divs Home,AboutUS,ContatcUS etc.. All this divs are in the master page. All the div background color is white and once we visited the particular page we need to set curresponding navigation div background color to blue. The steps explaining also how to access master page control from aspx page.

 Steps to change style of master page from aspx page 

Step 1 : For first step creating a master page with common header contents with navigations divs. Like below mentioned image, we have created 4 divs and back ground color is gray, and active page has background color is blue. CSS for menu and active menu is also given below. 

ASPX page 

<div class='<%= HomeMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="Home.aspx”">Home</a></div>
                </div>
                <div class='<%= ShopeMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="Products.aspx">Shope</a></div>
                </div>
                <div class='<%= ContactUsMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="ContactUs.aspx">Contact Us</a></div>
                </div>
                <div class='<%= AboutUsMenu %>'>
                    <div style="margin-top: 3px;">
                        <a href="AboutUs.aspx">About Us</a></div>
                </div> 

CSS Style 

.menubutton
{
background-color:#f2f2f2;
}
.menubuttonselect
{
background-color:#507cd1;
}
 

Step2 : Creating properties for each div navigation menu for style. 

private string _homeMenu = "menubutton";
        public string HomeMenu
        {
            get { return _homeMenu; }
            set { _homeMenu = value; }
        }

        private string _shopeMenu = "menubutton";
        public string ShopeMenu
        {
            get { return _shopeMenu; }
            set { _shopeMenu = value; }
        }

        private string _contactUsMenu = "menubutton";
        public string ContactUsMenu
        {
            get { return _contactUsMenu; }
            set { _contactUsMenu = value; }
        }

        private string _aboutUsMenu = "menubutton";
        public string AboutUsMenu
        {
            get { return _aboutUsMenu; }
            set { _aboutUsMenu = value; }
        }
 

Step 3 :

 In load event of every aspx page, we need to set active menu property of the master page as per the browsing page. Suppose when a user browses contact us page we need to set ‘ContactUsMenu’ to active class from the aspx page. 

protected void Page_Load(object sender, EventArgs e)
{ 
 Master.ContactUsMenu = "menubuttonselect";
}

How to set favicon for website page?


What is a favicon ? 

It’s a good practice to add a favicon to the website. Favicon is nothing but it is a small icon associated with a particular website, and typically displayed in the address bar of a browser viewing the site. A favicon (short for favorites icon), also known as a website icon, shortcut icon, url icon, or bookmark icon is a 16×16, 32×32 or 64×64 pixel square icon associated with a particular website or webpage. 

How to set favicon for websites? 

Setting favicon to the website is very simple, can be acieved by simple steps. First of all we need to create fav icon which should be associated with our website, size 16×16, 32×32 or 64×64 and uploaded to our website (commonly inside images folder). 

In the second step we have to put below codes inside the header tag of all webapages in our site. After that if you browse your web page you can see that your favicon is showing in address bar. Eg : www.supershope.com

 <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />

How to show error page in ASP.Net


Handle custom errors in ASP.Net

Once the ASP.Net application is ready to launh to customers, there is no need to show the error details in to the web page when any errors occurred. In this scenario we can show our customised page with details like “Server is busy now please after some time” to the customer. At the same time we can store error details to database or txt file for future reference for developers. For customise errors in the ASP.Net we need to do some settings in the web.config file.

 Settings on web.config to show error page 

<customErrors mode="On" defaultRedirect="error.aspx">
<error statusCode="404" redirect="404Error.aspx"/>
</customErrors> 

The above code should be placed in the web.config file for handling custom errors (mode=”On”). Also we can handling particular erros with error code with appropriate error page. In above mentioned code, if a user request a page that is not in the server, 404 error is occurred then page is automatically direct to 404Error.aspx. If any other errors occurred, it will show web page error.aspx. In the same way we can handle any type of error with the status code, with the appropriate web page.

How to use cache in ASP.Net ?


Why need to cache data in ASP.Net? 

Most of the developers don’t know where can use cache mechanisam in ASP.Net.   For good performance of ASP.Net dynamic application we can use cache mechanism. This is nothing but we store some dynamic data into the cache for reusablility of web pages when user request the same again. That means suppose we have a link in our websites, that displays all the items in the database. When user clicks first time, it will fetch all data from the database and displayed to the web page. If a user trying to get same data for the second time, normally we are not able track whether the user tried same data before, so we are doing same procedure again (Fetching data from database and render to the html). As a optimisation part of the we bsite, we need to fetch same data only in single time for a user (Because new items inserted in to the database is rare case). 

Simple codes to cache data in ASP.Net 

To achieve tracking of user’s request, we can use cache mechanism. In the above example when a user trying to get all items from the database, we need to fetch this data and will store to cache object. When the same user trying to get same data for the second time, we need to check is there any data in the cache object, if it is there just displayed to the web page else taken from the db and store to the cache for future. 

How to store a string variable to cache? 

Cache["name"]="Smitha";
 if (Cache["name"] != null)
    Label1.Text= Cache["name"].ToString();

 To insert objects into the cache, the Add method or different versions of the Insert method of the Cache class can be used. These methods allow us to use the more powerful features provided by the Cache class. One of the overloads of the Insert method is used as follows: (How to store data object into cache in ASP.Net ?)

Cache.Insert("Name", strName,
    new CacheDependency(Server.MapPath("name.txt"),
    DateTime.Now.AddMinutes(2), TimeSpan.Zero);
 

The first two parameters are the key and the object to be inserted. The third parameter is of type CacheDependency and helps us set a dependency of this value to the file named name.txt. So whenever this file changes, the value in the cache is removed. We can specify null to indicate no dependency. The fourth parameter specifies the time at which the value should be removed from cache. [See example 5 for an illustration.] The last parameter is the sliding expiration parameter which shows the time interval after which the item is to be removed from the cache after its last accessed time.

The cache automatically removes the least used items from memory, when system memory becomes low. This process is called scavenging. We can specify priority values for items we add to the cache so that some items are given more priority than others:

Cache.Insert("Name", strName,
    new CacheDependency(Server.MapPath("name.txt"),
    DateTime.Now.AddMinutes(2), TimeSpan.Zero,
    CacheItemPriority.High, null);
Categories: DotNet Tags:

How to create a always visible div in css and HTML

June 2, 2011 3 comments

 How to create a div that is always visible even while scrolling 

In some scenario we need to show some information like ads,twitter like account’s logo,new updates etc..  always to user even he is scrolling website We can implement this using simple HTML and CSS within few steps. We can create more attractive div with given appropriate color and style to css.

 Step by step process to create always visible div 

Here we are explaining how easily we can create an always visible div using simple CSS in html by steps by step. We can create always visible div within 2 steps.

 Step 1

Create a css class and name it “alwaysVisibleDiv” (you can give any name that you like). And add position as “fixed”; 

<style type="text/css">
<!--
.alwaysVisibleDiv
{
    position: fixed;
    bottom: 10px;
    left: 10px;
}
//-->
</style>
 

Step2

 Add a new div to the page and specify the class name (class=”alwaysVisibleDiv”)

 <div class="alwaysVisibleDiv">
    Hello I am here always
</div>

 Always visible div is ready. You can see above div position is always there (here we are fixed bottom left) even user scrolling website. We can fix this div at any position of the web page by giving bottom,right,top,left position to the class ‘alwaysVisibleDiv’. By using this html css code we can keep element in view while scrolling website without any jquery,ajax techniques.

Categories: HTML Tags: ,

How to confirm before close browser using javascript?

June 1, 2011 1 comment

Can we stop browser close using Javascript? 

Some time it’s better to give a warning to user when he trying to close the browser. Some browsers has the facility by default but they can be disabling from the browser itself. So it’s better to give a warning message to user from the application itself. In this case we can use JavaScript for given the confirm message to user before close the browser window.

 How to stop browser closing using javscript ?

We have to call a javascript funtion to give a confirmation message to user on browser closing event. We can achieve it by call a event ‘onbeforeunload’ from the body tag. This event will fired when a user close the browser. On this event we are calling a function quit(), On this function we are given a confirm message to user and return the result. If user clicks OK browser will close, if user press cancel it will return to the browser

 Simple Javascript codes to prevent browser close

 
<html>
<head>
<script type="text/javascript">
function quit(){
event.returnValue="Are you sure you have finished?"
}
</script>
</head>
<body onbeforeunload="quit()">
<div id="timeDiv"></div>
</body>
</html>
Categories: Javascript Tags:

How to display current time using javascript?


How ro create a Javascript clock?

Most of the websites are shown current time on top or bottom. But if we want to display updated time that means updated by each seconds, we can implemented JavaScript timer for the same. In some of the case we need to display count time or stopwatch have to display on our website, that time also we can implement same technique.

 Javascript code for dynamic timer.

Below are the javascript codes for timer. There is a default function setTimeout available in javscript for repeated execution for a particular period.

 
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('timeDiv').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',00);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>

<body onload="startTime()" bgcolor="blue">
<div id="timeDiv"></div>
</body>
</html>

%d bloggers like this: