Forms Authentication in ASP.NET 2.0, 3.5, 4.0 With Folder Level Access And Multiple Web.Config Files is technique to decide how users can access your web application. Using forms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access And roles.
we can manage formsAuthentication through web.config file
Read my article on implementing FormsAuthentication Ticket And Managing Roles
1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application
2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.
Now to implement Forms Authentication we need to configure web.config file (in the application root)
For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">
</forms>
</authentication>
</system.web>
Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it's access rules
In this web.config write this inside <system.web> tag
<authorization>
<deny users="?"/>
</authorization>
</system.web>
Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event
protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);
if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}
And this for checking username and password, i m using hard coded values
{
string userName = "amiT";
string password = "password";
if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}
Forms Authentication In Asp.Net 2.0 3.5 4.0
Export Paging Enabled GridView To PDF Using ITextSharp
Export Paging Enabled GridView To PDF Using ITextSharp C# VB.NET In ASP.NET. In my previous post Export GridView to pdf , i explained how to write Grid View contents to a PDF file , but this code has some bugs
1. Code doesn't work if paging is enabled in GridView
2. Columns become of variable width in PDF documnt as shown in the image below
To fix these problems we need to write code without using xmlTextReader and HtmlParser.
for this we need to create a table in PDF document and then fill the cells of table from GridView
And the new html and codebehind would become like this
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default" %><!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>Untitled Page</title>
</head><body><form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server"AutoGenerateColumns="False"AllowPaging="true"
PageSize="5"DataSourceID="SqlDataSource1"><
Columns><asp:BoundField DataField="Name
"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"
SortExpression="Location" /></Columns></asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>
"SelectCommand="SELECT [Name], [Location] FROM [Test]">
</asp:SqlDataSource></div><br />
<asp:Button ID="btnExport" runat="server"
OnClick="btnExport_Click"Text="Export to PDF" />
</form></body></html>
And the code behind goes like this
protected void btnExport_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
int tableRows = rowCount + 3;
iTextSharp.text.Table grdTable=
new iTextSharp.text.Table(columnCount, tableRows);
grdTable.BorderWidth = 1;
grdTable.BorderColor = new Color(0, 0, 255);
grdTable.Cellpadding = 5;
grdTable.Cellspacing = 5;
Cell c1 = new Cell("Exporting paging enabled GridView to PDF example");
c1.Header = true;c1.Colspan = 2;
grdTable.AddCell(c1);
Cell c2 = new Cell("By amiT jaiN , amit_jain_online@yahoo.com");
c2.Colspan = 2;
grdTable.AddCell(c2);
grdTable.AddCell("Name");
grdTable.AddCell("Location");
for (int rowCounter = 0;
rowCounter < rowCount; rowCounter++)
{for (int columnCounter = 0;columnCounter < columnCount; columnCounter++)
{string strValue =GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
Document Doc = new Document();
PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();Doc.Add(grdTable);
Doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader
("content-disposition", "attachment; filename=AmitJain.pdf");
Response.End();
PDF created would be like this
Ajax AutoCompleteExtender in GridView
In this example i am implementing Ajax AutoCompleteExtender TextBox in EditItemTemaplate of GridView using AjaxControlToolkit In Asp.Net, for this we need to create a web service which calls the method to fetch data from database and display results as suggestions for textbox
We can also create AutoComplete TextBox In Winforms Windows Forms Application.
Add a new webservice to the project and name it AutoComplete.asmx or whatever you want, in the code behind of the web service we write methods to get records from database and a web method called GetCompletionList which takes text entered in textbox as parameter to search database , this method is automatically called when ever user types anything in the textbox, following is the code for web service.
C# CODE
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {
public AutoComplete ()
{
}
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
DataTable dt = GetRecords(prefixText);
List
VB.NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration
In html source of aspx page add a ToolkitScriptManager and add ServiceReference and path to asmx file inside it, in gridview add autocomplete extender for the textbox which we want to show auto suggestion.
1: <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
2: <Services>
3: <asp:ServiceReference Path="AutoComplete.asmx"/>
4: </Services>
5: </asp:ToolkitScriptManager>
6:
7: <asp:UpdatePanel ID="UpdatePanel1" runat="server">
8: <ContentTemplate>
9:
10: <asp:GridView ID="GridView1" runat="server"
11: AutoGenerateColumns="False"
12: DataSourceID="SqlDataSource1">
13: <Columns>
14: <asp:CommandField ShowEditButton="True"/>
15: <asp:TemplateField HeaderText="ID" SortExpression="ID">
16: <ItemTemplate>
17: <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'/>
18: </ItemTemplate>
19:
20: <EditItemTemplate>
21: <asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'/>
22: </EditItemTemplate>
23: </asp:TemplateField>
24:
25: <asp:TemplateField HeaderText="Name" SortExpression="Name">
26: <ItemTemplate>
27: <asp:Label ID = "lblName" runat="server" Text='<%#Eval("Name")%>'/>
28: </ItemTemplate>
29: <EditItemTemplate>
30: <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name")%>'/>
31:
32: <asp:AutoCompleteExtender runat="server"
33: ID="autoComplete1"
34: TargetControlID="txtName"
35: ServicePath="AutoComplete.asmx"
36: ServiceMethod="GetCompletionList"
37: MinimumPrefixLength="1"
38: CompletionInterval="10"
39: EnableCaching="true"
40: CompletionSetCount="12" />
41: </EditItemTemplate>
42: </asp:TemplateField>
43:
44: </Columns>
45: </asp:GridView>
46: </ContentTemplate>
47: </asp:UpdatePanel>
48:
49: <asp:SqlDataSource ID="SqlDataSource1" runat="server"
50: ConnectionString="<%$ConnectionStrings:DatabaseConnectionString%>"
51: SelectCommand="SELECT [ID], [Name] FROM [Test]"
52: UpdateCommand="Update Test set [Name] = @Name where ID = @ID">
53: <UpdateParameters>
54: <asp:Parameter Name="Name" />
55: <asp:Parameter Name="ID" />
56: </UpdateParameters>
57: </asp:SqlDataSource>
Disable Copy Paste Right Click Using JavaScript In Asp.Net TextBox
In this example i'm explaining how to Disable Copy Paste Right Click Using JavaScript In Asp.Net TextBox, Some time for many reasons we don't want to allow users to use right click to copy paste or by using ctrl+C , ctrl+v in textbox on a aspx page in asp.net, To disable this we can use javascript
we can achieve this in 2 ways
1. use this method when u don't want any alerts or message
<asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false"> </asp:TextBox>
2. If you want to show alerts than use this method instead
Right this javascript function in the head section of aspx page, in this function we are disabling right mouse click and ctrl keys
<head runat="server"> <title>Untitled Page</title> <script language="javascript"> function DisableRightClick(event) { //For mouse right click if (event.button==2) { alert("Right Clicking not allowed!"); } } function DisableCtrlKey(e) { var code = (document.all) ? event.keyCode:e.which; var message = "Ctrl key functionality is disabled!"; // look for CTRL key press if (parseInt(code)==17) { alert(message); window.event.returnValue = false; } } </script> </head>
Now use this function on the textbox which we want to disable copy paste and right clicking
<body> <form id="form1" runat="server"> <div> <strong> Right click disabled</strong> textbox <br /> <asp:TextBox ID="TextBoxCopy" runat="server" onMouseDown="DisableRightClick(event)"> </asp:TextBox><br /> <br /> <strong>Ctrl key </strong>disabled<br /> <asp:TextBox ID="TextBox2" runat="server" onKeyDown="return DisableCtrlKey(event)"> </asp:TextBox><br /> <br /> Another method to disable<strong> Cut,Copy and paste </strong>in textbox<br /> <br /> <asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false"> </asp:TextBox> </form> </body>Hope this helps
AutoComplete TextBox In WinForms Windows Forms Application
In this example i am explaining how to create AutoComplete TextBox In WinForms Windows Forms Application Using C# VB.NET.
There are two ways we can use Autocomplete feature
1. Auto complete with previously entered text in textbox.
2. AutoComplete TextBox by fetching data from database.
Read Ajax AutoComplete Extender Textbox for asp.net web applications.
1. Auto complete textBox with previously entered text in textbox.
For filling textbox with previously entered data/text in textbox using Autocomplete feature we can implement by setting autocomplete mode proeprty of textbox to suggest, append or sugestappend and setting autocomplete source to custom source progrmetically
First of all create a global AutoCompleteStringCollection and write code like this
{
public partial class Form1 : Form
{
AutoCompleteStringCollection autoComplete = new AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
autoComplete.Add(textBox1.Text);
MessageBox.Show("hello");
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//auto.Add(textBox1.Text);
textBox1.AutoCompleteCustomSource = autoComplete;
}
}
}
2. AutoComplete textBox by fetching the data from database.
For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database
For autocomplete functionalty to work we need to define these 3 properties of textbox
1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory
2. AutoCompleteSource - this needs to be set as Custom Source
3. AutoCompleteCustomSource - this is the collection we created earlier
The complete C# code will look like this
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection =
ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection =
new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"Select distinct [Name] from [Names]" +
" order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show("Hope you like this example");
}
}
}
In the similar way we can also create a autocomplete type combobox

