Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

January 16

Updated Terms of Service and commitment to being an open platform

We’ve been building Unity for 15 years with the vision of creating an open and accessible tool to enable creators to build whatever you can dream of. Over the last week there was much confusion, and untrue statements were raised which we refuted. But most importantly we listened to you, our community that felt that […]

Kaze and the Wild Masks: Designing a great pixel art character

Nostalgia can be very powerful, but historical limitations don’t need to curb your creativity. Vox Game Studio shares their experience of designing a 16-bit character that references classic 1990s platformers while also taking advantage of all the tools and options today’s developers have at their disposal. When the studio decided to develop a down-to-earth and […]

January 11

Xamarin.Forms 3.5: A Little Bindable Love

This is a guest post contributed by Andrei Nitescu, a mobile developer since 2013 and frequent contributor to Xamarin.Forms. He shares about his experiences with other developers on his blog, and delivering talks whenever he has the chance.

Xamarin.Forms 3.5

Xamarin.Forms 3.5-pre2 is now available in pre-release on NuGet and via your Visual Studio NuGet package manager. For a complete list of improvements including Andrei’s BindableLayout contribution, review the full release notes.

I’d like to share with you some information about one of my contributions to Xamarin.Forms, the bindable layout. As a developer, I love the potential of the layout views to create visually rich views that delight our app users. Xamarin.Forms, the cross-platform mobile application framework, it’s more straightforward to create such custom views that work across all mobile platforms. Xamarin.Forms allows us to write the layout logic to set the size and position of the views only once.

While the “binding layout” name might suggest that it’s an addition to the base Layout view class, it actually works as an adaptor. It takes a source of data items and calls the Layout<T> view to create and update its child views based on the changes in the data item source.

Layouts, a Quick Refresh

(Skip this section and the next one if you already know how layouts and data-binding to layouts work. There is no new information on that.)

Xamarin.Forms has a special View called Layout. The Layout class is a container for other Views and has a specific mission: to position and size its child Views. Here’s the class diagram with all the available layouts in the framework today:

The Layout<T> class is a specialized Layout which exposes a Children View collection. Therefore, we can add, remove, or replace child Views to fit our design requirements:

StackLayout stackLayout =…;

stackLayout.Children.Add(new Label() { Text = … });

Layout<T> is the base class for most common layouts some of which you’ve already been using, like the StackLayout or Grid for example. The Layout<T> makes it possible to create your own layout to size and position child views any way you want; it’s really up to your imagination. There’s excellent documentation and samples on how to build your own custom layouts. Check out Creating a Custom Layout.

Layout + Data Binding

When creating the item views for a Layout based on a source of data items, you may have code that looks similar to this:

void UpdateItems (StackLayout layout, IEnumerable newDataItems)
{
    layout.Children.Clear ();
    foreach (object dataItem in newDataItems) {
        View itemView = CreateItemView(dataItem);
        layout.Children.Add (itemView);
    }
}

However, wiring up a collection of data items to a layout view needs to take into account and handle several aspects. For example, we need to check if the data item collection is observable (it implements INotifyCollectionChanged). In this case, it subscribes to the collection change event. If the collection instance is replaced, we need to make sure we remove it by listening to the old collection. We also need to handle creating the item view for each data item. Then bind the item view to the data item. Sometimes we may also want the item view to be different depending on the data item.

Bindable Layout

Starting with Xamarin.Forms 3.5.0 pre2, we can use the BindableLayout set of attached properties on any Layout<T> view:

  • IEnumerable ItemsSource { get; set; }
  • DataTemplate ItemTemplate{ get; set; }
  • DataTemplateSelector ItemTemplateSelector{ get; set; }

These should be familiar to you if you’ve used a ListView before.

The simplest usage is to set a data items source. This automatically creates a Label child View for every data item in the item source. It makes sense to use it when the data source is a collection of strings:

XAML:

<StackLayout BindableLayout.ItemsSource=”{Binding Sports}” />

C#:

IEnumerable sportsSource = …;
BindableLayout.SetItemsSource(sportsPanel, sportsSource);

When the default Label doesn’t suffice, you can configure a custom template which the Layout View uses to create a child View for every data item in the item source:

