Google Windows Phone : Login application sample, beginners tutorials (C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Friday, 6 March 2015

Windows Phone : Login application sample, beginners tutorials (C#-XAML)

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 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:
Now create LoginPage on Views folder,and in designing part create login form with following xaml code.

  1. <!--LayoutRoot is the root grid where all page content is placed-->  
  2.    <Grid x:Name="LayoutRoot" Background="White">  
  3.        <Grid.RowDefinitions>  
  4.            <RowDefinition Height="Auto"/>  
  5.            <RowDefinition Height="*"/>  
  6.        </Grid.RowDefinitions>          
  7.        <StackPanel Grid.Row="0" Margin="12,17,0,28">  
  8.            <!--Title-->  
  9.            <TextBlock Text="Login Page" Foreground="Black" FontSize="40"/>              
  10.             
  11.            <!--UserName-->  
  12.            <TextBlock Text="UserID" Foreground="Black" FontSize="30"/>  
  13.            <TextBox  BorderBrush="LightGray" Name="UserName" GotFocus="UserName_GotFocus"/>  
  14.              
  15.            <!--Password-->  
  16.            <TextBlock  Foreground="Black" Text="Password" Margin="9,-7,0,0" FontSize="30"/>  
  17.            <PasswordBox BorderBrush="LightGray" Name="PassWord" GotFocus="UserName_GotFocus" />  
  18.              
  19.            <!--Login Button-->  
  20.            <Button Content="Login" Background="#FF30DABB" Name="Login" Click="Login_Click" />  
  21.              
  22.            <!--  Registration Button-->  
  23.            <Button Content="Registration" Background="#FF30DABB" Name="SignUp" Click="SignUp_Click"/>  
  24.             
  25.        </StackPanel>  
  26.          
  27.    </Grid>  

so your phone looks like:

In LoginPage.xaml.cs, write following code

  1. public void Login_Click(object sender, RoutedEventArgs e)  
  2.        {  
  3.            //Will explain it later  
  4.        }  
  5.         
  6.         
  7.        public void SignUp_Click(object sender, RoutedEventArgs e)  
  8.        {  
  9.            NavigationService.Navigate(new Uri("/Views/SignUpPage.xaml", UriKind.Relative));  
  10.        } 

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.


  1. <!--LayoutRoot is the root grid where all page content is placed-->  
  2.    <Grid x:Name="LayoutRoot" Background="White">  
  3.      <Grid Margin="5,0,0,0">  
  4.        <Grid.RowDefinitions>  
  5.            <RowDefinition Height="Auto"/>  
  6.            <RowDefinition Height="Auto"/>  
  7.            <RowDefinition Height="Auto"/>  
  8.            <RowDefinition Height="Auto"/>  
  9.            <RowDefinition Height="Auto"/>  
  10.            <RowDefinition Height="Auto"/>  
  11.            <RowDefinition Height="Auto"/>  
  12.            <RowDefinition Height="Auto"/>  
  13.        </Grid.RowDefinitions>  
  14.            <!--Title-->  
  15.            <TextBlock Text="User Registration :" Grid.Row="0" FontSize="40"  Foreground="Black"/>  
  16.                
  17.            <!--UserName-->  
  18.            <TextBlock Text="UserName :" Grid.Row="1" Foreground="Black"   Margin="0,25,0,0"/>  
  19.            <TextBox Name="TxtUserName" BorderBrush="LightGray" Grid.Row="1" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>  
  20.   
  21.            <!--Password-->  
  22.            <TextBlock Text="Password: " Grid.Row="2" Margin="0,25,0,0" Foreground="Black" />  
  23.            <PasswordBox Name="TxtPwd" BorderBrush="LightGray" Grid.Row="2" Margin="100,0,0,0" GotFocus="pwd_GotFocus" />  
  24.   
  25.            <!--Address-->  
  26.            <TextBlock Text="Address: " Grid.Row="3" Margin="0,25,0,0" Foreground="Black" />  
  27.            <TextBox Name="TxtAddr" BorderBrush="LightGray" Grid.Row="3" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>  
  28.   
  29.            <!--Gender-->  
  30.            <TextBlock Text="Gender: " Grid.Row="4" Margin="0,25,0,0" Foreground="Black" />  
  31.            <RadioButton Name="GenMale" Background="LightGray" Content="Male" Grid.Row="4" Margin="100,0,0,0" Foreground="Black" />  
  32.            <RadioButton Name="GenFeMale"  Background="LightGray" Content="Female" Grid.Row="4" Margin="200,0,0,0" Foreground="Black" />  
  33.   
  34.            <!--Phone Number-->  
  35.            <TextBlock Text="Phone No: " Grid.Row="5" Margin="0,25,0,0" Foreground="Black" />  
  36.            <TextBox Name="TxtPhNo" BorderBrush="LightGray" MaxLength="10"  InputScope="digits" Grid.Row="5" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>  
  37.   
  38.            <!--Email-->  
  39.            <TextBlock Text="EmaiID: " Grid.Row="6" Margin="0,25,0,0" Foreground="Black" />  
  40.            <TextBox Name="TxtEmail" BorderBrush="LightGray" Grid.Row="6" Margin="100,0,0,0" GotFocus="Txt_GotFocus"/>  
  41.   
  42.            <!--Submit Button-->  
  43.            <Button BorderBrush="Transparent"  Background="#FF30DABB" Content="Submit"  Name="BtnSubmit" Click="Submit_Click" Grid.Row="7"/>  
  44.          
  45.        </Grid>  
  46.    </Grid>  
so your phone looks like:

In SignUpPage.xaml.cs, write following code and it is for validating user details to successful registration.


  1. IsolatedStorageFile ISOFile = IsolatedStorageFile.GetUserStoreForApplication();  
  2.         private void Submit_Click(object sender, RoutedEventArgs e)  
  3.         {  
  4.             //UserName Validation  
  5.             if (!Regex.IsMatch(TxtUserName.Text.Trim(), @"^[A-Za-z_][a-zA-Z0-9_\s]*$"))  
  6.             {  
  7.                 MessageBox.Show("Invalid UserName");  
  8.             }  
  9.   
  10.             //Password length Validation  
  11.             else if (TxtPwd.Password.Length < 6)  
  12.             {  
  13.                 MessageBox.Show("Password length should be minimum of 6 characters!");  
  14.             }  
  15.   
  16.             //Address Text Empty Validation  
  17.             else if (TxtAddr.Text == "")  
  18.             {  
  19.                 MessageBox.Show("Please enter your address!");  
  20.             }  
  21.   
  22.             //Gender Selection Empty Validation  
  23.             else if (gender == "")  
  24.             {  
  25.                 MessageBox.Show("Please select gender!");  
  26.             }  
  27.   
  28.             //Phone Number Length Validation  
  29.             else if (TxtPhNo.Text.Length != 10)  
  30.             {  
  31.                 MessageBox.Show("Invalid PhonNo");  
  32.             }  
  33.   
  34.             //EmailID validation  
  35.             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])\])$"))  
  36.             {  
  37.                 MessageBox.Show("Invalid EmailId");  
  38.             }  
  39.   
  40.            //After validation success ,store user detials in isolated storage  
  41.             else if (TxtUserName.Text != "" && TxtPwd.Password != "" && TxtAddr.Text != "" && TxtEmail.Text != "" && gender != "" && TxtPhNo.Text != "")  
  42.             {  
  43.                 UserData ObjUserData = new UserData();  
  44.                 ObjUserData.UserName = TxtUserName.Text;  
  45.                 ObjUserData.Password = TxtPwd.Password;  
  46.                 ObjUserData.Address = TxtAddr.Text;  
  47.                 ObjUserData.Email = TxtEmail.Text;  
  48.                 ObjUserData.Gender = gender;  
  49.                 ObjUserData.PhoneNo = TxtPhNo.Text;  
  50.                 int Temp = 0;  
  51.                 foreach (var UserLogin in ObjUserDataList)  
  52.                 {  
  53.                     if (ObjUserData.UserName == UserLogin.UserName)  
  54.                     {  
  55.                         Temp = 1;  
  56.                     }  
  57.                 }  
  58.                 //Checking existing user names in local DB  
  59.                 if (Temp == 0)  
  60.                 {  
  61.                     ObjUserDataList.Add(ObjUserData);  
  62.                     if (ISOFile.FileExists("RegistrationDetails"))  
  63.                     {  
  64.                         ISOFile.DeleteFile("RegistrationDetails");  
  65.                     }  
  66.                     using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("RegistrationDetails", FileMode.Create))  
  67.                     {  
  68.                         DataContractSerializer serializer = new DataContractSerializer(typeof(List<UserData>));  
  69.   
  70.                         serializer.WriteObject(fileStream, ObjUserDataList);  
  71.   
  72.                     }  
  73.                     MessageBox.Show("Congrats! your have successfully Registered.");  
  74.                     NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));  
  75.                 }  
  76.                 else  
  77.                 {  
  78.                     MessageBox.Show("Sorry! user name is already existed.");  
  79.                 }  
  80.   
  81.             }  
  82.             else  
  83.             {  
  84.                 MessageBox.Show("Please enter all details");  
  85.             }  
  86.         }  
