BenkoBlog

Confessions of an Evangelist

Issue with Xamarin Forms - InitializeComponent does not exist - Xamarin XAML is not Windows XAML

Originally posted on: http://geekswithblogs.net/benko/archive/2015/02/02/issue-with-xamarin-formsndashinitializecomponent-does-not-exist-xamarin-xaml-is-not.aspx

Have you ever tried to reuse code by adding existing files to a project? In Visual Studio this usually works, with the file getting put into the right location, associating the editor based on the file extension. I’ve been working on a Xamarin Forms project which allows me to use XAML to create the UI and C# for the code behind. This enables me to leverage my skills and experience building Windows and Windows Phone applications on iOS and Android. The problem came when I would include an existing file into a project.

image

The error: InitializeComponent does not exist – makes me wonder what’s wrong with the file? First things first, I checked that the namespace and class names matched. Next I tried commenting out what might’ve been invalid XAML syntax with the thought that maybe it wasn’t compiling right. No luck. Finally I compared the file to another that was working (I added myWorkingForm.XAML and guess what, no error in that one!). Both had the same namespace, both had the same class name declared as public partial (meaning it’ll compile the XAML + the C# into a class).

Finally I was down to looking at the compiled objects folder…and I saw that while myWorkingForm created an interim file myWorkingForm.xaml.g.cs the one that came from the file I included did not. I decided to look at the shared project’s projitems file (which is what lists the types of files in the project). I discovered that Visual Studio assumes that a XAML file is Windows XAML, not Xamarin XAML. In the projitems file the XML showed that adding the existing file associated it as a Page, where the other file that worked was marked as an Embedded resource (see below).

<ItemGroup>
  <EmbeddedResource Include="$(MSBuildThisFileDirectory)Pages\myWorkingForm.xaml">
    <SubType>Designer</SubType>
    <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
  </EmbeddedResource>
</ItemGroup>

<ItemGroup>
  <Page Include="$(MSBuildThisFileDirectory)Pages\TestForm.xaml">
    <SubType>Designer</SubType>
    <Generator>MSBuild:Compile</Generator>
  </Page>
</ItemGroup>

To make it work? Manually change the myproject.projitems file (in the solution explorer open the containing folder then edit the file with notepad) for TestForm.xaml to use the EmbeddedResource tag, matching that for myWorkingForm.xaml. This causes the build to use the Xamarin compiler and generate an interim file TestForm.xaml.g.cs. Problem solved!

Happy Coding!    (originally posted on www.benkotips.com)

Technorati Tags: ,
[More]

Setting a schema for the database in Azure Mobile Services

Originally posted on: http://geekswithblogs.net/benko/archive/2015/01/14/setting-a-schema-for-the-database-in-azure-mobile-services.aspx

I’ve been working on a project using Xamarin.Forms and Azure Mobile Services for a while, and one issue I came across that wasn’t entirely clear is how do you work with an existing database, yet support updates to the tables and be able to deploy to different environments (like Test, QA and Prod)? Hopefully I can shed some light with this post.

Azure Mobile Services is a feature rich cloud service that promises to take care of some of the complexities of building connected mobile apps. It supports things like 3rd party federated identity, push notifications, logging and more. With the original node.js release it supported JavaScript configuration for the CRUD operations against a table along with a dynamic schema that adapts to the request received via REST. In the .NET release they replace node.js with the ability to roll your own logic in C# and handle the data interaction with WebAPI type controllers. It requires a bit more work, and handling the database changes can be confusing.

Fortunately I’ve found a couple articles that help illustrate how this is done (on MSDN), but it doesn’t specify how to handle ongoing updates. To make it work for my scenario I either needed a way to support data model changes to a .NET backend mobile service, but have a consistent schema name when I move between environments. In the second article they show how to enable code-migrations, and to replace the default database initializers, by using the NuGet package manager and modifying code in the WebApiConfig.cs file. The steps were:

  1. Use NuGet Package Manager to Enable-Migrations
  2. Add a starting migration
  3. Update the WebApiConfig.cs file to use a DbMigrator to update the context instead of calling the default initializer

    public
    static class WebApiConfig
    {
    public static void Register()
    {
    // Use this class to set configuration options for your mobile service
    ConfigOptions options = new ConfigOptions();

    // Use this class to set WebAPI configuration options
    HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

    // *** BENKO: Enable database migrations for the service
    //Database.SetInitializer(new MobileServiceInitializer());
    var migrator = new DbMigrator(new Configuration());
    migrator.Update();
    }
    }
  4. Test local and confirm it’s working

I added a couple additional changes to set the schema name for my app in the MobileServiceContext.cs file (in the Models folder).


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// *** BENKO: This is what sets the schema name to the service name...
string schema = ServiceSettingsDictionary.GetSchemaName();
schema = "mySchema";
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}

modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}


I also need to make sure to create the schema on my database instance in SQL Azure and grant rights to the service user account. You can get the user account using SQL Server Mgmt tool (expand the users of the database node, or by running a SQL Script to select name from the SysLogins table of the master db. Once you have it you will need to create the schema an grant rights to it. Assuming the service user is ABC123Login_myServiceUser, the script looks like this:



create schema mySchema

-- Grant specific access rights to use based on Schema
GRANT
SELECT, INSERT, UPDATE, DELETE,
ALTER, CONTROL, EXECUTE,
REFERENCES, TAKE OWNERSHIP, VIEW DEFINITION
ON SCHEMA::[mySchema]
TO [abcdefghijLogin_democityUser]

When you publish the mobile service it will attempt to update the database using the schema provided. If there are error you can use the service’s logs to figure out what’s missing. By specifying the schema name instead of using the service’s name I’m able to deploy to multiple environments but integrate this data with my other applications.

Happy Coding! (originally posted on www.benkotips.com)

Technorati Tags: ,,,
[More]

Some Common Xamarin.Forms XAML Control Properties

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/29/some-common-xamarin.forms-xaml-control-properties.aspx

imageXamarin.Forms is an attractive option when building cross platform apps, but for an old XAML developer like myself it can be a challenge to get the nuances of the grammar and syntax right. For Windows I’ve depended on tools like Blend and Visual Studio Intellisense to help me understand what’s possible. Moving to Xamarin XAML is sometimes tedious because while I can use the intellisense from the C# code behind file it’s not there yet in a designer. While there’s some posts out there that compare and contrast how to move to Xamarin XAML from Microsoft XAML (like this one from TCPWare by Nicolò Carandini), I still wasn’t finding what I was looking for. This post is an attempt to iterate thru some of the core proprties of interest for many of the controls I use, and to catalog them here for current and future reference.

1/3/2015 : Update, added more controls to list -

Technorati Tags:

First some common properties – Some common properties to most controls include:

  • x:Name : The control name that can be used to reference the control from code
  • AnchorX, AnchorY : Positions control within the layout
  • HeightRequest, WidthRequest : The requested size of the control if the layout allows
  • MinimumHeightRequest, MinimumWidthRequest : The minimum size allowed
  • HorizontalOptions, VerticalOptions : Layout options for the control, include values Start, End, Fill, Center, StartAndExpand, EndAndExpand, CenterAndExpand
  • BackgroundColor : Color of background
  • Rotation, RotationX, RotationY : Rotation properties for rendering control
  • Scale : Scale value

Label - Displays text on a page.

  • XAlign, YAlign : Text alignment property…values include TextAlignment.Start, TextAlignment.Center, TextAlignment.End
  • TextColor : Color of text and background…can be named color
  • Font : Attributes of the font, such as Bold, Italic, Large, Medium, Small, Micro, 
  • LineBreakMode : Used to determine label’s text wrap properties. Values include CharacterWrap, NoWrap, WordWrap, HeadTruncation, MiddleTruncation, TailTruncation

TextCell - Displays text and detail subtext in a single control

  • Text : The main text to display
  • TextColor : Primary color of the text
  • Detail : Subtext displayed below main text
  • DetailColor : Color of secondary text

imageimageimageBoxView - Similar to Rectangle in Windows XAML. Used to display a box with some color on a page.

  • Color : Color of box
  • Opacity : Value of opacity…
  • IsEnabled, IsFocused : properties of Box

Entry - Similar to TextBox in Windows XAML. Used to get input from user.

  • TextColor : Color of text and background…can be named color
  • IsEnabled, IsFocused, IsPassword, IsVisible : Values that drive entry behaviors
  • InputTransparent : Determines whether to show input
  • Keyboard : Type of keyboard to show, possible values include Chat, Default, Email, Numeric, Telephone, Text, Url
  • Placeholder : Text to display when there is no value entered…displayed in grayed out mode
  • Text : Value of control

Image - Display an image. Includes common properties and:

  • Aspect : Scaling of image…stretch or fill. Values include Fill, AspectFill, AspectFit
  • IsEnabled, IsFocused, IsLoading, IsOpaque, IsVisible : Drive behaviors of image control
  • Source: This is where the image is sourced from…can be local resource or online.

ImageCell Displays an image and a TextCell

  • ImageSource
  • Text, TextColor
  • Detail, DetailColor
  • IsEnabled

Button - Used to trigger event processing in response to user’s actions

  • BorderColor, BorderRadius, BorderWidth : Values to control the border of the button
  • Command, CommandParameter : Values for the command to be executed when clicked
  • Font : Attributes of the font
  • IsEnabled, IsFocused, IsVisible : Values to drive button’s behaviors
  • Text : Text on the button
  • TextColor : Color of text on the button 

ActivityIndicator. An indicator that shows there is an action processing and the user needs to wait for it to complete

  • Color : Color of the indicator
  • IsEnabled, IsFocused, IsRunning IsVisible : Values to drive activity indicator’s behaviors

ProgressBar. Used to display how far along a process is

  • IsEnabled, IsFocused, IsVisible : Values to drive the control’s behaviors
  • Progress : Value to show completion…I think this is a value from 0.0 to 1.0

TimePicker. Used to select a time value

DatePicker. Similar to TimePicker, but used to select a date

  • Date : The date value of the control
  • Format : Format to display, using standard C# formats

Switch. Used to input whether a boolean property is true or false

  • IsToggled, IsEnabled, IsVisible, IsFocused : Drive control’s behaviors

SwitchCell. Displays a label and a switch

  • Text : The text of the label
  • On : A boolean value of whether the switch is toggled
  • Height : The height of the control

ViewCell. A basic layout control that displays an item in a data template. Does not have the basic properties.

  • Height : Height of cell to display

StackLayout. Similar to a StackPanel in Windows XAML, used to display items in a stack. Has the common properties as well

  • Padding : The area around the layout, displayed as an integer or series of values “left, top, right, bottom”… i.e. “20,0,0,0” means left margin of 20, zero on other sides
  • Spacing : The area between items
  • Orientation : Horizontal vs Vertical

Grid. Layout in Columns and Rows, using various spacing options, such as fixed, Auto and Star – *

  • RowDefinitions, ColumnDefinitions : Same as Windows XAML
  • RowSpacing, ColumnSpacing : distance between columns and rows, defaults to 6 px

ListView. Container for collections of items…

  • ItemsSource : The data collection used to populate the list
  • SelectedItem : If an item is selected in the list
  • IsEnabled, IsGroupingEnabled, IsVisible : Drives list’s behaviors
  • RowHeight : Height of item’s row
  • HasUnevenRows : A flag that indicates row height varies
  • Triggers : connects an item to a behavior
  • ItemTemplate : Binding template for item’s display
  • GroupHeaderTemplate : Binding template for list’s header

 

Happy Coding!

image

(originally posted on www.benkotips.com follow me on http://twitter.com/mbenko)

[More]

Working with Xamarin Forms and Navigation

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/17/working-with-xamarin-forms-and-authentication.aspx

I'm creating a Xamarin.Forms project, using XAML for markup that includes an authentication page when the app starts. I am using a TabbedPage (also tried CarouselPage) as the container of my main UI and plan to have several pages displayed. The first page (myDashboard) checks to see if the user has authenticated and if not I want to display a modal login page. When they return I would like to load data based on their user id.

What's happening is that the Dashboard page loads and is immediately overlaid by the myLogin page, but then all the DisplayAlerts show in succession before I do anything. When I call PopModalAsync() on the login page the OnAppearing method doesn't continue, which indicates to me that the await call had no effect in interrupting the process flow, as if it's already completed the calls after the PushModalAsync() call. (I plan to remove the DisplayAlert calls when it's working as expected.)

My code looks like this...in the App class:


    var mainPage = new TabbedPage() { Children = { new myDashboard() } };
    return mainPage;
    

 

In the myDashboard() class:


    protected async override void OnAppearing()
   {
       base.OnAppearing();
       try
       {

           await DisplayAlert("Alert", "OnAppearing Start", "ok", null);

           if (App.context.IsLoggedIn == false)
           {
               await Navigation.PushModalAsync(new myLogin());

               if (App.context.IsLoggedIn == true)
               {
                   // await LoadData();
                   PageLabel.Text = "Hello " + App.context.UserInfo;
               }
           }

           await DisplayAlert("Alert", "OnAppearing LoggedIn", "ok", null);

           await LoadData();
           await DisplayAlert("Alert", "OnAppearing Complete", "ok", null);
       }
       catch (Exception ex)
       {
           var err = ex.Message;
       }
   }
   

What am I missing?

It appears that because this code is in the OnAppearing() event which is called during a Pop or a Push that the behavior isn’t what is expected. I found an approach in the Xamarin Forums which wires up an event to the login page to send an event and then subscribe to it from the caller (see how-to-navigate-between-contentpages). I removed the code in the OnAppearing event, reserving it for handling core initialization and if the user is logged in I’ll load the data. To implement this approach subscribe to the event in the constructor of your main page…


    public myDashboard()
    {
        InitializeComponent();
        MessagingCenter.Subscribe<myLogin>(this, "LoginComplete",(sender) => LoadData());
    }
    

Then in the login page add code to send the message right after calling PopModalAsync() to close the window.

    
    public async void OnButtonClicked(object sender, EventArgs e)
    {
        var rc = await DisplayAlert("Alert!", "Logged in as " + myPhone.Text, "Ok", "Cancel");
        if (rc == true)
        {
            App.context.IsLoggedIn = true;
            await Navigation.PopModalAsync();
            MessagingCenter.Send<myLogin>(this, "LoginComplete");
        }
    }
    

It works, but is there a better way?

[More]

CloudTip 15-Avoid a gotcha in naming projects with Mobile Services

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/15/cloudtip-15-avoid-a-gotcha-in-naming-projects-with-mobile-services.aspx

Short Answer – Don’t use special characters in a Mobile Service’s project name when you create it, the local SQL won’t be able to open the database and you may spend a lot of time figuring out why chasing down false leads…

The Long Answer…

In my last role at Microsoft as an Azure Evangelist I posted a series of cloud tips, which were intended to be quick tips for using the latest tools & services. This one is the next in that series, and focuses around some esoteric gotcha’s that come up when you’re following a convention for organizing your solution in Visual Studio. As you probably are aware you can have multiple projects in a solution, and one approach for keeping them organized is to follow a naming standard that uses a dot-syntax to keep related related things in their right spot.

For example if my project is a solution to a to-do list, I might create the solution called “TestData”, and within that solution have a project for the web called “TestData.web” and a shared project called “TestData.shared”. Following this convention it makes sense if I want to add a data service project I might call it “TestData.svc”, right? When I try this out and build it, I was finding an error that took longer to expose than I had planned, and that’s the focus of this post.

image

I started with this solution and added some custom classes to the data tables to work with my TestData and found that I was getting  errors. The Mobile Services project type includes a testing page that allows me to try out the service and test the calls to my data, which is great. But I found that I was getting an error when I was running the project without adding or changing anything…Isn’t the stuff supposed to work “out of the box”? Instead I get the error - “The database name 'TR_TestData_svc]_TodoItems_InsertUpdateDelete' is invalid. Database names must be of the form [<schema_name>.]<object_name>”. What does this mean???

image

Don’t do this…

It looks like something’s not right with EF, so I tried updating my NuGet’s to make sure I have the latest packages…Right click the project explorer and go to the NuGet page and try update packages…this is the wrong thing to do because the template was created using specific versions of specific packages, and while some can be updated others shouldn’t.

This time I get an error that the JWTSecurityTokenHandler is broken. After some digging I found a StackOverflow post that answers this.  In particular I find that EF is unhappy with the latest MobileServices entity versions so in the NuGet Package Manager I need to uninstall the WindowsAzure.MobileServices.Backend packages and install the specific version 1.0.342.

Do this…Don’t name your Mobile Service project with special characters in the name

The problem isn’t with EF or out of date packages, it has to do with the local database name not being recognizable with the dot-syntax naming convention (another StackOverflow post). In the web config you can fix it by removing the period in the names, or you can do what I did which is just recreate the project without the dot name and test to confirm it’s working, and then rename the services project in the solution.

image

And it works! Time to go and write some code.

[More]

How to detect an iOS device when working with Xamarin and Visual Studio

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/03/how-to-detect-an-ios-device-when-working-with-xamarin.aspx

Xamarin + WAMS = Happiness (well, most of the time)

imageFirst some background…I spent the last couple months trying to figure out the best approach for cross-platform development stuff. After some research and working thru some POC’s with Apache Cordova, Native and Xamarin we decided to go down the path of Xamarin as the tool of choice. We did this for a few reasons, including that we can use C# for the code, that with Xamarin Forms it supports XAML as our markup which has a native backend for handling responsive design, and because we would like to have one set of code running across the different device platforms, and we can go deep on a platform to light up features as needed. For learning it there’s a nice set of xamples you can start from in GitHub that show working demo apps.

Secondly we’re using Azure Mobile Services (WAMS) with the .NET implementation so we can customize the authentication process to suit our needs (more on that in another post). The Node.js implementation is fast, but it has its limitations when we have multiple environments, need to work with specific 3rd party libraries, and we wanted to be able to debug completely offline. The new generation of WAMS with .NET does this by providing a WebAPI style implementation that lets me run the service locally and have complete control. All is good.

To build for iOS the configuration requires not just Xamarin but also a mac build machine. I went to Best Buy and found a reasonably inexpensive mini device, and with some cable magic I can connect it to a spare monitor and set it up. It takes a bit of configuration and creation of accounts with Apple to get it working as a dev machine, including registering with the developer program and getting a certificate to build with. The documentation on Xamarin’s site is pretty good on this.

All is good, and I’m able to build out the examples and deploy to my Windows Phone and Android devices, but when I try to detect an iPad (attached to my mac-mini build machine) it says no devices are attached.  When I click the drop down list of debug devices it shows the iOS simulator options. I don’t see the iOS device I have attached to my build machine! What to do?

image

Searching the issue finds some ideas, but after an hour or so of restarting Visual Studio, the mac, and reconnecting the build host and then restarting Visual Studio I find that sometimes it sees my device but then quickly switches to the simulator as the only options to test on. I prefer to run on real devices (a result of attempting to use the Android simulators and waiting in vain for them to start), and also I don’t have the monitor hooked up to the mac except when I turn it on to log in. I found this Stack Overflow post which further down had a nugget of info that solved my problem.

In a multi-project solution in Visual Studio the place to look is the configuration manager. Right click on the solution and open it up. Change the iOS project from iPhoneSimulator to iPhone and Bang! your issue is solved.

image 

Now when I look at my targets for the iOS project it shows my device.

image

All is good. Happy Coding!

[More]

Upgrading to Developer Preview of Windows Phone 8.1

Originally posted on: http://geekswithblogs.net/benko/archive/2014/04/14/upgrading-to-developer-preview-of-windows-phone-8.1.aspx

Preview for DevelopersWoot! I’ve got it, the new preview release of Windows Phone 8.1. Since the announcements at Build where they introduced the next generation of apps for Windows and Windows Phone I’ve been working to get the tools and start the learning process to be ready to build for the new devices. If you’re looking to do the same there are a few steps to follow, but it’s not that difficult, although it takes some time and a couple steps to complete.

Here’s what you need to do…

  1. Get a Windows 8 phone. This can be any wp8 device, I’ve been using Nokia devices lately. The 820 is nice and I like the size and format.
  2. Register as a developer on http://create.msdn.com – this is the developer portal where you can get started building for Windows. There is a registration cost of $19 if you’re not in the program. Another option is to register with App Studio – where you can literally create an app in minutes and have it running on your device.
  3. Download the phone registration tool to unlock your device for development. This is included with the tools for Windows Phone download.
  4. Unlock the phone
    Developer_Registration_Tool
  5. Install the preview app on your phone
  6. Check for updates and install them on your phone…it will walk you thru the process

The preview app allows your phone to download the bits and install them. You may need to check for updates (in the phone settings) a couple times, but when you do it will do the necessary work. I found that it took me more than an hour to complete (make sure your phone is charged before you start) and I had to run the check for updates 3 times to get all the prerequisites to get to the 8.1 install, but persistence paid off.  Now it’s time to start building some universal apps.

Ok, Cortana, what next?

Mike

[More]