Showing posts with label Xamarin. Show all posts
Showing posts with label Xamarin. Show all posts

Sunday, 11 October 2015

Using Xamarin.forms store value in Keystore (android) and Keychain (iOS)

This time I am going to share how I have used Platform Service  to store UserName and Password with Xamarin.forms. It will be quite a simple implementation as we will using Xamarin.Auth package.

First create a new Xamarin.forms application using pcl. I always prefer using pcl in my projects :).

In you pcl create a new interface as shown below:


public interface ILoginStoreService

    {

        void SaveLogin (string userName, string password);
        string GetUserName ();
        string GetPassword ();
        bool LoginExists ();

  }  


Then in your iOS project add Xamarin.Auth package. After that inside the same iOS project create a new Class inheriting the interface defined in the pcl project.

[assembly: Dependency(typeof(LoginStoreIOS))]
namespace HealthGateway.iOS
{   
        public class LoginStoreIOS        
            :ILoginStoreService    
       {        
                public void SaveLogin (string userName, string password)        
               {            
                        if (!string.IsNullOrEmpty (userName) && !string.IsNullOrEmpty (password)) 
                        {               
                                  Account user = new Account { Username = userName };                
                                  user.Properties.Add ("Key", password);                
                                 AccountStore.Create ().Save (user, "Shribits");            
                        }        
              }      
             public string GetPassword ()       
            {            
                       var account = AccountStore.Create ().FindAccountsForService ("Shribits").Last();           
                       return account.Properties["Key"];        
            }
            public bool LoginExists ()        
          {            
                    if(AccountStore.Create ().FindAccountsForService ("Shribits").Count() > 0)               
                             return true;            
                    else                
                             return false;        
           }       
           public string GetUserName ()        
           {            
                   var account = AccountStore.Create ().FindAccountsForService ("Shribits").Last();            
                  return account.Username;        
           }    
    }
}  

Similarly for android follow the same steps create a new Class inheriting the interface defined in your pcl and also add the Xamarin.Auth package to your solution.

The example of implementation is below:


[assembly: Dependency(typeof(LoginStoreDroid))]

namespace HealthGateway.Droid

{
    public class LoginStoreDroid
        :ILoginStoreService
    {
        public void SaveLogin (string userName, string password)
        {
            if (!string.IsNullOrEmpty (userName) && !string.IsNullOrEmpty (password)) {
                Account user = new Account { Username = userName };
                user.Properties.Add ("Key", password);
                AccountStore.Create (MainActivity.Instance.BaseContext).Save (user, "Shribits");
            }
        }
        public string GetPassword ()
        {
            var account = AccountStore.Create (MainActivity.Instance.BaseContext).FindAccountsForService ("Gateway").Last();
            return account.Properties["Key"];
        }
        public bool LoginExists ()
        {
            if(AccountStore.Create (MainActivity.Instance.BaseContext).FindAccountsForService ("Shribits").Count()>0)
                return true;
            else
                return false;
        }
        public string GetUserName ()
        {
            var account = AccountStore.Create (MainActivity.Instance.BaseContext).FindAccountsForService ("Gateway").Last();
            return account.Username;
        }
    }
}




Now you are good to go ahead with your implementation cross platform level. Below is the example of how to make the call :

DependencyService.Get<ILoginStoreService> ().LoginExists ()  

For more information on how to implement Dependency Service please https://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/

Add in your comments and questions. Also let me know if you would like to cover any topic.

Saturday, 19 September 2015

How to create custom viewcell in ListView - Xamarin.forms


Here I will be showing a few tricks I have used to make dynamic viewcell in Listview and a easy way to make your ux designer happy ;).
I will do a small walk through the code and explain the logic behind it. This project is also available in Github. I have shared the link below.
Primarily I have extended xamarin.forms ListView binding capability and created a CustomListView class to have a new property called TemplateSelector of type IDataTemplateSelector.

Screen Shot 2015-09-20 at 3.24.50 pm

Screen Shot 2015-09-20 at 3.19.41 pm