XAML:

<StackLayout BindableLayout.ItemsSource="{Binding Users}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Horizontal">
                <Image Source="{Binding Avatar}" />
                <Label Text="{Binding Name}" />
            </StackLayout>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

C#:

DataTemplate useItemTemplate = null;
BindableLayout.SetItemTemplate(usersPanel, userItemTemplate);

More information on creating and using DataTemplates can be found here: Creating a Xamarin.Forms DataTemplate.

If you want to have the Layout create the child View depending on the data item, you can then set a DataTemplateSelector:

XAML:

<FlexLayout BindableLayout.ItemsSource="{Binding Users}"
            BindableLayout.ItemTemplateSelector="{StaticResource UserItemTemplateSelector}" />

C#:

DataTemplateSelector userItemTemplateSelector = …;
BindableLayout.SetItemTemplateSelector(usersPanel, userItemTemplateSelector);

For more information on how to create and use a DataTemplateSelector, please check out Creating a Xamarin.Forms DataTemplateSelector.

Vertical List

When it comes to binding a source of items and displaying it in a vertical list, the ListView has the same features. Its behavior is different and it’s important to understand its limitations:

  • ListView is inherently a scrollable container. Unless you set a specific height, it takes as much height as possible, because its nature is to display a scrollbar in order to scroll the item views. Having a scrollable view along with other views on a scrollable page is not desirable for your users. There are workarounds to make a ListView display without scrolling. By setting the right height based on the containing views for example, but it’s not pretty or ideal.
  • The StackLayout for example, in contrast, doesn’t have this issue. It takes as much space as it needs for its child elements on the direction of its orientation (vertical/horizontal), so it computes its size based on its child views.
  • In ListView, the items are selectable and provide a visual feedback when items are pressed/released. ListView can disable selection (SelectionMode=”None”), but it does not eliminate the highlight when tapping the item. More tweaking is needed and it requires renderers.
  • You could try to disable the interaction with the a ListView. This way both the scrolling and selection won’t be an issue anymore, however this won’t work in the case that you want your users to interact with the items.
  • Because of its more complex features, the ListView is heavier to render than the StackLayout, for example.

Upcoming CollectionView

Like I mentioned earlier, when using the current built-in Layouts available on the framework (StackLayout, FlexLayout, Grid, etc.), the bindable layout functionality is useful when you know that the items source is of few items. The items display must also not be scrollable or selectable. You can always wrap the layout with a ScrollView, though in the future a much better option would be to use CollectionView instead. This does exactly what you need and it’s more efficient.

Try it Today!

I put together a sample app (screenshot below) which uses different bindable layouts in various scenarios that I think it makes sense. Check out this BindableLayoutsApp on Github.

The post Xamarin.Forms 3.5: A Little Bindable Love appeared first on Xamarin Blog.

January 10

Our response to Improbable’s blog post (and why you can keep working on your SpatialOS game)

Improbable published a blog post regarding their relationship with Unity earlier today. Improbable’s blog is incorrect. We terminated our relationship with Improbable due to a failed negotiation with them after they violated our Terms of Service. We’ve made it clear that anyone using SpatialOS will not be affected. Projects that are currently in production or […]

Hackathon Superweapon: F# and Fabulous

Recently, I participated in Hack for the Sea, a weekend devoted to applying tech to marine conservation. One of our local challenges was a “cross-platform mobile app for reporting marine debris.” A perfect opportunity to explore the Fabulous  project, which brings the Elmish Model-View-Update (MVU) architecture to Xamarin and F#.

Hackathons are great short and intense challenges that (hopefully) turn a concept into, if not a complete prototype, at least an initial iteration. The camaraderie, short deadline, and free pizza make hackathons an ideal place to explore new technologies.

F# has become a favorite programming language for production work. It has a combination of concise syntax for writing new code and strong types for working with older or unfamiliar code. However, would it be up for the controlled chaos of a hackathon?

MVU Architecture

The MVU architecture is an increasingly popular architecture that combines “UI in code,” with a simple-to-use separation between:

  • A view function which describes the user-interface appropriate to the current state of the application.
  • An update function that modifies that state.

