Sie sind auf Seite 1von 7

10/12/2015

SimpleLoginProjectinASP.Net

In Focus

SQLServerMostAskedSQLServerInterviewQuestionsandAnswers

Ask a Question

ARTICLE

SPONSORED BY

READERLEVEL:

Spire.DocFree.NET
WordAPI

SimpleLoginProjectinASP.Net
ByAbhimanyuKVatsaonJun17,2010

UseSpire.Doctocreate,read,
write,print,andconvertword
documentstoOpenXML,RTF,
TXT,XPS,EPUB,EMF,HTML,
ImageandPDF.

Thisarticlewillexplainyouhowtocreatesimpleloginprojectwithoutusinganylogin
controls.

191.5 k
DownloadFiles:SimpleLoginProjectinASP.zip

Contribute

26

DownloadAspose,itreallyhelps

Introduction
Asweknowoninternetworldwithoutsecuritywecannotexpectanything.Atleastonevery
websiteweusetofacesuchliketocreateaccountbutasfarweconcerntolearnhowtocreateit
thenwithoutanygoodguidelineswecan't.Let'stakealookonthisarticletocreatesuchproject.
Perquisite
Thisarticleexpectsomethingfromyouas
1. YoushouldknowMSSQLServer
2. YoushouldhavethebasicknowledgeofASP.Netcontrols
CreatingDatabase
Tostoretheuser'scredentialsforfuturelogin,weshouldhavedatabase.So,let'screateit.
DatabaseName:myDb.mdf
TableName:myTb
ColumnNames:
ColumnName

DataType

RequiredorNot

name

varchar(50)

NotChecked

username

varchar(50)

NotChecked

password

varchar(50)

NotChecked

emailed

varchar(100)

NotChecked

TRENDING UP

01

MostAskedSQLServerInterview
QuestionsandAnswers

02

VisualStudio2015Tips

03

MostAskedASP.NETProperty,
MethodsAndEventsInInterview

04

Important.NETInterviewQuestions
AndAnswers

05

WebForms,MVCAndWebPagesin
ASP.NET

06

LearnTinyBitOfC#In7DaysDay1

07

DynamicPivotGridUsingMVC,
AngularJSAndWEBAPI2

08

ApplyingConditionalAttributesin
ASP.NETMVCViews

09

IntroducingGoogleChartInASP.NET
MVC5

10

Resolve'StringWasNotRecognized
AsAValidDateTime'Error
ViewAll

Follow@csharpcorner

47Kfollowers

C#Corner
109,589likes

LikePage

Share

Bethefirstofyourfriendstolikethis

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

1/7

10/12/2015

SimpleLoginProjectinASP.Net

TECHNOLOGIES

ANSWERS

BLOGS

VIDEOS

INTERVIEWS

BOOKS

NEWS

CHAPTERS

CAREER

JOBS

CODE

IDEAS

C#CornerSearch

CreatingDatabaseConfigurationinweb.configfile
Tocreatedatabaseconfigurationinweb.configfile,simplydragthe'myTb'tablefromDatabase
Exploreronanyformandnowdeletethedraggeditemfromwebpage,itwillcreatethe
configurationsettingsforyourdatabaseinweb.configfileautomatically.

Hereisyourconfigurationinweb.configfile

<connectionStrings>
<addname="myDbConnectionString1"connectionString="Data
Source=.\SQLEXPRESSAttachDbFilename=|DataDirectory|\myDb.mdfIntegrated
Security=TrueUserInstance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
CreateUserFormDesigning
Tocreateorregisternewuserweshouldhaveaformasgivenbelow.Youcanignoretheside
links,topbannerandfootertextsbecausetheyareoccurringfrommasterpage.

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

2/7

10/12/2015

SimpleLoginProjectinASP.Net

ControlName

ID

Other

TextBox

name

TextBox

username

TextBox

password

Textmode=password

TextBox

emailed

Button

create

Text=CreateUser

Tocallforthedatabaseconfigurationsettingfromweb.configfileIhaveusedafunction

publicstringGetConnectionString()
{
return
System.Configuration.ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ConnectionString
}
Ihaveusedaexecutenamedfunctionincodebehindtoperformtheinsertiontaskwhen'Create
User'namedbuttonclicked