DataTemplateSelector class has all the different DataTemplateTypes Defined in it. Highlighted function SelectTemplate takes each viewcell viewmodel type and converts them to Template.  

Screen Shot 2015-09-20 at 3.20.50 pm


I have a DummyModel with properties Name, ContactNo , ProfileImage and TemplateType. In my DummyViewModel I have added a few DummyModel objects to List<DummyModel> DummyModelSet.

To bind the ItemSource of the ListView we have created a BaseCellViewModel and added the properties  Name, ContactNo and ProfileImage only. For binding we don't need the TemplateType anymore. Inheriting BaseCellViewModel we have three other view model for three different template (RightImageCellViewModel, LeftImageCellViewModel, CenterImageCellViewModel). 

Screen Shot 2015-09-20 at 3.09.52 pm


Finally we have reached the view part. In our DummyPage will define the our CustomListView as below with the TemplateSelector property:

Screen Shot 2015-09-20 at 3.35.42 pm


https://github.com

Happy Coding!!!

Shri

Wednesday, 29 October 2014

IOS 8 : Restricting orientation on a View Controller

In my recent xamarin project (iOS 8 app) one of the requirement was to restrict the orientation at ViewController level. There had been lot of changes from the apple side related to screen orientation.
  • In iOS 4, it was possible to force app rotation when changing view controllers in a tab bar controller and a navigation controller, as well as when presenting/dismissing a controller.
  • Then in iOS 6 it became impossible to force app rotation except when presenting/dismissing a view controller.
  • Now, in iOS 8, it is impossible to force app rotation at all (except at launch). It can prefer a certain orientation, so that once it is in that orientation it will stay there, but it cannot force the app to go into that orientation.
    Instead, your view controller is expected to "adapt". There are several WWDC 2014 videos concentrating on "adaptation", and now I'm starting to understand that this is one reason why this is so important.
Workaround to restrict the orietation
Xamarin:

Step 1:
In info.plist unselect all the orientation as shown in the image below:




Step 2:
In AppDelegate.cs:

Define a boolean type variable to assign the value of each ViewController Orientation type.

public partial class AppDelegate : ApplicationDelegate
{
public bool RestrictRotation {
            get;
            set ;
     }
}
        }
  
also add the function bellow to get the supported orientation type at run time.

Export ("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, IntPtr forWindow)
{
     if (this.RestrictRotation)
         return UIInterfaceOrientationMask.Portrait;
     else
         return UIInterfaceOrientationMask.All;
}
  

Step 3:

In ViewController add the following code:

a) For Portrait view:

i) Inside ViewDidLoad:
The following code will return true to the AppDelegate -> GetSupportedInterfaceOrientations. This will enable to get the UIInterfaceOrienntationMask to Portrait.

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    this.RestrictRotation(true);
  

ii) Add the functions below to the View Controller.

public override bool ShouldAutorotate()
{
     return false;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations ()
{
     return UIInterfaceOrientationMask.Portrait;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation ()
{
      return UIInterfaceOrientation.Portrait;
}

void RestrictRotation(bool restriction)
{
AppDelegate app =(AppDelegate)UIApplication.SharedApplication.Delegate;
            app.RestrictRotation = restriction;
}
  

b) For Landscape and Portrait view:
i) Inside ViewDidLoad:
The following code will return true to the AppDelegate -> GetSupportedInterfaceOrientations. This will enable to get the UIInterfaceOrienntationMask to Portrait and Landscape.

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    this.RestrictRotation(false);
  

ii) Add the functions below to the View Controller.

public override bool ShouldAutorotate()
{
     return false;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations ()
{
     return UIInterfaceOrientationMask.Portrait;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation ()
{
      return UIInterfaceOrientation.Portrait;
}

void RestrictRotation(bool restriction)
{
AppDelegate app =(AppDelegate)UIApplication.SharedApplication.Delegate;
            app.RestrictRotation = restriction;
}
  

Image:

View 1:

Portrait Only:




View 2:

Portrait and Landscape:



Please pick up the code example from github...

Enjoy coding!!!