Wednesday, June 24, 2009

Authentication in ASP.Net

Authentication in ASP.Net


There are three types of Authentication Levels exist in the ASP.Net: Windows Authentication, Forms Authentication, Passport Authentication.

You can change/add authendication in web config file, in that you have to mention the authendication mode is Windows Authenticatin/Passport Authentication/Form Authentication as follows:

// web.config file

<authentication mode = "[Windows/Forms/Passport/None]">
</authentication>


Windows authentication: enables you to identify users without creating a custom page. Credentials are stored in the Web server’s local user database or an Active Directory domain. Once identified you can use the user’s credentials to gain access to resources that are protected by Windows authorization. It’s a default authentication mode.


Forms authentication: enables you to identify users with a custom database such as an ASP.NET membership database. Alternatively you can implement your own custom database. Once authenticated you can reference the roles the user is in to restrict access to portions of your Web site.


Passport authentication: relies on a centralized service provided by Microsoft. Passport authentication identifies a user with using his or her e-mail address and a password and a single Passport account can be used with many different Web sites. Passport authentication is primarily used for public Web sites with thousands of users.


Thursday, June 18, 2009

ASP .Net Page Life Cycle

ASP .Net Page Life Cycle

1. OnInit (Init) Initializes each child control of the current

2. LoadControlState: Loads the ControlState of the control. To use this
method the control must call the Page.RegisterRequiresControlState method in
the OnInit method of the control.

3. LoadViewState: Loads the ViewState of the control.

4. LoadPostData: Is defined on interface IPostBackDataHandler. Controls that
implement this interface use this method to retrieve the incoming form data and
update the control s properties accordingly.

5. Load (OnLoad): Allows actions that are common to every request to be
placed here. Note that the control is stable at this time; it has been
initialized and its state has been reconstructed.

6. RaisePostDataChangedEvent: Is defined on the interface IPostBackData-Handler.
Controls that implement this interface use this event to raise change events in
response to the Postback data changing between the current Postback and the
previous Postback. For example if a TextBox has a TextChanged event and
AutoPostback is turned off clicking a button causes the Text-Changed event to
execute in this stage before handling the click event of the button which is
raised in the next stage.

7. RaisePostbackEvent: Handles the client-side event that caused the Postback
to occur

8. PreRender (OnPreRender): Allows last-minute changes to the control. This
event takes place after all regular Post-back events have taken place. This
event takes place before saving ViewState so any changes made here are saved.

9. SaveControlState: Saves the current control state to ViewState. After this
stage any changes to the control state are lost. To use this method the
control must call the Page.RegisterRequiresControlState method in the OnInit
method of the control.

10. SaveViewState: Saves the current data state of the control to ViewState.
After this stage any changes to the control data are lost.

11. Render: Generates the client-side HTML Dynamic Hypertext Markup Language
(DHTML) and script that are necessary to properly display this control at the
browser. In this stage any changes to the control are not persisted into
ViewState.

12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this
stage. Unmanaged resources are resources that are not handled by the .NET common
language runtime such as file handles and database connections.

13. UnLoad

Thursday, May 28, 2009

Caching Overview (ASP.Net)

Caching Overview:

Abstract: Caching is a feature of ASP.NET that can dramatically improve the performance of your application by storing the page output or application data across HTTP requests.

This article cover:

  • What is Caching ?
  • Benefits of Caching
  • Introducing the Problems that Caching Solves
  • Types of Caching
What is caching?

  • Caching is a feature that stores data in memory, allowing incoming requests to be served from memory directly.
  • In the context of a web application, caching is used to retain pages or data across HTTP request and reuse them without the expense of recreating them.

Benefits of Caching

The following are the benefits of using Caching:

  • Faster page rendering
  • Minimization of database hits
  • Minimization of the consumption of server resources

Types of Caching

  • Page Output Caching
  • Page Fragment Caching
  • Data Caching
  • Page Output Caching:
Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML
is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.

Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique.
The following is the complete syntax of page output caching directive

<%@ OutputCache
Duration="no of seconds“ * required field
Location="Any | Client | Downstream | Server | None"
VaryByControl="control"
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter“ * required field
%>