privatevoidexecution(stringname,stringusername,stringpassword,stringemailid)
{
SqlConnectionconn=newSqlConnection(GetConnectionString())
stringsql="INSERTINTOmyTb(name,username,password,emailid)VALUES"
+"(@name,@username,@password,@emailid)"
try
{
conn.Open()

SqlCommandcmd=newSqlCommand(sql,conn)
SqlParameter[]pram=newSqlParameter[4]
pram[0]=newSqlParameter("@name",SqlDbType.VarChar,50)
pram[1]=newSqlParameter("@username",SqlDbType.VarChar,50)
pram[2]=newSqlParameter("@password",SqlDbType.VarChar,50)
pram[3]=newSqlParameter("@emailid",SqlDbType.Char,10)
pram[0].Value=name
pram[1].Value=username
pram[2].Value=password
pram[3].Value=emailid
for(inti=0i<pram.Lengthi++)
{
cmd.Parameters.Add(pram[i])
}
cmd.CommandType=CommandType.Text

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

3/7

10/12/2015

SimpleLoginProjectinASP.Net

cmd.ExecuteNonQuery()
}
catch(System.Data.SqlClient.SqlExceptionex_msg)
{
stringmsg="Erroroccuredwhileinserting"
msg+=ex_msg.Message
thrownewException(msg)
}
finally
{
conn.Close()
}
}
FinallyIhaveusedtofollowingcodein'CreateUser'buttonclickevent.Inthiseventwehaveto
checkthedatabasefortheduplication.Becauseinloginprojectduplicationsareneverassumed
even.Ifthereisnoanyduplicationfoundincodebehindwillcreateanewaccount.Hereitis

protectedvoidcreate_Click(objectsender,EventArgse)
{
SqlDataSourcesds=newSqlDataSource()
sds.ConnectionString=
ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString()
sds.SelectParameters.Add("name",TypeCode.String,this.name.Text)
sds.SelectParameters.Add("username",TypeCode.String,this.username.Text)
sds.SelectParameters.Add("password",TypeCode.String,this.password.Text)
sds.SelectParameters.Add("emailid",TypeCode.String,this.emailid.Text)
sds.SelectCommand="SELECT*FROM[myTb]WHERE[username]=@username"
DataViewdv=(DataView)sds.Select(DataSourceSelectArguments.Empty)
if(dv.Count!=0)
{
this.lblinfo.ForeColor=System.Drawing.Color.Red
this.lblinfo.Text="TheuseralreadyExist!"
return
}
else
{
execution(name.Text,username.Text,password.Text,emailid.Text)
this.lblinfo.Text="NewUserProfilehasbeencreatedyoucanloginnow"this.name.Text
=""
this.username.Text=""
this.password.Text=""
this.emailid.Text=""
}
}
LoginUserFormDesigning
Tocreateorregisternewuserwehavecreatedaformbutstillwedon'thaveanyloginform.So
let'screatetheloginform.

ControlName

ID

Other

TextBox

username

TextBox

password

Button

log

Text=Login

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

4/7

10/12/2015

SimpleLoginProjectinASP.Net

Nowwehavetowritesomecodeswhichwillselectthevaluesfromdatabase@valuesin
textboxes.Andifanyvaluesarenotbeingselected(retrieved)incodebehindthenshowtheerror
messagelike'Invalidusernameorpassword!'.Andifitmatchesanyrecordthenwillredirectto
thesecurepage.Hereonemorebigconceptarises,isknowas'membership'.Buthisisoutofthis
article.Let'stakealookatcodebehindofloginform.

protectedvoidlog_Click(objectsender,EventArgse)
{
SqlDataSourcesds=newSqlDataSource()
sds.ConnectionString=
ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString()
sds.SelectParameters.Add("username",TypeCode.String,this.username.Text)
sds.SelectParameters.Add("password",TypeCode.String,this.password.Text)
sds.SelectCommand="SELECT*FROM[myTb]WHERE[username]=@usernameAND
[password]=@password"
DataViewdv=(DataView)sds.Select(DataSourceSelectArguments.Empty)
if(dv.Count==0)
{
this.lblinfo.ForeColor=System.Drawing.Color.Red
this.lblinfo.Text="Invalidusernameandpassword!"
return
}
else
{
this.Session["username"]=dv[0].Row["username"].ToString()
Response.Redirect("securepage/SecurePage.aspx")
}
}
Almostwehavedoneeverythingbutstillwearemissingamajorthing.Ifyourunyourprojectat
thistimewillopentheSecurePage.aspxwithoutloginalso.Butifyouwanttoredirecttheuserfor
loginandthenwithauthenticationcanaccesstheSecurePage.aspxwehavetodenytheaccessin
SecurePage.aspxpageordirectlyinparticulardirectory.Andalsowhenuserenterscredentials
thensessionvariablesrememberituntiluserclosehisbrowserorclickonlogoutbuttonorlink
(generallyweprefertoclickonlogout).
Solet'stakealooktodenytheaccess:

