Thursday, January 10, 2019
Wednesday, October 17, 2018
Too much fun with Xamarin Forms
The SVG is created dynamically, based on the position of the text-boxes and the button, so it will work on any number of text-boxes and buttons. The actual SVG for the login screen in the videos, looks like this:

Friday, September 04, 2015
Debugging HTML5 running in iOS from Windows with Chrome dev tools!
In order to debug HTML5 running in Safari on iOS, I used to connect the iOS device to my Mac, open Safari, go to Developer menu(needs to be activated from Safari Preferences) and open the page.
You can find detailed steps how to do this on internet.
I tried to remote debug HTML5 with other tools (Telerik has one), but the best way is with an utility called ios-webkit-debug-proxy which uses Chrome dev tools!
You can find it here https://github.com/google/ios-webkit-debug-proxy and its Windows port: https://github.com/artygus/ios-webkit-debug-proxy-win32
It allows you inspect the WebKit (either the Safari or UIWebViews) running on the iOS device from your Windows machine with Chrome dev tools.
This utility connects to the WebKit for inspection.
Steps (most of these are written in https://github.com/google/ios-webkit-debug-proxy):
- Go to https://github.com/artygus/ios-webkit-debug-proxy-win32
- You can either get the compiled version or build from the source. I chose to built it from source just for the kicks.
- Run the ios-webkit-debug-proxy.exe
- In Chrome, go to http://localhost:9222/ to see web-browser tabs open in Safari or the WebViews on the iOS device. Click on a tab.
- A new window should open with Dev tools. Note the silver icon, click on it and choose to 'Load unsafe scripts':
Some things to keep in mind:
- note that a web server is being used. when inspecting a tab, the link is
https://chrome-devtools-frontend.appspot.com/static/27.0.1453.93/devtools.html?host=localhost:9222&page=1
not sure if this might be a security issue for what you're debugging.
- in the inspector window, clicking on elements in the Elements tab doesn't do anything; you can use arrow keys to navigate up and down in the DOM tree
Monday, June 22, 2015
GridSplitter control for Xamarin Forms
You can find the full description of how it works and how to include it in your app:
https://github.com/andreinitescu/GridSplitterApp
Some screenshots with sample layouts included in the sample app:
and a Grid with both horizontal and vertical splitters:
The sample app also shows a technique to create reusable custom controls which you can style easily just with XAML, very similar to how it works on Windows.
Wednesday, June 17, 2015
Easiest way to know which w3wp.exe PID corresponds to which application pool
Open Task Manager and have it show the Command Line column
You can see for the w3p.exe processes the name of the app pool in the command line parameters
Wednesday, June 10, 2015
Xamarin Forms: Create a style BasedOn default style defined in app's global resource dictionary
<Style TargetType="Label">
<Setter Property="TextColor" Value="Red" />
</Style>And this style defined in a page:
<Style x:Key="MyLabelStyle" TargetType="Label">
<Setter Property="FontSize" Value="14" />
</Style> If you want MyLabelStyle to inherit the global style, one way is to use this syntax:
<Style x:Key="MyLabelStyle" TargetType="Label" BasedOn=”{StaticResource Xamarin.Forms.Label}”> otherwise MyLabelStyle will not have the text color red.
Note that this won’t work:
<Style x:Key="MyLabelStyle" TargetType="Label" BasedOn=”{StaticResource {x:Type Label}}”>Instead of hard coding the Label’s type full name, a nicer way would be to define a custom markup extension which resolves the Label type (something like this)
Xamarin Forms style resets
For example, some container controls have default padding and spacing for their child views.
In a more complicated UI, sometimes these default styles can become an issue. Because the UI you build is complex, you can forget about these default values and you wonder why some views are not positioned the way you want.
I created a small XAML 'resets' snippet, which can be added to the App.xaml:
https://gist.github.com/andreinitescu/69e8afcad1ed9de69b76
Add App.xaml in your Xamarin Forms project
The support for App.xaml is briefly mentioned in Xamarin Forms documentation but without giving the exact steps.
These steps are:
<Application
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.App">
<Application.Resources>
<ResourceDictionary>
</ResourceDictionary>
</Application.Resources>
</Application>
public partial class App : Application
{
public App ()
{
InitializeComponent ();
MainPage = YourContentPage(); // change as required
}
}
Monday, June 08, 2015
IconView control for Xamarin Forms
Someone was asking on the forum how to draw a colored icon.
I created an IconView control which does this: https://github.com/andreinitescu/IconApp/
The control takes a local image and applies a color on it. This is useful when you want to color images on the fly, without the need to have multiple images for different colors.
At this moment the implementation is for Android and iOS. Contributions for Windows support are welcome!
Usage
An example of a Page using the IconView control:<?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="IconApp.MyPage" xmlns:controls="clr-namespace:IconApp;assembly=IconApp"> <controls:IconView Source="monkey" Foreground="Red" WidthRequest="100" HeightRequest="100" HorizontalOptions="Center" VerticalOptions="Center" /> </ContentPage>
Add the control to your project
1. Add /IconApp/IconApp/IconView.cs to your Xamarin Forms PCL project
2. The control uses native renderes. You need to add the renderers to your Android and iOS project respectively:
/IconApp/IconApp.Droid/Renderers/IconViewRenderer.cs
IconApp/IconApp.iOS/Renderer/IconViewRenderer.cs
Note you might need to update some namespaces.
Tuesday, May 26, 2015
CallDataMethod trigger in Xamarin Forms
Here’s a very simple implementation of a CallDataMethod trigger in Xamarin Forms:
public class CallDataMethod: TriggerAction<VisualElement> { public string Method { get; set; } #region implemented abstract members of TriggerAction protected override void Invoke (VisualElement sender) { MethodInfo method = sender.GetType ().GetRuntimeMethod (Method, new Type[0]); if (method != null) { ParameterInfo[] parameters = method.GetParameters (); if (parameters.Length == 0) method.Invoke (sender, null); } } #endregion }
For a demo, let’s say we have two text-boxes (Entry control in Xamarin Forms) and you want to enable the second one when the first has ten characters:
<?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:controls="clr-namespace:Xamore.Controls;assembly=Xamore.Controls" x:Class="Xamore.Controls.TestApp.Views.CallDataMethodPage"> <StackLayout> <Entry x:Name="FirstEntry" WidthRequest="100" /> <Entry IsEnabled="false" WidthRequest="100"> <Entry.Triggers> <DataTrigger TargetType="Entry" Binding="{Binding Source={x:Reference FirstEntry}, Path=Text.Length}" Value="10"> <Setter Property="IsEnabled" Value="True" /> <Trigger.EnterActions> <controls:CallDataMethod Method="Focus" /> </Trigger.EnterActions> </DataTrigger> </Entry.Triggers> </Entry> </StackLayout> </ContentPage>
Wednesday, May 20, 2015
Manually install Xamarin Studio addins
on Windows:
%LocalAppData%\XamarinStudio-5.0\LocalInstall\Addins
on Mac:
/Users/[YourUser]/Library/Application Support/XamarinStudio-5.0/LocalInstall/Addins
Source:
http://forums.xamarin.com/discussion/comment/6356/#Comment_6356
Monday, May 18, 2015
Add ImageFailed and ImageOpened to the Xamarin Forms Image control
I created a way to do this by extending the implementation for the Image control and ImageSource.
Check out the source code and a demo app on my GitHub: https://github.com/nitescua/ImageExtensionsApp
I implemented two ways to handle image loaded status. You could either:
1. Use the Image derived class ImageEx which exposes ImageOpened and ImageFailed events:
<controls:ImageEx Source="http://dummyimage.com/100x100/000/fff" ImageFailed="Image_ImageFailed" ImageOpened="Image_ImageOpened"/>
2. Handle the status change right on the ImageSource instance:
ImageSourceExtensions.SetStatusChangedHandler (MyImage.Source, (sender, status) => { Debug.WriteLine("Image status: {0}", status); });
To add the implementation in your apps, you need to:
1. Add ImageSourceExtensions.cs and ImageEx.cs to your shared Xamarin Forms project
https://github.com/andreinitescu/ImageExtensionsApp/blob/master/ImageExtensionsApp/ImageExtensionsApp/Helpers/ImageSourceExtensions.cs
https://github.com/andreinitescu/ImageExtensionsApp/blob/master/ImageExtensionsApp/ImageExtensionsApp/Controls/ImageEx.cs
2. Add the ImageLoaderSourceHandlerEx.cs in your platform specific code
Android: https://github.com/andreinitescu/ImageExtensionsApp/blob/master/ImageExtensionsApp/ImageExtensionsApp.Droid/Renderers/ImageLoaderSourceHandlerEx.cs
iOS: https://github.com/andreinitescu/ImageExtensionsApp/blob/master/ImageExtensionsApp/ImageExtensionsApp.iOS/Renderers/ImageLoaderSourceHandlerEx.cs
WindowsPhone: https://github.com/andreinitescu/ImageExtensionsApp/blob/master/ImageExtensionsApp/ImageExtensionsApp.WinPhone/Renderers/ImageLoaderSourceHandlerEx.cs
Few things you should be aware of:
- the events are called when Uri is valid. So for example, it will work when uri is “http://xxxxx’ but not for ‘xxxxx’
- when using the ImageSource.StatusChangedHandler note that the event is called only if you set the ImageSource to an Image. It doesn’t work if you just create an ImageSource using ImageSource.FromXXX methods. You must set the ImageSource to an Image.
Wednesday, May 06, 2015
Cross platform splash screen in Xamarin Forms
EDIT: I do not recommend this approach. Instead, use native approach to create splash screen because it shows much faster.
If the splash screen is more than just an image, you can treat the splash screen as a Xamarin Page.
To make this there are some steps:
Step 1. set the App’s MainPage to the splash screen page:
public partial class App : Application { public App() { InitializeComponent(); Setup.Init(); // with XLabs, you would do (Page)ViewFactory.CreatePage<SplashViewModel>(); MainPage = new SplashPage(); }
Step 2. In SplashPage, after some logic is done, you will need to “navigate” to your first app’s page. This means you just need to set again the App’s MainPage, i.e”:
void ShowMainPage() { MainPage = new SplashPage(); }
If you are not doing any logic in the splash screen, you can just do something like this:
public class SplashPage : Page { async protected override void OnAppearing() { base.OnAppearing(); await Task.Delay(TimeSpan.FromSeconds(2)); // again, here you might want to use instead XLab's ViewFactory.Create<FirstPageViewModel>() App.Current.MainPage = new FirstPage(); } }
There are few ways to change the App’s MainPage without calling it from the view-model.
You could use a messaging mechanism to send a custom message from the view-model to the view. Look to the Xamarin Form’s MessagingCenter: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/messaging-center/.
Another way is, you probably are already using some navigation service to navigate between view-models, so what you need to do is have a custom navigation behavior in the way you navigate to the first page. With XLabs for example, you can define your own CustomNavigationService : XLabs.Platform.Services.INavigationService, override NavigateTo( ), then check for the page to which you navigate to, and if it’s FirstPage then create the NavigationPage and push the first page to it:
public class CustomNavigationService : INavigationService { NavigationService navigationSvc; public CustomNavigationService() { navigationSvc = new NavigationService(); } public void GoBack() { navigationSvc.GoBack(); } public void GoForward() { throw new NotImplementedException(); } public void NavigateTo<T>(object parameter = null, bool animated = true) where T : class { NavigateTo(typeof(T), parameter, animated); } public void NavigateTo(string pageKey, object parameter = null, bool animated = true) { throw new NotImplementedException(); } public void NavigateTo(Type pageType, object parameter = null, bool animated = true) { if (pageType == typeof(MainViewModel)) { var page = (Page)ViewFactory.CreatePage(pageType); App.Current.MainPage = new NavigationPage (page); navigationSvc = new NavigationService(App.Current.MainPage.Navigation); } else { navigationSvc.NavigateTo(pageType, parameter, animated); } } public void RegisterPage(string pageKey, Type pageType) { navigationSvc.RegisterPage(pageKey, pageType); } }
a. Define a startup theme and an app theme in your Resources\values\themes.axml:
<?xml version="1.0" encoding="utf-8" ?> <resources> <color name="splashscreencolor">#232323</color> <style name="StartUpAppTheme" parent="android:Theme.Holo.Light"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@color/splashscreencolor</item> </style> <style name="AppTheme" parent="android:Theme.Holo.Light"> </style> </resources>
b. In the native MainActivity, have the activity start with the Theme.Splash and then have it running with the AppTheme:
[Activity(Theme = "@style/Theme.Splash"", MainLauncher = true, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize)] public class MainActivity : FormsApplicationActivity { protected override void OnApplyThemeResource(global::Android.Content.Res.Resources.Theme theme, int resid, bool first) { base.OnApplyThemeResource(theme, Resource.Style.AppTheme, first); } ... }
Friday, October 03, 2014
Configure app which requires admin rights to run at startup with task scheduler
App which requires elevated admin rights can’t just be set to run at startup by adding it to the registry key (HKLM\Software\Microsoft\Windows\CurrentVersion\Run) because it mail fail to start since it requires the UAC prompt. Windows will silently fail to display the UAC prompt.
One solution is to make the app a Windows Service, but depending on the technology used, this might not be possible. For example, a .NET Windows Service which is using .NET API printing (System.Printing) is not recommended (see http://blogs.msdn.com/b/dsui_team/archive/2013/06/24/printing-from-a-windows-service.aspx or see ‘Caution’ in http://msdn.microsoft.com/en-us/library/system.drawing.aspx).
So another solution is to use task scheduler.
When configuring the scheduled task, you need to make sure:
1. In the task properties popup, "Run with highest privileges" option is checked.
2. In the "Edit Action" popup, "Start in" is filled with the directory path (Do not include quotation marks or a trailing slash)
Tuesday, September 02, 2014
Duplicate folders issue with MvvmCross by NuGet
EDIT: Issue is fixed in MVVMCROSS v3.2.1 !
With the current NuGet version of MvvmCross, when adding it to the project you get duplicate folders (‘Layout’ and ‘layout’, ‘Values’ and ‘values’)
To fix this, right click on the project and choose ‘Tools \ Edit File’ in Xamarin Studio. In Visual Studio, there’s a similar way.
In the .csproj, you just need to replace the first upper case letter with lower case letter, so replace ‘Layout’ with ‘layout’ and ’Values’ with ‘values’ and save the file.
Tuesday, August 05, 2014
Auto binding of outlets in Xamarin iOS and MvvmCross
If you are like me and you don’t like doing the bindings in code, you start thinking about solutions.
So I’m experimenting with the idea of creating the bindings at runtime, based on a simple name convention:
- An UIButton outlet with the name 'btnXXX' is bound to the view-model 'XXXCommand' property.
- An UITextField outlet with the name 'txtXXX' is bound to the view-model 'XXX' property.
- An UILabel outlet with the name 'lblXXX' is bound to the view-model 'XXX' property.
For example, if you have a UIButton outlet called btnLogin, it's bound to view-model LoginCommand property.
I uploaded the code here;
https://github.com/nitescua/AutoBinding/
This can be done for other platforms as well.
Tuesday, July 29, 2014
Xamarin HttpClient NameResolutionFailure exception
If you look on internet there are plenty of people reporting this error.
Xamarin is somehow aware of this error, and it marked it as fixed but it doesn’t seem like it is.
Fortunately, this exception appears only in debug mode, not in release mode.
Android–deployment error - INSTALL_FAILED_UPDATE_INCOMPATIBLE
When trying to deploy on device I got this error:
Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]
Deployment failed. Internal error.
To fix it, run:
C:\Users\[YourUserName]\AppData\Local\Android\android-sdk\platform-tools>adb uninstall com.xxx.yyy
Don’t include the .apk file extension
Monday, May 26, 2014
Publish empty folders
If you need to include an empty folder when deploying using MSDeploy (either manually from Visual Studio or calling msdeploy from scripts) you can do that by:
1. create a Web Publishing Pipeline file (.wpp.targets)
Create a new XML file in the project folder (the same folder that holds the .csproj or .vbproj file) and name it <projectname>.wpp.targets.
2. Add the following
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AfterAddIisSettingAndFileContentsToSourceManifest>MakeEmptyFolders</AfterAddIisSettingAndFileContentsToSourceManifest>
</PropertyGroup>
<Target Name="MakeEmptyFolders">
<Message Text="Adding empty folder to hold downloads" />
<MakeDir Directories="$(_MSDeployDirPath_FullPath)\Survey\responses"/>
</Target>
</Project>
In my case I needed an empty folder called ‘responses’ inside an existing ‘Survey’ folder.
The folder will be created no matter which configuration or publishing profile is run.
More info:
http://msdn.microsoft.com/en-us/library/ff398069(v=vs.110).aspx
http://blog.alanta.nl/2011/02/web-deploy-customizing-deployment.html
Monday, April 07, 2014
A busy MvxViewController for MvvmCross + iOS
In my MVVMCross apps, in the shared PCL core library, I usually have a MvxViewModel derived class called ViewModelBase with a IsBusy property:
public class ViewModelBase : MvxViewModel
{
bool isBusy;
public bool IsBusy
{
get { return this.isBusy; }
set { if (this.isBusy != value) { this.isBusy = value; this.RaisePropertyChanged("IsBusy"); } }
}
// other base stuff in ViewModelBase
}
For iOS the control can be UIActivityIndicatorView.
But instead of placing a UIActivityIndicatorView on each view, we can dynamically create it at run-time when IsBusy property changes to true.
We can have this implemented in a ViewController base class like this:
using System;
using System.ComponentModel;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using Cirrious.MvvmCross.Touch.Views;
using Cirrious.CrossCore.WeakSubscription;
using YourApp.Core.ViewModels;
namespace YourApp.Touch
{
public abstract class MvxViewControllerBase : MvxViewController
{
// weak subscription to NotifyProperty event
IDisposable npSubscription;
public override void ViewDidLoad()
{
base.ViewDidLoad();
// subscribe to view-model's PropertyChanged
this.npSubscription = ((INotifyPropertyChanged)this.ViewModel).WeakSubscribe<bool>("IsBusy", (s, e) => { this.UpdateActivityIndicatorView(); });
// at this point view-model exists, so update the indicator view
this.UpdateActivityIndicatorView();
// add other common UIViewController stuff
}
protected override void Dispose(bool disposing)
{
if (disposing && this.npSubscription != null)
{
this.npSubscription.Dispose();
this.npSubscription = null;
}
base.Dispose(disposing);
}
void UpdateActivityIndicatorView()
{
// get the activity indicator
var activityIndicatorView = (UIActivityIndicatorView)this.View.ViewWithTag(1000);
var vm = (ViewModelBase)this.ViewModel;
if (vm.IsBusy)
{
// show busy indicator. create it first if it doesn't already exists
if (activityIndicatorView == null)
{
activityIndicatorView = new UIActivityIndicatorView(this.View.Frame)
{
ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray,
Tag = 1000
};
this.Add(activityIndicatorView);
this.View.BringSubviewToFront(activityIndicatorView);
activityIndicatorView.StartAnimating();
}
// show the activity indicator
activityIndicatorView.Hidden = false;
}
else
{
// hide the activity indicator
if (activityIndicatorView != null)
{
activityIndicatorView.Hidden = true;
}
}
}
}
}
Please let me know if you see any possible issues.
I am thinking to do a similar implementation for other platforms as well.
Maybe MVVMCross could support out of the box a similar implementation. A built in implementation in MVVMCross would probably require to be able to override the style for the indicator.