After successfully user registration, i saved user details in IsolatedStorageFile name is 'RegistrationDetails'. So that every user details list can be stored in this file.

Step 4 : How to get login user 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


  1. private void LoginPage_Loaded(object sender, RoutedEventArgs e)  
  2.         {  
  3.             var Settings = IsolatedStorageSettings.ApplicationSettings;  
  4.             //Check if user already login,so we need to direclty navigate to details page instead of showing login page when user launch the app.  
  5.             if (Settings.Contains("CheckLogin"))  
  6.             {  
  7.                 NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));  
  8.             }  
  9.             else  
  10.             {  
  11.                 if (ISOFile.FileExists("RegistrationDetails"))//loaded previous items into list  
  12.                 {  
  13.                     using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("RegistrationDetails", FileMode.Open))  
  14.                     {  
  15.                         DataContractSerializer serializer = new DataContractSerializer(typeof(List<UserData>));  
  16.                         ObjUserDataList = (List<UserData>)serializer.ReadObject(fileStream);  
  17.   
  18.                     }  
  19.                 }  
  20.             }  
  21.              
  22.         } 

On Login button Click:


  1. public void Login_Click(object sender, RoutedEventArgs e)    
  2.         {    
  3.             if (UserName.Text != "" && PassWord.Password != "")    
  4.             {    
  5.                 int Temp = 0;    
  6.                 foreach (var UserLogin in ObjUserDataList)    
  7.                 {    
  8.                     if (UserName.Text == UserLogin.UserName && PassWord.Password == UserLogin.Password)    
  9.                     {    
  10.                         Temp = 1;    
  11.                         var Settings = IsolatedStorageSettings.ApplicationSettings;    
  12.                         Settings["CheckLogin"] = "Login sucess";//write iso    
  13.     
  14.                         if (ISOFile.FileExists("CurrentLoginUserDetails"))    
  15.                         {    
  16.                             ISOFile.DeleteFile("CurrentLoginUserDetails");    
  17.                         }    
  18.                         using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("CurrentLoginUserDetails", FileMode.Create))    
  19.                         {    
  20.                             DataContractSerializer serializer = new DataContractSerializer(typeof(UserData));    
  21.     
  22.                             serializer.WriteObject(fileStream, UserLogin);    
  23.     
  24.                         }    
  25.                         NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));    
  26.                     }    
  27.                 }    
  28.                 if (Temp == 0)    
  29.                 {    
  30.                     MessageBox.Show("Invalid UserID/Password");    
  31.                 }    
  32.             }    
  33.             else    
  34.             {    
  35.                 MessageBox.Show("Enter UserID/Password");    
  36.             }    
  37.         }  

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:


  1. private void UserDetailsPage_Loaded(object sender, RoutedEventArgs e)  
  2.        {  
  3.            if (ISOFile.FileExists("CurrentLoginUserDetails"))//read current user login details    
  4.            {  
  5.                using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("CurrentLoginUserDetails", FileMode.Open))  
  6.                {  
  7.                    DataContractSerializer serializer = new DataContractSerializer(typeof(UserData));  
  8.                    ObjUserData = (UserData)serializer.ReadObject(fileStream);  
  9.   
  10.                }  
  11.              StckUserDetailsUI.DataContext = ObjUserData;//Bind current login user details to UI  
  12.            }  
  13.        }  


