{"id":7839,"date":"2013-10-02T08:51:24","date_gmt":"2013-10-02T12:51:24","guid":{"rendered":"http:\/\/blog.xamarin.com\/?p=7839"},"modified":"2013-10-02T08:51:24","modified_gmt":"2013-10-02T12:51:24","slug":"porting-existing-net-apps-to-android","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/porting-existing-net-apps-to-android\/","title":{"rendered":"Porting existing .NET apps to Android"},"content":{"rendered":"<p dir=\"ltr\">Android&#8217;s growth to number one smartphone platform in terms of units shipped has resulted in a significant increase in interest from businesses and developers to ship applications that run natively on Android devices and that take advantage of features such as the camera and voice recognition. With Xamarin.Android, .NET developers have the ability to write native Android apps in C# using many of the existing .NET APIs that they are already familiar with, but what&#8217;s perhaps more attractive is the potential to share your existing .NET code to Android. \u00a0Almost any .NET codebase, including Windows Forms, WPF, ASP.NET, and Silverlight, has sharable code that can be ported to <a href=\"http:\/\/xamarin.com\/android\">Xamarin.Android<\/a>, <a href=\"http:\/\/xamarin.com\/ios\">Xamarin.iOS<\/a>, Windows Phone &amp; Windows Store.<\/p>\n<p dir=\"ltr\">In my previous blogpost on <a href=\"\/porting-existing-.net-apps-to-ios\/\">Porting Existing .NET apps to iOS<\/a>, we looked at a step-by-step approach in porting an existing Silverlight application <a href=\"http:\/\/www.silverlightshow.net\/items\/Exploring-the-Model-View-Controller-MVC-pattern.aspx\">Diet Calculator<\/a> to Xamarin.iOS. In this post I will take a similar approach to what we did in the iOS porting sample to build the same app for Android phones using Xamarin.Android.<\/p>\n<p dir=\"ltr\">Here\u2019s how the Silverlight sample looks:<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Silverlight-MVC.png\"><img decoding=\"async\" class=\"alignnone size-medium wp-image-7600\" alt=\"DietCalculator-Silverlight-MVC\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Silverlight-MVC.png\" width=\"506px;\" height=\"384px;\" \/><\/a><\/p>\n<p dir=\"ltr\">And here\u2019s how the ported application will look on an Android phone:<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android.png\"><img decoding=\"async\" class=\"alignnone  wp-image-7840\" alt=\"DietCalculator-Android\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android.png\" width=\"303\" height=\"507\" \/><\/a><\/p>\n<p dir=\"ltr\">You can download the code used in this post for the<a href=\"https:\/\/github.com\/nishanil\/DietCalculatorVS\"> Xamarin.Android DietCalculator sample from github<\/a>.<\/p>\n<h2>Scan your Code for Mobilization<\/h2>\n<p dir=\"ltr\"><a href=\"http:\/\/scan.xamarin.com\/\">Xamarin\u2019s .NET Mobility Scanner<\/a> can determine the amount of code sharing and re-use you can expect from an existing .NET app or library and provide a detailed road-map of remaining work required to mobilize it. The Mobility Scanner analyzes compiled .NET assemblies and compares the APIs used with the capabilities of each platform. Since we are porting a Silverlight app we can easily extract the Silverlight_MVC.dll from the .XAP and upload that to the Scanner.<\/p>\n<p dir=\"ltr\"><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-ScanReport.png\"><img decoding=\"async\" class=\"alignnone size-medium wp-image-7606\" alt=\"DietCalculator-ScanReport\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-ScanReport.png\" width=\"565px;\" height=\"274px;\" \/><\/a><\/p>\n<p dir=\"ltr\">We analyzed how mobile our Silverlight code is and concluded that 71% of the app code can be re-used. As per the <a href=\"http:\/\/scan.xamarin.com\/Home\/Report?scanId=edfa5d67-3e9d-4b28-b445-5de0a3b6d1e6\">detailed report<\/a>, all of the platform-specific method calls (i.e., code that we can\u2019t re-use across platforms) are user-interface specific and hence the business logic code that consists of Models, Controllers and Helpers from the Silverlight_MVC project can be re-used in our Xamarin.Android application! Now we are all set to build a Diet Calculator\u2019s User Interface native to the Android platform!<\/p>\n<h2>Separate Reusable Code into a Core Library<\/h2>\n<p dir=\"ltr\"><a href=\"\/porting-existing-.net-apps-to-ios\/\">When we set up our solution<\/a>, we followed the separation of responsibility principle and moved our Models, Controllers and Helpers from the Silverlight application to a core project called DietCalculator.Core and referred them using <a href=\"http:\/\/docs.xamarin.com\/guides\/cross-platform\/application_fundamentals\/building_cross_platform_applications\/sharing_code_options\">File Linking<\/a> on iOS and Silverlight projects. We will take the same approach and refer to these files from our Xamarin.Android project. Don\u2019t forget to check-out our detailed documentation on <a href=\"http:\/\/docs.xamarin.com\/guides\/cross-platform\/application_fundamentals\/building_cross_platform_applications\">Building Cross Platform Applications<\/a>.<\/p>\n<p dir=\"ltr\">Now that you\u2019ve got a fair idea about how we separated the business logic from the existing Silverlight_MVC project to a core project and referred them to iOS and Silverlight projects, let\u2019s create a Xamarin.Android project and re-use them there.<\/p>\n<h2>Adding Xamarin.Android project to Visual Studio solution<\/h2>\n<p dir=\"ltr\">Xamarin makes it possible for developers to use Visual Studio for Android &amp; iOS Development: you can access your Android, iOS, Windows Phone &amp; Windows Store app projects from one solution, code in on programming language, with one IDE.<\/p>\n<p dir=\"ltr\">To create a new Android project in Visual Studio:<\/p>\n<ul>\n<li>\n<p dir=\"ltr\">File &gt; New &gt; New Project &gt; Visual C# &gt; Android &gt; Android Application (DietCalculator.Droid)<\/p>\n<\/li>\n<\/ul>\n<p dir=\"ltr\">Now, our solution file will consist of 5 projects including existing Silverlight_MVC projects, Core Library, Xamarin.iOS &amp; Xamarin.Android projects:<\/p>\n<p dir=\"ltr\"><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-VS-Solution.png\"><img decoding=\"async\" class=\"alignnone size-medium wp-image-7842\" alt=\"DietCalculator-Android-VS-Solution\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-VS-Solution-214x300.png\" width=\"214\" height=\"300\" \/><\/a><\/p>\n<p dir=\"ltr\">Once you add the project, create a folder called Core in it and link all the files from your Calculator.Core project using <a href=\"http:\/\/docs.xamarin.com\/guides\/cross-platform\/application_fundamentals\/building_cross_platform_applications\/sharing_code_options\">File Linking<\/a>. \u00a0Other approaches to enable source code sharing would include using a Portable Class Library project or the <a href=\"http:\/\/visualstudiogallery.msdn.microsoft.com\/5e730577-d11c-4f2e-8e2b-cbb87f76c044\">Project Linker<\/a>; however, discussing the pros and cons of each approach is beyond the scope of this article.<\/p>\n<h2>Building the User Interface<\/h2>\n<p dir=\"ltr\">A key benefit of using Xamarin is that the application user interface uses native controls on each platform and is therefore indistinguishable from an application written in Objective-C for iOS or Java for Android. We can take advantage of native UI toolkits to present a familiar interface to the user. You can build your UI completely in code or use declarative XML and layout your controls. \u00a0XML-based User Interface for Android is very similar to technologies such as XAML for Windows Phone and HTML for the web. When using the declarative approach, XML files can be either hand-edited or modified visually by using the <a href=\"http:\/\/docs.xamarin.com\/guides\/android\/user_interface\/designer_overview\">Xamarin.Android designer <\/a>for Visual Studio. Use of a designer allows immediate feedback during UI creation, speeds up development, and makes the process of UI creation less laborious. If you are new to the Android platform, our <a href=\"http:\/\/docs.xamarin.com\/guides\/android\/getting_started\/hello%2C_world\">get started guide<\/a> can get you up to speed.<\/p>\n<p dir=\"ltr\">The existing Silverlight application displays user inputs &amp; resulting fields in one big screen. This is OK for desktop applications, however we cannot afford to do the same in mobile applications. Instead as we built in iOS, we split it into two screens \u2013 an input screen(Main.axml) and a result screen(Results.axml). Main screen will have a Calculate button which, when tapped, navigates to the result screen and displays all results.<\/p>\n<h3>Main.axml<\/h3>\n<p dir=\"ltr\">Under the Resources &gt; Layout folder is a file called Main.axml. Let\u2019s design the UI with all the necessary controls for Diet Calculation in Visual Studio. Here\u2019s our famous Android Designer for Visual Studio with all the android controls in the toolbox and a property window to set the attributes:<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-Designer.png\"><img decoding=\"async\" class=\" wp-image-7843 alignnone\" alt=\"DietCalculator-Android-Designer\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-Designer.png\" width=\"507\" height=\"255\" \/><\/a><\/p>\n<h3>Results.axml<\/h3>\n<p>We need a result screen to display all the values calculated based on the inputs provided by the user in the first screen. To do so, create a new Android Layout:<\/p>\n<ul>\n<li>\n<p dir=\"ltr\">Right Click on Layout Folder &gt; Add new Item &gt; Xamarin.Android &gt; Android Layout (Results.axml)<\/p>\n<\/li>\n<\/ul>\n<p dir=\"ltr\"><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-Designer-Results.png\"><img decoding=\"async\" class=\"alignnone  wp-image-7844\" alt=\"DietCalculator-Android-Designer-Results\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android-Designer-Results.png\" width=\"507\" height=\"321\" \/><\/a><\/p>\n<p dir=\"ltr\">Find above the resulting xml generated by the designer for Results screen.<\/p>\n<h3>Activities<\/h3>\n<p dir=\"ltr\">When we created a new Xamarin.Android Project, the project template also created a class called Activity1 in the file Activity1.cs. An Activity is a class that models a destination where a user can perform some action while using an app, typically via a user interface.<\/p>\n<p dir=\"ltr\">Conceptually, an activity can be thought of as being mapped to an application screen. An activity is similar in some ways to a Page in ASP.NET, in that every activity has a lifecycle associated with it. An Activity contains methods to be called at certain points in the lifecycle. These methods can also be overridden. For example, the Activity subclass created by the project template overrides the OnCreate method, which is called after an Activity first starts. I recommend reading the <a href=\"http:\/\/docs.xamarin.com\/guides\/android\/application_fundamentals\/activity_lifecycle\">Activity Lifecycle<\/a> article to effectively handle user data in changing states such as Running, Paused, Backgrounded &amp; Stopped.<\/p>\n<h4>MainActivity<\/h4>\n<p dir=\"ltr\">Rename the existing class Activity1 to MainActivity and Set the Content View to the Layout that we created in the Resources.<\/p>\n<pre class=\"lang:csharp decode:true\">\n[Activity(Label = &quot;Diet Calculator&quot;, MainLauncher = true, Icon = &quot;@drawable\/icon&quot;)]\npublic class MainActivity : Activity\n{\n protected override void OnCreate(Bundle bundle)\n {\n base.OnCreate(bundle);\n \/\/ Set our view from the &quot;main&quot; layout resource\n SetContentView(Resource.Layout.Main);\n }\n}\n<\/pre>\n<p dir=\"ltr\">Now, we can access all the controls created in the Layout file in the MainActivity class by calling the FindViewById method and passing the Resource ID. For e.g:<\/p>\n<pre class=\"lang:csharp decode:true\">\n\/\/ retrieve the widgets in UI using FindByViewId\n\/\/ to interact programmatically\nvar ageText = FindViewById(Resource.Id.ageText);\n\/\/ \u2026 do the same for other controls\n<\/pre>\n<p dir=\"ltr\">Initialize DietCalculator\u2019s Model and Controller from the Core project (re-usable code):<\/p>\n<pre class=\"lang:csharp decode:true\">\nmodel = new DietCalculatorModel();\ncontroller = new DietCalculatorController(model);\n<\/pre>\n<p dir=\"ltr\">When the calculate button is tapped, we need to do two things:<\/p>\n<ul>\n<li>\n<p dir=\"ltr\">Populate the values from the input fields and set the controller methods accordingly<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Navigate to Result screen with updated values<\/p>\n<\/li>\n<\/ul>\n<p dir=\"ltr\">CalculateButton.Click will set the values for all of the fields on the form, for instance:<\/p>\n<pre class=\"lang:csharp decode:true\">\ncontroller.SetAge(StringToNumberUtility.GetInt32(ageText.Text, 0));\n\/\/...\n<\/pre>\n<p dir=\"ltr\">We use Intents to pass the resulting data to the second screen. Intents are used throughout Android to make things happen by sending messages. They are most commonly used within applications to launch Activities. \u00a0For more information, I recommend reading <a href=\"http:\/\/docs.xamarin.com\/guides\/android\/getting_started\/hello%2C_multi-screen_applications\">Hello, Multiscreen Applications<\/a>.<\/p>\n<pre class=\"lang:csharp decode:true\">\n\/\/ Since Model classes are already populated with the results, pass them to Result Activity\n\/\/ using PutExtra method\nvar resultIntent = new Intent(this, typeof (ResultsActivity));\nresultIntent.PutExtra(&quot;CaloriesPerDay&quot;, model.CaloriesPerDay.ToString());\n\/\/...\nStartActivity(resultIntent);\n<\/pre>\n<h4>ResultsActivity<\/h4>\n<p dir=\"ltr\">Finally, in the resulting view you retrieve the data passed in the Intents and set it to the UI:<\/p>\n<pre class=\"lang:csharp decode:true\">\nFindViewById(Resource.Id.caloriesPerDayResultText).Text = Intent.GetStringExtra(&quot;CaloriesPerDay&quot;);\n\/\/...\n\n<\/pre>\n<h2>Final Output:<\/h2>\n<p><img decoding=\"async\" class=\"alignnone  wp-image-7840\" alt=\"DietCalculator-Android\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculator-Android.png\" width=\"233\" height=\"390\" \/><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculatorAndroid-Results.png\"><img decoding=\"async\" class=\"alignnone  wp-image-7841\" alt=\"DietCalculatorAndroid-Results\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/DietCalculatorAndroid-Results.png\" width=\"233\" height=\"390\" \/><\/a><\/p>\n<p>Please note, the logic in the program is ported as is \u2014 so all calculation results will depend on the algorithm used by the original author \ud83d\ude42 You can download the <a href=\"https:\/\/github.com\/nishanil\/DietCalculatorVS\">sample code from github<\/a>.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Android&#8217;s growth to number one smartphone platform in terms of units shipped has resulted in a significant increase in interest from businesses and developers to ship applications that run natively on Android devices and that take advantage of features such as the camera and voice recognition. With Xamarin.Android, .NET developers have the ability to write [&hellip;]<\/p>\n","protected":false},"author":547,"featured_media":39167,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-7839","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Android&#8217;s growth to number one smartphone platform in terms of units shipped has resulted in a significant increase in interest from businesses and developers to ship applications that run natively on Android devices and that take advantage of features such as the camera and voice recognition. With Xamarin.Android, .NET developers have the ability to write [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/7839","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/547"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=7839"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/7839\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/39167"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=7839"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=7839"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=7839"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}