Introduction:
Recently i recieved one question from one of our blog visitor and now-days login page is very important step for most of application.And it is very helpful for allowing only authenticated user's can use our app.For example the process is like,
1. First user need to fill registration form.
2. Login with registered username & password
3. After login successfully ,app need to show the related login user details until SignOut
4. SignOut from the application,so that it will redirect to login page for another login.
Requirements:
- This sample is targeted on windowsphone 7.1 OS
Description:
Okay,lets follow below steps to create login app .
Step 1:
- Open Visual Studio and create new project name (Ex: "LoginApp")
Step 1:
Step 2 : Creating Login Form
For simplicity, I divided this sample into MVVM design pattern. So in Model folder i placed related classes, In Views folder i placed xaml pages. And this sample hierarchy is like this:
For simplicity, I divided this sample into MVVM design pattern. So in Model folder i placed related classes, In Views folder i placed xaml pages. And this sample hierarchy is like this:
Now create LoginPage on Views folder,and in designing part create login form with following xaml code.
- <!--LayoutRoot is the root grid where all page content is placed-->
- <Grid x:Name="LayoutRoot" Background="White">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <StackPanel Grid.Row="0" Margin="12,17,0,28">
- <!--Title-->
- <TextBlock Text="Login Page" Foreground="Black" FontSize="40"/>
- <!--UserName-->
- <TextBlock Text="UserID" Foreground="Black" FontSize="30"/>
- <TextBox BorderBrush="LightGray" Name="UserName" GotFocus="UserName_GotFocus"/>
- <!--Password-->
- <TextBlock Foreground="Black" Text="Password" Margin="9,-7,0,0" FontSize="30"/>
- <PasswordBox BorderBrush="LightGray" Name="PassWord" GotFocus="UserName_GotFocus" />
- <!--Login Button-->
- <Button Content="Login" Background="#FF30DABB" Name="Login" Click="Login_Click" />
- <!-- Registration Button-->
- <Button Content="Registration" Background="#FF30DABB" Name="SignUp" Click="SignUp_Click"/>
- </StackPanel>
- </Grid>
so your phone looks like:
In LoginPage.xaml.cs, write following code
- public void Login_Click(object sender, RoutedEventArgs e)
- {
- //Will explain it later
- }
- public void SignUp_Click(object sender, RoutedEventArgs e)
- {
- NavigationService.Navigate(new Uri("/Views/SignUpPage.xaml", UriKind.Relative));
- }
For new user registration, click on 'Registration' button will redirect to registration form.
Step 3 : Creating Registration Form
Now create 'SignUpPage' on Views folder,and in designing part create registration form with following xaml code.
- <!--LayoutRoot is the root grid where all page content is placed-->
- <Grid x:Name="LayoutRoot" Background="White">
- <Grid Margin="5,0,0,0">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- </Grid.RowDefinitions>
- <!--Title-->
- <TextBlock Text="User Registration :" Grid.Row="0" FontSize="40" Foreground="Black"/>
- <!--UserName-->
- <TextBlock Text="UserName :" Grid.Row="1" Foreground="Black" Margin="0,25,0,0"/>
- <TextBox Name="TxtUserName" BorderBrush="LightGray" Grid.Row="1" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
- <!--Password-->
- <TextBlock Text="Password: " Grid.Row="2" Margin="0,25,0,0" Foreground="Black" />
- <PasswordBox Name="TxtPwd" BorderBrush="LightGray" Grid.Row="2" Margin="100,0,0,0" GotFocus="pwd_GotFocus" />
- <!--Address-->
- <TextBlock Text="Address: " Grid.Row="3" Margin="0,25,0,0" Foreground="Black" />
- <TextBox Name="TxtAddr" BorderBrush="LightGray" Grid.Row="3" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
- <!--Gender-->
- <TextBlock Text="Gender: " Grid.Row="4" Margin="0,25,0,0" Foreground="Black" />
- <RadioButton Name="GenMale" Background="LightGray" Content="Male" Grid.Row="4" Margin="100,0,0,0" Foreground="Black" />
- <RadioButton Name="GenFeMale" Background="LightGray" Content="Female" Grid.Row="4" Margin="200,0,0,0" Foreground="Black" />
- <!--Phone Number-->
- <TextBlock Text="Phone No: " Grid.Row="5" Margin="0,25,0,0" Foreground="Black" />
- <TextBox Name="TxtPhNo" BorderBrush="LightGray" MaxLength="10" InputScope="digits" Grid.Row="5" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
- <!--Email-->
- <TextBlock Text="EmaiID: " Grid.Row="6" Margin="0,25,0,0" Foreground="Black" />
- <TextBox Name="TxtEmail" BorderBrush="LightGray" Grid.Row="6" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>
- <!--Submit Button-->
- <Button BorderBrush="Transparent" Background="#FF30DABB" Content="Submit" Name="BtnSubmit" Click="Submit_Click" Grid.Row="7"/>
- </Grid>
- </Grid>
- IsolatedStorageFile ISOFile = IsolatedStorageFile.GetUserStoreForApplication();
- private void Submit_Click(object sender, RoutedEventArgs e)
- {
- //UserName Validation
- if (!Regex.IsMatch(TxtUserName.Text.Trim(), @"^[A-Za-z_][a-zA-Z0-9_\s]*$"))
- {
- MessageBox.Show("Invalid UserName");
- }
- //Password length Validation
- else if (TxtPwd.Password.Length < 6)
- {
- MessageBox.Show("Password length should be minimum of 6 characters!");
- }
- //Address Text Empty Validation
- else if (TxtAddr.Text == "")
- {
- MessageBox.Show("Please enter your address!");
- }
- //Gender Selection Empty Validation
- else if (gender == "")
- {
- MessageBox.Show("Please select gender!");
- }
- //Phone Number Length Validation
- else if (TxtPhNo.Text.Length != 10)
- {
- MessageBox.Show("Invalid PhonNo");
- }
- //EmailID validation
- else if (!Regex.IsMatch(TxtEmail.Text.Trim(), @"^([a-zA-Z_])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$"))
- {
- MessageBox.Show("Invalid EmailId");
- }
- //After validation success ,store user detials in isolated storage
- else if (TxtUserName.Text != "" && TxtPwd.Password != "" && TxtAddr.Text != "" && TxtEmail.Text != "" && gender != "" && TxtPhNo.Text != "")
- {
- UserData ObjUserData = new UserData();
- ObjUserData.UserName = TxtUserName.Text;
- ObjUserData.Password = TxtPwd.Password;
- ObjUserData.Address = TxtAddr.Text;
- ObjUserData.Email = TxtEmail.Text;
- ObjUserData.Gender = gender;
- ObjUserData.PhoneNo = TxtPhNo.Text;
- int Temp = 0;
- foreach (var UserLogin in ObjUserDataList)
- {
- if (ObjUserData.UserName == UserLogin.UserName)
- {
- Temp = 1;
- }
- }
- //Checking existing user names in local DB
- if (Temp == 0)
- {
- ObjUserDataList.Add(ObjUserData);
- if (ISOFile.FileExists("RegistrationDetails"))
- {
- ISOFile.DeleteFile("RegistrationDetails");
- }
- using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("RegistrationDetails", FileMode.Create))
- {
- DataContractSerializer serializer = new DataContractSerializer(typeof(List<UserData>));
- serializer.WriteObject(fileStream, ObjUserDataList);
- }
- MessageBox.Show("Congrats! your have successfully Registered.");
- NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
- }
- else
- {
- MessageBox.Show("Sorry! user name is already existed.");
- }
- }
- else
- {
- MessageBox.Show("Please enter all details");
- }
- }
So 'RegistrationDetails' isolated storage file having list of users registration details. When user entering his username, password and pressing the login button from LoginPage. we need to check authentication process like this:
On LoginPage Loaded : Read all existing user details list
- private void LoginPage_Loaded(object sender, RoutedEventArgs e)
- {
- var Settings = IsolatedStorageSettings.ApplicationSettings;
- //Check if user already login,so we need to direclty navigate to details page instead of showing login page when user launch the app.
- if (Settings.Contains("CheckLogin"))
- {
- NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));
- }
- else
- {
- if (ISOFile.FileExists("RegistrationDetails"))//loaded previous items into list
- {
- using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("RegistrationDetails", FileMode.Open))
- {
- DataContractSerializer serializer = new DataContractSerializer(typeof(List<UserData>));
- ObjUserDataList = (List<UserData>)serializer.ReadObject(fileStream);
- }
- }
- }
- }
On Login button Click:
- public void Login_Click(object sender, RoutedEventArgs e)
- {
- if (UserName.Text != "" && PassWord.Password != "")
- {
- int Temp = 0;
- foreach (var UserLogin in ObjUserDataList)
- {
- if (UserName.Text == UserLogin.UserName && PassWord.Password == UserLogin.Password)
- {
- Temp = 1;
- var Settings = IsolatedStorageSettings.ApplicationSettings;
- Settings["CheckLogin"] = "Login sucess";//write iso
- if (ISOFile.FileExists("CurrentLoginUserDetails"))
- {
- ISOFile.DeleteFile("CurrentLoginUserDetails");
- }
- using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("CurrentLoginUserDetails", FileMode.Create))
- {
- DataContractSerializer serializer = new DataContractSerializer(typeof(UserData));
- serializer.WriteObject(fileStream, UserLogin);
- }
- NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));
- }
- }
- if (Temp == 0)
- {
- MessageBox.Show("Invalid UserID/Password");
- }
- }
- else
- {
- MessageBox.Show("Enter UserID/Password");
- }
- }
Here after successful login, I am storing the current login user details in Isolated Storage file name is 'CurrentLoginUserDetails'. So that i can able to read current login user details from this file to show the details in 'UserDetails' page like this:
- private void UserDetailsPage_Loaded(object sender, RoutedEventArgs e)
- {
- if (ISOFile.FileExists("CurrentLoginUserDetails"))//read current user login details
- {
- using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("CurrentLoginUserDetails", FileMode.Open))
- {
- DataContractSerializer serializer = new DataContractSerializer(typeof(UserData));
- ObjUserData = (UserData)serializer.ReadObject(fileStream);
- }
- StckUserDetailsUI.DataContext = ObjUserData;//Bind current login user details to UI
- }
- }
And xaml code in UserDetails.xaml page like this:
- <!--LayoutRoot is the root grid where all page content is placed-->
- <Grid x:Name="LayoutRoot" Background="LightGray">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="Auto"/>
- </Grid.RowDefinitions>
- <Grid Grid.Row="0" Background="White">
- <TextBlock Text="User details:" Margin="0,10,0,20" HorizontalAlignment="Center" FontSize="30" Foreground="Black" />
- <Image Stretch="None" HorizontalAlignment="Right" Source="/Images/SignOut.jpg" Width="51" Tap="ImgSignOut_Tap"/>
- </Grid>
- <!--ContentPanel - place additional content here-->
- <Grid x:Name="ContentPanel" Grid.Row="1" Margin="2">
- <StackPanel Name="StckUserDetailsUI" Grid.Row="0" Margin="12,17,0,28">
- <TextBlock Name="TxtUserName" Text="{Binding UserName}" Foreground="Black"/>
- <TextBlock Name="TxtAddress" Text="{Binding Address}" Foreground="Black"/>
- <TextBlock Name="TxtGender" Text="{Binding Gender}" Foreground="Black"/>
- <TextBlock Name="TxtPhoneNo" Text="{Binding PhoneNo}" Foreground="Black"/>
- <TextBlock Name="TxtEmaiID" Text="{Binding Email}" Foreground="Black"/>
- </StackPanel>
- </Grid>
- </Grid>
Step 5 : Logout from the application
Normally in login applications, when user already login with our app and on next app launch we need to directly showing the user details page instead of showing login page until signout from the application.
And it is very simple to implement this functionality. Just take one isolated variable(i.e CheckLogin) and store some temporary value when user successfully login with his details, so on next app launch we need to check 'CheckLogin' variable value. If it is having value means user already logined. So our app directly need to show user details instead of loginpage until logout . And when user pressing on 'Logout/Signout' button we need to remove isolated variable value(i.e CheckLogin) so on next app launch this variable value will be empty and our app need to show LoginPage.
On SignOut tap event : remove 'CheckLogin' isolated variable value
- private void ImgSignOut_Tap(object sender, System.Windows.Input.GestureEventArgs e)
- {
- SignOut();
- }
- public void SignOut()
- {
- var Result = MessageBox.Show("Are you sure you want to signout from this page?", "", MessageBoxButton.OKCancel);
- if (Result == MessageBoxResult.OK)
- {
- var Settings = IsolatedStorageSettings.ApplicationSettings;
- Settings.Remove("CheckLogin");
- NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
- }
- }
On next app launch :
- private void LoginPage_Loaded(object sender, RoutedEventArgs e)
- {
- var Settings = IsolatedStorageSettings.ApplicationSettings;
- //Check if user already login,so we need to direclty navigate to details page instead of showing login page when user launch the app.
- if (Settings.Contains("CheckLogin"))
- {
- NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));
- }
- else
- {
- NavigationService.Navigate(new Uri("/ViewsLoginPage.xaml", UriKind.Relative));
- }
- }
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
how can Download
ReplyDeleteThank you for sharing. This will help me set up the Affordable windows tablet
ReplyDeletethat I bought. I'm very new to windows phone so this will help me to navigate my phone.
Hi!
ReplyDeleteCan you share the code for ListData.cs & UserData.cs
Hello Subbu, I am a head of smartphone applications development. You have done a fantastic job especially for young developers.
ReplyDeletePlease provide the code download link and I have a question whether this code will work for windows 8.1 apps or not?
ReplyDeletePlease provide the code download link and I have a question whether this code will work for windows 8.1 apps or not?
ReplyDeleteThanks a lot for sharing.. Really very helpful and easy to understand.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI am Getting this error while i Deserialize the data from isolated Storage.....
ReplyDeleteError in Following line...
ObjUserData = (UsertData)serilazer.ReadObject(fileStream);
An exception of type 'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.ni.dll but was not handled in user code
Additional information: Error in line 1 position 2. Expecting element 'UsertData' from namespace 'http://schemas.datacontract.org/2004/07/LoginApp.Model'.. Encountered 'Element' with name 'ArrayOfUsertData', namespace 'http://schemas.datacontract.org/2004/07/LoginApp.Model'.
Please send me the reason
Hi subramanyamraju
ReplyDeletecan u please provide code for login & registration calling with API
I try to run in windows10 but it showing parameter is in correct
Deleteyes showing incorrect
DeleteInteresting and useful information that you have provided here on your post.
ReplyDeleteBelfast SEO Companies & iPhone Game Development Belfast UK
Hi, where we can download the code?
ReplyDeleteI try to run in windows10 but it showing parameter is in correct
ReplyDeleteDelete
thank you so much sir
ReplyDeletethank u so much sir for posting this wonderfull example of windows phone for fresher thank you
ReplyDeleteDude, how are you getting the button fits the parent stackpanel width? For me it just wraps!
ReplyDeleteThe type or name UserData could not be found....
ReplyDeleteplease help me to solve this,,,,
You have to add UserData class in Model folder. Download source code from https://code.msdn.microsoft.com/windowsapps/Windows-Phone-Login-17725566/sourcecode?fileId=134666&pathId=1541052689
DeleteGreat website to read meaningful comments, that will be useful.
ReplyDeleteBuy Mobile Cases
I am actually thankful to the owner of this web site who has shared this fantastic post at here.
ReplyDeleteMobile App Development Company
Travel Application Development Company
nice blog has been shared by you.before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blog.
ReplyDeletexamarin development company
hire xamarin developer india
That is some extraordinary information on baby gender calculator uses that I did not know. Though I have heard a lot about it but still could not figure it out. I am planning on using it. Hoping for the best.
ReplyDelete