And xaml code in UserDetails.xaml page like this:


  1. <!--LayoutRoot is the root grid where all page content is placed-->  
  2.    <Grid x:Name="LayoutRoot" Background="LightGray">  
  3.        <Grid.RowDefinitions>  
  4.            <RowDefinition Height="Auto"/>  
  5.            <RowDefinition Height="Auto"/>  
  6.            <RowDefinition Height="Auto"/>  
  7.            <RowDefinition Height="Auto"/>  
  8.        </Grid.RowDefinitions>  
  9.        <Grid  Grid.Row="0" Background="White">  
  10.            <TextBlock Text="User details:" Margin="0,10,0,20" HorizontalAlignment="Center" FontSize="30" Foreground="Black" />  
  11.            <Image Stretch="None" HorizontalAlignment="Right" Source="/Images/SignOut.jpg" Width="51" Tap="ImgSignOut_Tap"/>  
  12.        </Grid>  
  13.        <!--ContentPanel - place additional content here-->  
  14.        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="2">  
  15.           <StackPanel  Name="StckUserDetailsUI"  Grid.Row="0" Margin="12,17,0,28">  
  16.                <TextBlock Name="TxtUserName" Text="{Binding UserName}" Foreground="Black"/>  
  17.                <TextBlock Name="TxtAddress" Text="{Binding Address}" Foreground="Black"/>  
  18.                <TextBlock Name="TxtGender" Text="{Binding Gender}" Foreground="Black"/>  
  19.                <TextBlock Name="TxtPhoneNo" Text="{Binding PhoneNo}" Foreground="Black"/>  
  20.                <TextBlock Name="TxtEmaiID" Text="{Binding Email}" Foreground="Black"/>  
  21.            </StackPanel>  
  22.        </Grid>  
  23.    </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


  1. private void ImgSignOut_Tap(object sender, System.Windows.Input.GestureEventArgs e)  
  2.        {  
  3.            SignOut();  
  4.        }  
  5.        public void SignOut()  
  6.        {  
  7.            var Result = MessageBox.Show("Are you sure you want to signout from this page?""", MessageBoxButton.OKCancel);  
  8.            if (Result == MessageBoxResult.OK)  
  9.            {  
  10.                var Settings = IsolatedStorageSettings.ApplicationSettings;  
  11.                Settings.Remove("CheckLogin");  
  12.                NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));  
  13.            }  
  14.        } 