Example:

<%@OutputCache Duration="60" VaryByParam="none" %>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.

The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached.


  • Page Fragment Caching
In addition to output caching an entire page, ASP. Net provides Partial-Page Output
Caching, or Page Fragment Caching. Page Fragment Caching allows specific regions of pages to be cached.

Page Fragment Caching is easy to implement. By simply using the @OuputCache
page directive, ASP.NET Web pages can take advantage of this powerful technique.
The syntax looks like this:

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButtonList"%>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.

The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached.

The VaryByControl parameter allows different cache entries to be made based on the values for a specified control.


  • Data Caching
ASP. Net provides a full-featured cache engine, Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache, similar to the storing of objects in Application scope in classic ASP.

The ASP. Net cache is private to each application and stores objects in memory. The lifetime of the cache is equivalent to the lifetime of the application.

To store a value in the cache, use syntax like this:

Cache[“myKey"] = myValue; // C#
Cache(“myKey") = myValue ' VB.NET

To retrieve a value, simply reverse the syntax like this:

myValue = Cache[“myKey"]; // C#
myValue = Cache(“myKey") ' VB.NET

Monday, March 30, 2009

Custom paging in grid view control using c#

In one of my application I required to implement custom paging in the ASP.Net 2.0 Gridview control in the following pattern:

"Previous 10 Pages Previous Page 1 2 3 4 5 6 7 8 9 10 Next Page Next 10 Pages"


In ASP.Net 2.0 GridView is most often used to display the data retrieved from the database in Tabular form with features of Gridview like data paging, sorting and auto formats.
For above mentioned paging, I find a way to implement custom paging in ASP.Net 2.0 GridView control.
So this article basically describes how we can implement custom paging style in ASP.Net GridView control.


CSharp (C#) code:


#-----region Class for creating grid view navigation links--------
class NumericWithNext : ITemplate
{

GridView localGrid;
int intSlotNo = 0;

#region CONTRUCTOR
public NumericWithNext(GridView gv)
{
localGrid = gv;
//intSlotNo = slotNo;
intSlotNo = localGrid.PageIndex / 10;

//constructor
}
#endregion

#region HELPER

#region Function for creating Navigation Links
public void InstantiateIn(Control container)
{

LinkButton prevTenRecords = new LinkButton();
prevTenRecords.Text = "Previous 10 Pages";
prevTenRecords.CssClass = "PagingLnks";
prevTenRecords.CommandArgument = ((intSlotNo - 1) * 10 + 1).ToString(); ;
prevTenRecords.CommandName = "Page";
//prevTenRecords.Click += new EventHandler(prevTenRecords_Click);
prevTenRecords.Width = Unit.Pixel(125);
if (intSlotNo > 0)
{
container.Controls.Add(prevTenRecords);
}

LinkButton nextTenRecords = new LinkButton();
nextTenRecords.Text = "Next 10 Pages";
nextTenRecords.CommandName = "Page";
nextTenRecords.CommandArgument = ((intSlotNo + 1) * 10 + 1).ToString();
// nextTenRecords.Click += new EventHandler(nextTenRecords_Click);
nextTenRecords.CssClass = "PagingLnks";
nextTenRecords.Width = Unit.Pixel(118);
// nextTenRecords.Visible = false;



LinkButton prev = new LinkButton();
prev.Text = "Previous Page";
prev.CssClass = "PagingLnks";
prev.CommandArgument = "Prev";
prev.CommandName = "Page";
prev.Width = Unit.Pixel(90);
if (localGrid.PageIndex > 0)
{
container.Controls.Add(prev);
}

//for (int pagenum = 1; pagenum <= localGrid.PageCount; pagenum++)
for (int pagenum = (intSlotNo*10)+1; pagenum <= (intSlotNo+1)*10; pagenum++)
{
if (pagenum > localGrid.PageCount)
{
nextTenRecords.Visible = false;
break;
}
LinkButton pageInd = new LinkButton();
if (pagenum == localGrid.PageIndex + 1)
{
//pageInd.ForeColor = System.Drawing.Color.Green;PagingSelected
pageInd.CssClass = "PagingSelected";
}
else
{
pageInd.CssClass = "PagingLnks";
}
pageInd.ID = "PageInd_" + pagenum;
pageInd.Text = pagenum.ToString();
pageInd.CommandName = "Page";
pageInd.CommandArgument = pagenum.ToString();
container.Controls.Add(pageInd);
pageInd.Width = Unit.Pixel(10);
}

LinkButton next = new LinkButton();
next.Text = " Next Page";
next.CommandName="Page";
next.CommandArgument = "Next";
next.CssClass = "PagingLnks";
next.Width = Unit.Pixel(80);
if (localGrid.PageIndex < localGrid.PageCount - 1)
{
container.Controls.Add(next);
}

container.Controls.Add(nextTenRecords);
}

void nextTenRecords_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
intSlotNo++;

}

void prevTenRecords_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
intSlotNo--;
}
#endregion

#endregion
}
#-------endregion-----------


//--------------Use above mentioned class to create custom paging------------------
private void loadDynamicGrid(DataTable dt)
{

grdSearchResults.HeaderStyle.CssClass = "blkheader gridViewBorder_IP";
grdSearchResults.GridLines = GridLines.None;
grdSearchResults.CssClass = "gridViewBorder_IP";
grdSearchResults.RowStyle.CssClass = "gridViewBorder_IP";
grdSearchResults.HeaderStyle.CssClass = "blkheader gridViewBorder_IP";
grdSearchResults.AlternatingRowStyle.CssClass = "grayRow";
grdSearchResults.PageSize = this.RecordsPerPage;
grdSearchResults.PagerSettings.Mode = PagerButtons.Numeric;
//-------------Create custom paging-----------------------
grdSearchResults.PagerTemplate = new NumericWithNext(grdSearchResults);
//--------------------------------------------------------------------
//Initialize the DataSource
grdSearchResults.DataSource = dt;
//Bind the datatable with the GridView.

grdSearchResults.DataBind();


}

With the help of above code, you will get the results as shown in the below image:


How to move vertical scroll bar using javascript in ASP.Net Web Form

Whenever ASP.NET Web Form page loaded, by defualt its focus set to first control (vertical scroll bar moved downward in this case) in the ASP.Net web form page. If you required to move your vertical scroll bar to the top of the page, then following client-side script help you in achieving this task:

<script>
function moveVerticalScroll()
{
document.body.scrollTop=0;
}
window.onload=
moveVerticalScroll;

</script>




How to set focus on control using javascript

This article demonstrates how to set focus to an ASP.NET Web Form control by using client-side script.

ASP.NET Web Form controls provide a similar look and feel of the traditional HTML controls while they provide a consistent and structured interface and more robust features. In addition, you can use client-side scripting to enhance the functionality that these controls provide.

In my project, i required to set focus on particular control on the drop down change event. For this i used/added following javascript on the SelectedIndexChanged event of drop down list:

Page.RegisterStartupScript("MoveVerticalScrollBar", "<script>document.all('" + chkEmployee.ClientID + "').focus();</script>");

With the help of above script, focus set to
chkEmployee control after the SelectedIndexChanged event of drop down list.

Saturday, September 20, 2008

A Rainy Day :: A sweet-2 morning

A Rainy Day :: A sweet-2 morning


Today is rainy day. I got the chance to see this beautiful weather today morning when my maid came to home and ring the door bell. At that time every one was busy in dreaming except me, so I wake up quickly for opening the door and asked her to make a cup of tea so that I can completely get rid of from my sleep. After taking the tea I was thinking that daily I was missing this beautiful weather created by the GOD.


Also, its good time for me to surprise my fiancé by saying sweet GOOD MORNING, so i make a call to her. During call I was thinking for the song “Mere hath mem thera Hath ho..Saare Jannathe mere saath ho….Tujo paas Ho..phir kya ye jaha ..tere pyaar mem hojavuu FANAA….”, but dear friend It can’t possible at that moment (because we are living too far from each other) and this situation arises due to impact of this sweet rainy morning.


After making a call, i started thinking that why not try to utilize my photographic skill to shot some best pictures. I clicked some picture and added in this post. In the rainy day, I like to eat Bhajias (fried Indian snack). Also known as Pakoras, these are the perfect snack for a cold, rainy day! Make up a batch and serve them with sweet-sour tamarind chutney, YUMMY!

The rainy day is more romantic day in comparision to other day. I love to watch the rain falling. Sometimes the drop of water is hard (thick) and sometimes ever so soft (thin). I love the sound it makes when it hits the ground.


Dear friends this was the starting of my sweet Saturday rainy morning.


A Sweet Rainy morning pictures are
:











Sunday, September 14, 2008

Serial bomb Blast in Delhi: A Saturday

Serial bomb Blast in Delhi:

In Delhi, Yesterday (13th September’08) evening Five blasts rocked New Delhi. The blasts at Ghaffar market in Karol Bagh, at Connaught Place and Greater Kailash took place in quick succession, the police said. All these places are crowded areas of Delhi. In the history of delhi, this Saturday become A Saturday. Last blasts (29th October’05) in delhi also occurred before festive season (Dushera/ Durga Puja/ Diwali) was arrived.


The first blast took place at Ghaffar market in which at least 20 people were injured. They were rushed to the nearby Ram Manohar Lohia Hospital.

Two explosions took place in Connaught Place, in which at least 10 people were injured.Another explosion rocked M-Block market in Greater Kailash-I.The first blast took place at 6:10 pm. The bomb was placed in a dustbin in a parking lot outside Grover’s Enterprises, a local shop. The blast caused panic among the shoppers and the shopkeepers downed their shutters.

Three unexploded bombs were found later taking the total number of bombs to 8. The first was found near India Gate inside a dustbin at the Children's Park and one was defused at Regal Cinema Hall which was lying on the road, while another one was found at Central Park, again inside a dustbin. A National Security Guard (NSG) team defused the bombs after they were informed by the witnesses about unclaimed objects. NSG experts were assessing the situation and nature of explosives used.

Indian mujahddin has claimed the responsibility .Delhi police arrested mastermind of these bomb blast.


Now, these blasts cleared that this system does not able to handle these terrorism. So that its time for every common man to think about how can remove terrorism from this system. The best example is to follow the story line of A Wednesday movie, in which one common man trying to remove terrorism from this system.

Movie Review - A Wednesday

A Wednesday is one of the best movies in recent times. It is good time for the Indian Cinema (Bollywood) because directors are coming out with their own new stories and fresh ideas that make an impact on the viewer. The examples of these things are Phoonk and Rock ON. A Wednesday movie is not about the train blasts, nor the sequel to ‘Mumbai Meri Jaan’ which too was about the blasts that rocked the Mumbai city two years ago. This movie (A Wednesday) also based on the terrorism but its showing the pledge and power of the Common Man (Aam Aadmi).




Powered by: Chakpak.com A Wednesday !


A Wednesday has a star cast that includes veteran actors like Naseeruddin Shah and Anupam Kher. The duo last acted in a movie called China Gate way back in the year 1998. Neeraj Pandey gets them together once again in a hard hitting thriller.

A Wednesday’s plotline is very strong and straight forwad. The story of this movie (A Wednesday)does not contain any sweet songs shot at scenic locales in some distant continent, its totally shot in the Mumbai for giving strong impact to the story line of the movie. This movie talks about terrorism from a new angle. In this movie a common man trying to show to the system that if common man reached to the extreme point of frustration due to the terrorism then it can do anything to clear terrorism from system. In this film director have not been used any religious label to point out terrorism in this system. This is the best thing with this film, because terrorism is related to the entire world not related to particular community.

A Wednesday tells the story of certain events that unfold between 2 and 6 P.M. on A Wednesday in Mumbai. Events that do not exist in any record.

It’s a Wednesday when Prakash Rathod (Anupam Kher), the Commissioner of Police, Mumbai receives a phone call asking him to release four militants.

The caller (Naseeruddin Shah) threatens him saying if he took his call lightly, he would be responsible for a series of 5 bomb blasts in the city. But if he listens to him, many innocent lives would be saved and the caller would also reveal where he had planted the bombs.

Rathod suspects it to be a crank call, but is forced to change his opinion when his men find a bomb at the police station right in front of the headquarters.The information about this bomb given by the caller to Prakash Rathod to prove him self that don’t take me lightly.

It is then that the Chief Minister orders Rathod to tackle this critical situation. While trying to trace the caller, he meets a reporter from a news channel - Naina Roy, played by Deepal Shaw, who has also been tipped off by the same anonymous caller.

Two of Rathod’s best men, Arif (Jimmy Shergill) and Jai (Aamir Bashir) also chip in to trail the caller.

This short, one and a half hour film, has a tight script which would not divert your attention from the silver screen for a split second. The director even manages to squeeze in a couple of comic scenes too e.g. when one man come to police station to logged F.I.R. against his wife / After giving the interview to the News Channel Jai (Aamir Bashir) asked some dialog to Rathod. Director Neeraj Pandey has filmed some mind-blowing sequences and surely has a creative vision which would help him make a name amongst the top directors of Bollywood pretty soon.

Naseeruddin Shah proves yet again that there is just noone like him. Immensely powerful performance, he conveys so much just through his expressions. Anupam Kher too is fantastic, a treat to see the two legends together on screen. Also do watch Jimmy Shergill in one of his best performances to date.

Overall, A Wednesday is not to be missed. Its got the right combination of everything with reveting performance and a movie that will be with you long after you leave the cinema hall.

Movie: A Wednesday

Cast: Anupam Kher, Aamir Bashir, Deepal Shaw, Gaurav Kapur, Naseeruddin Shah,

Rajpal Yadav, Jimmy Shergill

Cinematographer: Fuwad KhanSound

Designer: Rakesh Ranjan

Producer: Anjum Rizvi, Shital Bhatia

Banner: Anjum Rizvi Film Company

Director: Neeraj Pandey

Saturday, September 13, 2008

Saddi DILLI to PAGAL hai


A is for Adjust, Punjabis will always ask you to adjust whenever they want to push you around.

B is for Backside, and it has nothing to do with your bum, it is an instruction to go to the rear of a building, or block, or shop or whatever.

C is for cloney and its first name is not George nor is it a process for replicating sheep – it is an area where people live eg. Dfence cloney.

D is for Saddi Dilli



E is for expanditure – and believe me Punjabis are not scared of spending money – the latest cars, marble floors, their ambitions are always expanding.

F is for fackade, and even though it sounds like a bad word it is actually just the front of a building (with backside being the back, of course).

G is for Gaddi and the way a Punjabi can pilot a car puts any F1 driver to shame, if the Grand Prix does come to Delhi there’s no way Hamilton, Alonso or Kimi can overtake Balvinder, Jasvinder and Sukhvinder.

H is for Ho Jayega, the moment you hear that, you have to be very careful because you can be reasonably sure it’s not going to happen.

I is for Intezaar… to know more about it see P.

J is for Jindagi and if there’s one person who knows how to live life to the full it’s a Punjabi.

K is for Khanna, Khurana, etc – the Punjabi equivalent of the Johnses ie, keeping up with the Khuranas.

L is for Lovely but she never is.

M is for Mrooti – the car that moved an entire Punjabi generation.

N is for No problem ji - to find out how that works see H.

O is for Oye which can be surprise (oyye!), a hailing (oyy), anger (OYY) or pain (oy oy oy).

P is for Panch minit and no matter how near (1 km) or far a Punjabi is from you (100 km) they usually say they’ll reach you in panch minit.

Q is for Queue for which there’s really no word in Punjabi.

R is for Riks and a Punjabi is always prepared to take one, even if the odds are against them. S is for Sweetie, Bunty, Pappu and Sonu who seem to own half the cars in Delhi.

T is for the official bird of P u n j ab –
Tandoori chicken.

U is for when U lose your sex appeal and become ‘Uncle’.

V is for VIP phone numbers @ Rs 15 lakh and counting.

W is War – on the roads.

X is x-rated words they flow freely in casual conversations on the street.

Y is ‘You nonsense’, anger replacing vocabulary in a shouting match.

And Z is for Zig zag for which you should see G, M and P.


Reference: Author: Shivjeet Kullar; Delhi Times; The Times of India;