MVU is not specific to any language, but it fits well with the functional programming mindset. Both view and update are expected to receive all the information they need from their arguments rather than reading and maintaining instance data.

The MVU architecture and F#’s concise syntax allow one to rapidly create a reporting app that is very similar to a lot of Line of Business (LOB) apps. The app has a combination of data-entry pages and device-generated data (default location and time info, photos, etc.).

Creating Xamarin.Forms UI in Code

Creating a Xamarin.Forms UI in code is very straightforward. Define each complex element or page in a local function. A simple one like header just contains a static label. A more complex one like locationPage can have a message depending on the value (or non-existence) of model.Report.Location. As you can see, using the powerful FlexLayout capability of Xamarin.Forms defines a user interface that lays out properly on any sized device:

let view model dispatch =

    let header = 
        View.Label(text = "Report Marine Debris", fontSize = 24, horizontalTextAlignment = TextAlignment.Center)

    let locationPage = 
        let locMsg = match model.Report |> Option.bind (fun r -&gt; r.Location) with
                     | Some loc -> sprintf "Location: %.3f, %.3f" loc.Latitude loc.Longitude
                     | None -> "Location Unknown"

        View.FlexLayout(direction = FlexDirection.Column, alignItems = FlexAlignItems.Center, justifyContent = FlexJustify.SpaceEvenly, 
            children = [
                View.Map(requestedRegion = model.MapRegion, minimumWidthRequest = 200.0, widthRequest = 400.0) |> flexGrow 1.0
                View.Label(text = locMsg, verticalTextAlignment = TextAlignment.Center) |> flexGrow 1.0
            ])

    // ... more building up of elements and pages ... 

    View.ContentPage(
         content = View.FlexLayout(direction = FlexDirection.Column, alignItems = FlexAlignItems.Center, justifyContent = FlexJustify.SpaceEvenly, 
            children = [
                header
                content
                footer
            ]))

F# reads quite a bit like Python (quite often when writing Python I accidentally type an F#-ism!). One thing possibly surprising to people who’ve heard of “strongly typed functional languages” is the lack of explicit type declarations. While developers may  add explicit declarations, mostly you rely on the compiler to correctly infer the type and use IntelliSense to give you the precise signature. Other things worth pointing out :

  • In F# “everything is an expression.” Both functions and values are declared using let;
  • The |> operator is similar to a Unix or PowerShell pipe. It passes the left-hand side value to the right-hand side as an argument;
  • The match ... with ... pattern-matching syntax that generates a compiler error if you miss a case;
  • The function Option.bind which is something like the null-conditional operator.

Using F# to Write a Function

Once you learn the basics of F#, it’s very readable and concise. Since local functions are trivial to write, you end up refactoring the boilerplate code into local functions. For instance, this “progress panel” uses different icons to indicate whether or not the user has entered a particular type of data (e.g., “what_some.png” vs “what_none.png”). Rather than write a bunch of near-identical if...then... blocks, it’s natural in F# to write a function such as imageFor that checks if the data has a particular field (the Some case). Then it returns the results of the check and the name of the particular icon to load :

let imageFor f imagePrefix =
    match model.Report |> Option.bind f with
    | Some _ -> (true, sprintf "%s_some.png" imagePrefix)
    | None -> (false, sprintf "%s_none.png" imagePrefix)

let (hasLoc, locImage) = imageFor (fun r -> r.Location) "where"
let (hasDebris, debrisImage) = imageFor (fun r -> r.Material) "what"
// ... etc. for each type of data and icon

 

Updating to Update

To be honest, I love the Model-View-Controller architecture. However, MVU has some clear advantages, particularly in the earliest iterations of a project. Also, it has the potential for “time-travel debugging” in which you can “run the program backward and forwards” rather than just freezing at a breakpoint.