On next app launch :


  1. private void LoginPage_Loaded(object sender, RoutedEventArgs e)  
  2.         {  
  3.             var Settings = IsolatedStorageSettings.ApplicationSettings;  
  4.             //Check if user already login,so we need to direclty navigate to details page instead of showing login page when user launch the app.  
  5.             if (Settings.Contains("CheckLogin"))  
  6.             {  
  7.                 NavigationService.Navigate(new Uri("/Views/UserDetails.xaml", UriKind.Relative));  
  8.             }  
  9.             else  
  10.             {  
  11.                 NavigationService.Navigate(new Uri("/ViewsLoginPage.xaml", UriKind.Relative));  
  12.             }  
  13.              
  14.         }  

LoginAppWP

FeedBack Note:
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  
Have a nice day by  :)

24 comments:

  1. Thank you for sharing. This will help me set up the Affordable windows tablet
    that I bought. I'm very new to windows phone so this will help me to navigate my phone.

    ReplyDelete
  2. Hi!
    Can you share the code for ListData.cs & UserData.cs

    ReplyDelete
  3. Hello Subbu, I am a head of smartphone applications development. You have done a fantastic job especially for young developers.

    ReplyDelete
  4. Please provide the code download link and I have a question whether this code will work for windows 8.1 apps or not?

    ReplyDelete
  5. Please provide the code download link and I have a question whether this code will work for windows 8.1 apps or not?

    ReplyDelete
  6. Thanks a lot for sharing.. Really very helpful and easy to understand.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. I am Getting this error while i Deserialize the data from isolated Storage.....

    Error 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

    ReplyDelete
  9. Hi subramanyamraju

    can u please provide code for login & registration calling with API

    ReplyDelete
    Replies
    1. I try to run in windows10 but it showing parameter is in correct

      Delete
  10. Interesting and useful information that you have provided here on your post.

    Belfast SEO Companies & iPhone Game Development Belfast UK

    ReplyDelete
  11. Hi, where we can download the code?

    ReplyDelete
  12. I try to run in windows10 but it showing parameter is in correct

    Delete

    ReplyDelete
  13. thank u so much sir for posting this wonderfull example of windows phone for fresher thank you

    ReplyDelete
  14. Dude, how are you getting the button fits the parent stackpanel width? For me it just wraps!

       
      

    ReplyDelete
  15. The type or name UserData could not be found....
    please help me to solve this,,,,

    ReplyDelete
    Replies
    1. 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

      Delete
  16. Great website to read meaningful comments, that will be useful.
    Buy Mobile Cases

    ReplyDelete
  17. I am actually thankful to the owner of this web site who has shared this fantastic post at here.
    Mobile App Development Company
    Travel Application Development Company

    ReplyDelete
  18. 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.
    xamarin development company
    hire xamarin developer india

    ReplyDelete
  19. 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

Search Engine Submission - AddMe