:::::::::::
:::::::::::
<locationpath="securepage">
<system.web>
<authorization>
<denyusers="?"/>
</authorization>
</system.web>
</location>
</configuration>

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

5/7

10/12/2015

SimpleLoginProjectinASP.Net

Andwealsohavetochangetheauthenticationmodeto"Forms"like:

::::::::::::::
<system.web>
<authenticationmode="Forms">
<formsloginUrl="Login.aspx"/>
</authentication>
<compilationdebug="true"/>
</system.web>
::::::::::::::
Conclusion
WecanalsoplaceourloginstoMasterPagesothatcanbevisibleentirelyinwebsite.
HAVEAGOODCODING!

Abhimanyu K Vatsa
MicrosoftMVP|Author|ITFaculty|StudentofM.Tech.IT|BlogsatITORIAN.COM
PersonalBlog:http://www.itorian.com
Rank

6.1m

Platinum

Read

Member

Time

RELATED ARTICLES
SimpleUserLogininASP.NETusingC#
WhoseOnlineinASP.NET2.0
CreateasimpleloginforminMVCASP.NET

LoginPageinPHP
TrackLastLoginofaWebSiteVisitor
SimpleLoginProjectusingStoredProceduresin
ASP.NET:Part1

ViewPreviousComments>>

COMMENTS

10 of 26

Hi....Thisisreallynicearticle.http://dotnetpools.com/Article/ArticleDetiail/?
articleId=24&title=AjaxLoginExampleUsingJqueryInAsp.net
Oct02,2012

vinaysingh
641 73 282

PostReply

Isthismethodofcreatingauser/logginginprotectedfromsqlinjection?
Feb14,2013

TimG
713 1 0

PostReply

@TimG:noitsnot,thetextboxdataishardcoded
Mar15,2013

AbhimanyuKVatsa
8 10.4k 6.1m

PostReply

Canyouexplainc#.net2010andmssql2008windowsformdesinandgivemefullsource
code
Apr24,2013

ganeshsadu
703 11 5.4k

PostReply

PostReply

Wellnicebut....keepitup
Jun05,2013

EmanuelSherpa
713 1 0

HelloAbhimanyuKVatsa.whatiftheuserisnotloggedinthentheusercannotaccessthe
pagesinthenext
May11,2014

hothorasmanpanjaitan
648 66 7.7k

PostReply

NiceAbhimanyuKVatsasir..
Nov19,2014

ManishKumarChoudhary
67 2.7k 396.4k

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

PostReply

6/7

10/12/2015

SimpleLoginProjectinASP.Net
Howtosaveamultifilesatonceinasp.net
Dec01,2014

hothorasmanpanjaitan
648 66 7.7k

PostReply

Nice
Feb27,2015

muhamaadwaqas
712 2 0

PostReply

Howtocreatediscussionforuminasp.net
Feb27,2015

muhamaadwaqas
712 2 0

PostReply

Type your comment here and press Enter Key....

COMMENT USING
0Comments

Sortby Top

Addacomment...

FacebookCommentsPlugin

MVPs

MOSTVIEWED

LEGENDS

ABOUTUS

MEDIAKIT

CONTACTUS

PRIVACYPOLICY

NOW

MEMBERS

PRIZES

REVIEWS

STUDENTS

TERMS&CONDITIONS

SURVEY

CERTIFICATIONS

DOWNLOADS

HostedByCBeyondCloudServices

LINKS

SITEMAP

REPORTABUSE

2015C#Corner.Allcontentsarecopyrightoftheirauthors.

http://www.csharpcorner.com/uploadfile/abhikumarvatsa/simpleloginprojectinAspNet/

7/7

Das könnte Ihnen auch gefallen