Key to MVU is the update method, which has a signature Msg -> Model -> Model * Cmd<Msg> (which would be expressed in C# as Func<Msg,Model,Tuple<Model,Cmd<Msg>>). This shows the common functional pattern of “Take a request (Msg) and an argument representing the state (Model). Act on it, and then return a new version of the state with a new request to tackle the next step in responding to the input.”

For instance, when the GPS gets a reading, the handler creates a LocationFound Msg with a value of type Xamarin.Essentials.Location. In response, the update method has this snippet :

| LocationFound loc ->
    let report = { oldReport with Location = Some loc }
    let newRegion = new MapSpan(new Position(loc.Latitude, loc.Longitude), 0.025, 0.025)
    { model with MapRegion = newRegion; Report = Some report }, Cmd.none

 

Reports

A new report (the data that is ultimately uploaded to Azure) is created by copying the oldReport with the new Location value. I then create a new model that contains both my new report and the MapRegion value used in the view method as discussed previously.

And that’s it! The handler for LocationFound is actually the longest one in the update function. If a message requires complex handling, handling it should be done in a separate function. This is particularly nice for async processing, as you can see in the below snippet, that stores the photo to an Azure blob and the data to table storage:

let SubmitReportAsync reportOption =
    async {
        match reportOption with
        | Some report ->
            let photoName = sprintf "%s.jpg" ( report.Timestamp.ToString("o") )
            let csa = CloudStorageAccount.Parse connectionString
            let! photoResult = photoSubmissionAsync csa "image/jpeg" report.Photo photoName
            let! submissionResult = reportSubmissionAsync csa report photoResult
            return SubmissionResult submissionResult
        | None ->
            return Error "Choose data to make report"
} |> Cmd.ofAsyncMsg

 

Unlike the synchronous LocationFound handler, this function does some asynchronous work and then fires off a new Cmd with a Msg that’s either an Error message or a SubmissionResult message. Rather than a function that tries to do all the business of coordinating async network requests, displaying the results or errors, etc., the MVU architecture facilitates creating clear, discrete single-task functions. In a rapidly-iterating situation such as a hackathon, this is a blast: “OK, what’s next?” … type a few lines … run it … change it … run it … “OK, what’s next?”

Scaling Applications

There is a trade-off. An update function that has to handle lots of Msg types whose abstraction levels can vary (for example, SubmitReport vs. TakePhoto). It’s pretty jarring to be preaching the functional “lots of small functions” and have a multi-hundred line update function. I recommend watching Zaid Ajaj’s talk “Scaling Elmish Applications” for a good discussion of the issue.

Wrapping Up

In the end, I made my final commit a few minutes before midnight on Saturday, having created from scratch a cross-platform data-entry mobile application, two wrappers for custom controls, and a pile of soda cans to be recycled (Ocean conservation protip: aluminum cans are efficiently recycled compared to plastic bottles, despite their relatively poor packaging-to-content ratio). You can see the interim result (and proof that UX design is not my forte!) at my Github repo.

The pressure-cooker environment of a hackathon demands tools that are both high in productivity and fun: exactly how I would describe F# and Fabulous!

The post Hackathon Superweapon: F# and Fabulous appeared first on Xamarin Blog.

January 08

UnityScript to C# Conversion Tool

Do you have any older projects that use UnityScript? If so, you might be interested in our open source UnityScript to C# conversion tool available to download now. Back in August 2017, we have begun the deprecation process for UnityScript, a JavaScript-like scripting language, and started working on a conversion tool from that language to […]

January 07

Now taking submissions for $25K Unity for Humanity 2019 Challenge

We’re happy to announce that the annual Unity for Humanity Challenge is now open for submissions! As our world evolves at a rapid rate, Unity creators are developing projects and tools that have a positive and meaningful impact on our planet. Whether they touch on social, healthcare, science, education, humanitarian or environmental issues, we see […]

January 04

The final month of the Unity Global Student Challenge

We’re now officially under the 30 day mark for the Unity Global Student Challenge, and we’re excited to share some inspiration from student projects that made an impact this past year! With the start of a new year and the return of many students back to school, it’s been a busy start to 2019, and […]

January 03

Faces of Unity: Sonya Gharsallah

Cultivating an atmosphere of energy, positivity, and collaboration is a goal of every Unity office, and no team better embodies this goal than our Workplace Experience (WE) team! From managing the day-to-day operations of each office to planning and executing Unity office events, our WE teams around the globe are charged with ensuring that each […]

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers