search

What I’ve learned from porting my first app ever to Android and iOS with Xamarin

What I’ve learned from porting my first app ever to Android and iOS with Xamarin

What’s the app about?

The app is about fishing knots. It sounds boring for most people, but for me, this app made me becoming a developer. So I have a somewhat emotional connection to it. It was back in time when Windows Phone 7 was new and hot. A new shiny OS from Microsoft, but clearly lacking the loads of apps that were available on iOS and Android. At that time, I also managed to get my fishing license in Germany.

As I had a hard time to remember how to tie fishing knots, I searched the store and found… nothing. I got very angry over that fact, partly because it meant I had to use one of the static websites back then, but more about the fact that there was this damn app gap (WP7 users will remember). So I finally decided to learn how to write code for Windows Phone and wrote my first app ever after some heavy self-studying months.

Why porting it?

Writing code should soon become my favorite spare-time activity, effectively replacing fishing. And so the years went on, I made some more apps (most of them for Windows Phone) and also managed to become employed as a developer. After some time, S. Nadella became the CEO of Microsoft, and Windows for mobile phones was dead. So I had created all my “babies”, and they were now set to die as Windows Phone/Mobile did. Not accepting this, I started to create a plan to port my apps over to the remaining mobile platforms. After Facebook effectively killed my most successful app (UniShare – that’s another story, though), I stopped porting that one and started with Fishing Knots +.

Reading your own old code (may) hurt

When I was starting to analyze which parts of the code I could reuse, I was kind of shocked. Of course, I knew that there was this code that I wrote when I didn’t know it better, but I refused to have a look into it and refactor it (for obvious reasons from today’s perspective). I violated a lot of best practices back then, the most prominent ones

  • No MVVM
  • Repeating myself over and over again
  • Monster methods with more than 100 lines within

In the end, I did the only right thing and did not reuse any line of my old code.

Reusing the concept without reusing old code

After I took the right decision to not use my old codebase, I needed to abstract the concept from the old app and translate it into what I know now about best practices and MVVM. I did not immediately start with the implementation, however.

The first thing I did was drawing the concept on a piece of paper. I used a no-code language in that sketch and asked my family if they understand the idea behind the app (you could also ask your non-tech friends). This approach helped me to identify the top 3 features of the app:

  • Controllable animation of each knot
  • Easy-to-follow 3-step instructions for each knot
  • Read-Aloud function of the instructions

Having defined the so-called “Minimum Viable Product“, I was ready to think about the implementation(s).

The new implementation

Finding the right implementation isn’t always straight forward. The first thing I wrote was the custom control that powers the controllable animation behind the scenes. I wrote it out of the context in a separated solution as I packed it into a NuGet package after finishing. It turned out to be also the most complex part of the whole app. It uses a common API in Xamarin.Forms, and custom renderers for Android and iOS. I had to go that route because of performance reasons – which is one of the learnings I took away from the porting.

It was also clear that I will use the MVVM pattern in the new version. So I was setting up some basic things using my own Nuget packages that I wrote during working on other Xamarin based projects.

When it came to the overall structure of my app, I thought a Master/Detail implementation would be fine. However, somehow this never felt right, and so I turned to Shell (which was pretty new, so I tried to give it a shot). In the end, I went with a more custom approach. The app uses a TabbedPage with 3 tabs, one being for the animation, the second for the 3-Step tutorial, and last but not least the Settings/About page. The first two pages share a custom top-down menu implementation, bound to the same ViewModel for its items and selection.

More Xamarin.Forms features I learned (to love)

Xamarin and Xamarin.Forms itself are already powerful and have matured a lot since the time I used it to write my first Xamarin app for Telefonicá Germany. Here is a (high level) list of features I started to use:

  • Xamarin.Essentials – the one library that kickstarts your application – seriously!
  • Xamarin Forms Animations – polish the appearance of your app with some nice looking visual activity within the UI
  • Xamarin Forms Effects – easily modify/enhance existing controls without creating a full-blown custom renderer
  • Xamarin Forms VisualStateManager – makes it (sometimes) a whole lot easier to change the UI based on property changes
  • Xamarin.Forms Triggers – alternative approach to modify the UI based on property changes (but not limited to that)

The three musketeers

Because of Xamarin and Xamarin.Forms are such powerful tools, you may run into the situation of needing help/more information. My three musketeers to get missing information, implementation help or solution ideas:

  • Microsoft Xamarin Docs – the docs for Xamarin are pretty extensive and by reading them (even again), I often had one of these “gotcha!”- moments
  • Github – if the docs don’t help, Github may. Be it in the issues of Xamarin(.Forms) or studying the renderers, Github has been as helpful as the docs to me.
  • Web Search – chances are high that someone had similar problems/ideas solved and wrote a blog about it. I don’t blindly copy those solutions. First I read them, then I try to understand them and finally, I implement my own abstraction of them. This way, I am in a steady learning process.

Learn to understand native implementations

I guarantee you will run into a situation where the musketeers do not help when focusing solely on Xamarin. Accept the situation that Xamarin is sitting on top of the native code of others and does the heavy conversion for us. Learn to read Objective-C, Swift, Java and Kotlin code and translate it into C# code. Once you found possible solutions in one of the native samples, blog posts or docs, you will see that most of them are easy to translate into Xamarin code. Do not avoid this part of Xamarin development, it will help you in future, trust me.

Conclusion

