Tuesday, September 5, 2017

Using .net Standard 2.0 with Xamarin Forms

Standard Libraries are replacing Portable Class Libraries.  Here is how to start using them in Xamarin Forms projects today.

To Start with create a new Xamarin forms app that uses a Portable Class Library

Since UWP will nor support .net Standard Libraries for a few months I would press cancel if you get the dialog asking what version of UWP you want to support.

Right click on the solution and select add new project.  Add a class library (.net standard)

Now drag the files App.Xaml and MainPage.Xaml from the PCL to the new class library.  You can also delete the file Class1.cs in the standard library we  created.

Open the properties for the Standard class library and change the default namespace to be the same as the portable class libraries

Time to add a NuGet package to the standard class library.  Microsoft.NetCore.Portability.Compatibility.  This will help prevent some build errors

Remove the portable class library from the solution.  Right click on the solution and select mange NuGet packages for the solution.  Select Updates and find Xamarin Forms.  Select the latest pre release and make sure the standard library is checked.  The latest prerelease supports standard libraries

Right click on the standard class library and select edit csproj.  Remove the following lines from the file.

    <EmbeddedResource Include="App.xaml">
    <EmbeddedResource Include="MainPage.xaml">

Save the file and add a reference in the android and ios project to the new standard library

Now you can run it

Here is what it looks like in the android emulator

In the next post in this series we will call a web service and save the json we get back to a file on the device.

Sunday, September 3, 2017

Client NoSql DB

I have used the NoSql database Lex.DB in some of my mobile apps in the past.  The DB was actually very handy and it worked on Xamarin.iOS, Xamarin.Android, Windows phone 8+, UWP,  PCL, Silverlight, and WinRT+.  I am in the process of converting the project to a standard library 2.0 that you can use with net core, Xamarin, UWP when the fall creators update comes out in Oct 2017, and .net 4.6.1

My hope is to get the Database so it can be used in windows, linux, mac, xamarin, or UWP apps.  This database is meant to be used with an app not as a server based NoSql database.

The code is currently in GitHub please report any bugs or feature requests there. Send me an email if you want to contribute to the project


Sunday, August 27, 2017

Using Entityframework core 2.0 with xamarin for android

In this post we are going to use the entity framework core 2.0 with a Xamarin for Android project

I am using Visual Studio 2017 (version 15.3)

I also installed .Net Core 2.0 from https://dot.net

Once you have dot net core 2.0 installed which includes .net standard 2.0 lets start by creating a new Xamarin.Android project

First Create a Blank Xamarin for Android app

Once that is added right click on the project and select Manage NuGet Package

Add the package microsoft.entityframeworkcore.sqlite

Add the package and you will see it installs a few extra packages with it.  After it is installed I will update any packages that have updates available.

Lets add a Entities Folder to the android solution and create 2 code files Monkey.cs and MonkeyContext.cs

Monkey class

public class Monkey
public int id { get; set; }
public string monkeyType { get; set; }

MonkeyContext class

    public class MonkeyContext : DbContext
        private string DatabasePath { get; set; }
        public MonkeyContext(string databasePath)
           DatabasePath = databasePath;
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

        public DbSet<Monkey> Monkeys {get;set;}

In the MainActivity  change the code in MainActivity to this. The code will create the database and add 5 monkeys to the database if there are not any records.  I also changed the MainActivity to inherit from ListActivity so it show the items in the database is a list

   public class MainActivity : ListActivity
        MonkeyAdapter adapter;

        protected override async void OnCreate(Bundle savedInstanceState)
            List<Monkey> lst = null;
            string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "monkeys.db");
            using (var db = new MonkeyContext(path))
                await db.Database.EnsureCreatedAsync();
                if (!db.Monkeys.Any())
                    db.Monkeys.Add(new Monkey { monkeyType = "Squirrel Monkey" });
                    db.Monkeys.Add(new Monkey { monkeyType = "Spider Monkey" });
                    db.Monkeys.Add(new Monkey { monkeyType = "Golden Lion Tamarin" });
                    db.Monkeys.Add(new Monkey { monkeyType = "Howler Monkey" });
                    db.Monkeys.Add(new Monkey { monkeyType = "Owl or Night Monkey" });
                    await db.SaveChangesAsync();
                lst = db.Monkeys.ToList();

            adapter = new MonkeyAdapter(this, lst);
            ListAdapter = adapter;

The code for MonkeyAdapter.   This code is needed to show the data in a list

   public class MonkeyAdapter : BaseAdapter<Monkey>
        private readonly List<Monkey> data;
        private readonly Activity context;
        public MonkeyAdapter(Activity activity, IEnumerable<Monkey> monkeys)
            data = monkeys.OrderBy(s => s.id).ToList();
            context = activity;

        public override long GetItemId(int position)
            return position;

        public override Monkey this[int position]
            get { return data[position]; }

        public override int Count
            get { return data.Count; }

        public override View GetView(int position, View convertView, ViewGroup parent)
           var view = convertView;
           if (view == null)
                view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);

            var monkey = data[position];
            var text = view.FindViewById<TextView>(Android.Resource.Id.Text1);
            text.Text = monkey.monkeyType;
            return view;

Once you run the project it will add a few items to the database and show them in a list view

You can download  a sample from my CodeImpact demo at GitHub


Code Impact 2017

I spoke at the 2017 Code Impact in Jacksonville Florida on Aug 26.    The sample code and power point for my talk on Use .Net Standard with Xamarin forms can be found on my Git Hub repo.


Wednesday, March 8, 2017

VS 2017 setup the product definitions failed to load

I tried to upgrade my Visual Studio 2017 RC to the release version and got an error product definitions failed to load

The way I got the installer to work was to delete the folder  %LocalAppData%\Microsoft\VisualStudio\Packages\ 

After that running the installer I was able to update my install to the released version

Sunday, March 5, 2017

Cloning an Object in an PCL

Here is an example on how to clone an object in a portable class library

I am using Json.net to help.  Add the Json.Net nuget package to any project in the solution that uses the PCL

Then you an serialize the object into Json and then deserialize it right away to create a clone of a object

        public T CloneObject<T>(T toBeCloned)
            T clone = default(T);
            string serialized = JsonConvert.SerializeObject(toBeCloned);
            clone = JsonConvert.DeserializeObject<T>(serialized);
            return clone;

Sunday, February 26, 2017

Visual Studio 2017 live unit tests

I was experimenting today with VS 2017 live unit testing. I really like them a lot. I wish they were available in all editions of VS  2017 not just enterprise.

I started with a simple console app.  Which adds 2 numbers.

   public class Program
        static void Main(string[] args)
            Console.Write("1 + 1 = ");
            Console.WriteLine("Press any key to continue");
        public static int Add2Numbers(int x,int y)
            return x * y;

Then I added a Unit Test project. I added a project reference to my ConsoleApp

Here is the tests I added.

Namespace UnitTestProject1
    public class UnitTest1
        public void TestMethod1()
            int x = 1;
            int y = 1;
            int expected = 2;
            Assert.AreEqual(expected, ConsoleApp1.Program.Add2Numbers(x, y));

Then I build the project and ran the test.  As you can see the test failed. 

Lets turn on the Live Unit Tests in Visual Studio's Options.  There is a section for it.

Right click on the solution in the solution explorer and select Live Tests and select include.

Here is what you will see.

Now if we update the code. We  will see it goes to passing

        public static int Add2Numbers(int x,int y)
            return x + y;

Very useful feature.