Porting over my first app ever to Android and iOS has provided me not only a lot of fun but also huge learnings/practicing. Some of them are of behavioral nature, some of them are code implementations. This post is about the behavioral part – I will write about some of the implementations in my upcoming blog posts.

I hope you enjoyed reading this post. If you have questions or have similar experiences and want to discuss, feel free to leave a comment on this post or connect to me via social media.

Until the next post, happy coding!

Helpful links:

Posted by msicc in Dev Stories, Xamarin, 0 comments

How to search the Windows Phone Store within your app

MPSearch

I am currently working on my NFC app, and I want to make it easier for the end user to search for the AppId which you need for the LaunchApp record. So I thought about a possible solution for this, and of course the easiest way is to search the app.

If you only want to search the Windows Phone Store and let show some search results, there is the MarketplaceSearchTask, which you can call as a launcher. The only problem is, you cannot get any values into your app this way. But I found a way to get the results into my app. This post is about how I did it.

The first thing you will need to add to your project is the HTMLAgilitypack. It helps you parsing links from an HTML-based document. Huge thanks to @AWSOMEDEVSIGNER (follow him!), who helped me to get started with it and understand XPath. Xpath is also important for the HAP to work with Windows Phone. You will need to reference to System.Xml.Xpath.dll, which you will find in

%ProgramFiles(x86)%Microsoft SDKsMicrosoft SDKsSilverlightv4.0LibrariesClient or
%ProgramFiles%Microsoft SDKsMicrosoft SDKsSilverlightv4.0LibrariesClient

Ok, if we have this, we can continue in creating the search. Add a TextBox, a Button and a ListBox to your XAML:

            <Grid.RowDefinitions>
                <RowDefinition Height="90"></RowDefinition>
                <RowDefinition Height="90"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <TextBox x:Name="MPsearchTerm" Height="80" Grid.Row="0"></TextBox>
            <Button x:Name="searchButton" Height="80" Grid.Row="1" Content="search" Click="searchButton_Click_1"></Button>
            <ListBox Grid.Row="2" x:Name="ResultListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding AppLogo}" 
                                   Height="50" 
                                   Width="50" 
                                   Margin="10,0,0,0">
                            </Image>
                            <TextBlock Text="{Binding AppName}"
                                       FontSize="32"
                                       Margin="12,0,0,0" >
                            </TextBlock>

                        </StackPanel>

                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

After creating this, we will hook up the Click-Event of our Button to create our search. We are going to use the search of windowsphone.com to get all the information we want. You can parse any information that you need like ratings etc., but we focus on AppId, Name of the App and of course the store Logo of each app.

First, we need to create the search Uri. The Uri is country dependent like your phone. This is how we create the Uri:

string currentLanguage = CultureInfo.CurrentCulture.Name;
string searchUri = string.Format("http://www.windowsphone.com/{0}/store/search?q={1}", currentLanguage, MPsearchTerm.Text);

After that, we are using a WebClient to get the HTML-String of  the search. I used the WebClient as I want to make it usable on WP7.x and WP8.

//start WebClient (this way it will work on WP7 & WP8)
WebClient MyMPSearch = new WebClient();
 //Add this header to asure that new results will be downloaded, also if the search term has not changed
// otherwise it would not load again the result string (because of WP cashing)
MyMPSearch.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
//Download the String and add new EventHandler once the Download has completed
 MyMPSearch.DownloadStringCompleted += new DownloadStringCompletedEventHandler(MyMPSearch_DownloadStringCompleted);
MyMPSearch.DownloadStringAsync(new Uri(searchUri));

In our DownloadStringCompletedEvent we now are parsing the HTML-String. First thing we need to do is to create a HTML-Document that loads our string:

//HAP needs a HTML-Document as it is based on Linq/Xpath
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(e.Result);

The next step is a bit tricky if you do not know Xpath. You need to got through all the HTML elements to find the one that holds the data you want to parse. In our case it is the class called “medium” within the result table “appList”.

var nodeList = doc.DocumentNode.SelectNodes("//table[@class='appList']/tbody/tr/td[@class='medium']/a");

Note that you have to use ‘ instead of ” for the class names in Xpath. I recommend to open a sample search page in an internet browser and look into the code view of the page to find the right path.

image

Now that we have a NodeList, we can parse the data we want:

foreach(var node in nodeList)
            {
                //get AppId from Attributes
                cutAppID = node.Attributes["data-ov"].Value.Substring(5, 36);

                //get ImageUri for Image Source 
                var ImageMatch = Regex.Match(node.OuterHtml, "src");
                cutAppLogo = node.OuterHtml.Substring(ImageMatch.Index + 5, 92);

                // get AppTitle from node
                //Beginning of the AppTitle String
                var AppTitleMatch = Regex.Match(node.InnerHtml, "alt=");
                var StringToCut = Regex.Replace(node.InnerHtml.Substring(AppTitleMatch.Index),"alt="",string.Empty);
                //End of the AppTitle String
                var searchForApptitleEnd = Regex.Match(StringToCut, "">");
                //FinalAppName - cutting away the rest of the Html String at index of searchForApptitelEnd
                // if we won't do that, it would not display the name correctly
                cutAppName = StringToCut.Remove(searchForApptitleEnd.Index);
           }

As you can see, we need to perform some String operations, but this is the easiest way I got the result I want – within my app. As always I hope this will be helpful for some of you.

You can download full working sample here:  MarketplaceSearch.zip

Happy coding!

Posted by msicc in Archive, 0 comments