dimanche 21 mars 2021

Xamarin forms : access controls inside a CarouselView

Hi everyone,

By working on one of my project, I had to implement the wonderful CarrouselView. Actually, I think this control was really well written because it takes into account MVVM in some important itemporperties and events (see mircosoft doc for more info)

But I spend some time on a problem: how can I access control inside this carrousel if I want to interact with one of the child control? This becomes a bit tricky.

As any dev, I start by google it,  and the anwser was blurry.

So I decided to do by my own:

Watchout: 

  • this solution described in this article is not the most elegant, but I will at the end give some tips in order to the clean the code 😃 
  • I volontary did not use MVVM due to the separtion of the UI and the "business". 


Here are the "data" sources  classes:


The xaml that manage the carousel. You can see that is composed with a boxview, a label and a button. No rocket science. This boxview displays a color, a label displays the name of the color, and the button wants to launch a message box (displayAlert) with a simple message

In the constructor, I bind my item source

Here comes then the problem, if we wants to find any control inside de carousel, there is no way to access it


So, instead of tying to access the value, we can by code retrieves the several childeren

Let's explain quickly how to find the conrols:

  1. Get the carrousel control via the command this.Content.FindByName<CarouselView>("MyCarrousel");
  2. Get all the control inside the carrousel control via the command: caroussel.VisibleViews;

By this, we have all the conrols inside the carousel. In my example, I have volontary added a Grid, once the grid accessed, I get the controls and now, I can work with them.

Clean code


It could have been over, but you and I knows that this code is not clean at all, and the main problem is if we change any position of a control, this code either use the wrong control or crash.

So instead of  using the index of the device, it's esier to loop (with a foreach loop) any childeren against the type of control used. (don't forget to cast when you find the device)
Once again, I intentionnaly don't show the full answer, just to let you exercice yoursel

have fun.







dimanche 22 octobre 2017

Mircosoft annonce la fin du service Groove... Quid de mes apps?

Bonjour à tous,

Début octobre, Microsoft a envoyé un message nous signifiant l’arrêt du service groove, de sa musique et de ses api.
En tant qu'acteur sur le marché, ça a du sens. Par contre pour tous les développeurs, c'est quand même une tuile.

Microsoft préconise donc à ses utilisateur de migrer vers Spotify

Quand est il niveau dev? En faisant mes recherches sur les api Spotify: Je les ai trouvé assez compliqué à utiliser.

J'ai evalué les (le) concurrent(s) et je me suis rendu compte que Deezer faisaient parfaitement l'affaire. A tel point que je me suis même demandé pourquoi je n'ai pas sauté sur Deezer il y a 2 ans. Des api claires et facile d’acces (au premier abord)

Maintenant il ne reste plus qu'a implémenter tout.

Je documenterai les étapes de développement.

Bonne journée




mardi 9 mai 2017

Xamarin.forms : Add Splash screen (XF 2.3.4.234)

Hi all,

As I've installed VS2017, I took the time to do refactoring on my project in order to add new api.
So I've decide to start from a blank project and add my classes.

After several quirks, I've spent a lot of time to add a splash screen.
When I followed old fashion method or the method Xamarin describes on their website  I always had this error:
  • The file “obj\Debug\android\bin\packaged_resources” does not exist.

To solve that: It tooks time to find a correct sample all around the web.. but the sample (with project) to download in the xamarin website works well.


The main difference is : No layer list to create, and in the style.xml file,
there are those two more item

    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowActionBar">true</item>

Now everything works fine.

Good work.

lundi 28 septembre 2015

Utiliser les api de XboxMusic / Groove Music dans Windows 10

Bonjour à tous,

Voici un nouvel article afin de vous aider à vite incorporer de la musique en streaming sous Windows 10.
Ceci fonctionne aussi bien pour les autres plateformes Windows (W8,W8.1,WP8.0, WP8.1 (silverlight et RT)) (je n'ai pas encore testé android et IPhone sous Xamarin)

Cet exemple traité est juste la diffusion des 30 sec de streaming de présentation d'une chanson.

L'étape prerequis de lancer Visual Studio --> File--> new project, est surement acquise, donc je ne ferais pas l'affront d'en parler ici :-)

Première étape:

Se connecter au site de microsoft music et suivre les étapes pour obetnir une clé sur Azure. Tout est clairement expliqué sur le site


Seconde étape

Le plus simple est de télécharger le code mis en ligne sur Github . Il est complet et on peut réutiliser  toutes les fonctions : les infos sur un artiste, albums, chansons, Photos ...



Troisième étape

Télécharger la dernière version package XboxMusic sur nuget :-) . Lors de l'écriture de cet article nous sommes à la version 1.7.0





Quatrième étape

Télécharger la dernière version de la librairie JSON sur nuget 




Cinquième étape

Pour faire simple, j'ai créé un petit folder pour y mettre toutes les assemblies dont j'ai besoin.
Celles-ci sont disponibles pour la plus part dans le projet téléchargé précédemment
 sous github

voici les différentes assemblies à avoir: 
  • Microsoft.Threading.Tasks
  • Microsoft.Threading.Tasks.Extensions
  • Microsoft.Xbox.Music.Platform.Client
  • Microsoft.Xbox.Music.Platform.Contract
  • System.Net.Http.Extensions
  • System.Net.Http.Primitives

Sixième étape:

Il suffit juste d'importer le tout dans votre pojet. Je vais mettre un exemple pour jouer un morceau 

Dans cet exemple il y a un simple bouton et un MediaElement pour jouer le son.

Et le tour est joué 


Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Microsoft.Xbox.Music.Platform.Client;
using Microsoft.Xbox.Music.Platform.Contract.DataModel;


// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace MusicBoss
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        protected static string ClientInstanceId { get { return "XboxMusicClientTests12345678901234567890"; } }
        private IXboxMusicClient _client;
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _client = XboxMusicClientFactory.CreateXboxMusicClient("AzureProjectNAme", "AzureKey");
                
                string val = "music.F6DE7208-0100-11DB-89CA-0019B92A3933";
                StreamResponse son = await _client.PreviewAsync(val, ClientInstanceId, null);

                PrevMed.Source = new Uri(son.Url, UriKind.RelativeOrAbsolute);
               

                PrevMed.Play();
            }
            catch (FileNotFoundException ex)
            {
                string mess = ex.Message;
                throw;
            }
           
        }
    }
}

dimanche 13 septembre 2015

Reprise

Bon,

Ca fesait un petit bout de temps que je n'avais plus rien publié.
La tout, je suis de retour avec pas mal d'expérience en plus

Oracle (même si je deteste)
SQL server
Windows 10 universal app
Xamarin
Azure mobile app
Unit Testing
VS2015 - C#6
...

Aussi un peu plus de gestion de projets...

Stay tunes ;-)

mardi 22 juillet 2014

SQL server 2008: Unpredictable sort order from a select - Ordre de trie imprevisible lors d'un select

Hi all, I Just found a strange problem...
using SQL server 2008 with a large amount of data. I've created a query that just select a list of devices by serial number.
My select query of course returns all the set of data BUT not in the order I entered it!!!

This article confirms my problem

default-sort-order-when-using-select-no-order-clause

I'm searchin for a solution..


Bonjour à tous,

Je viens de tomber sur un problème assez etrange. Je crée un requete via sql server 2008 qui selectionne une liste de compteurs par numéro de série. Cette liste est bien sur qu'une partie de la totalité de mes compteurs.

Le soucis est que le résultat de ma requète ne reviens pas dans l'ordre dans laquelle ma requête fut faite.

Cette article en anglais parle du problème

default-sort-order-when-using-select-no-order-claus


samedi 29 juin 2013

WP7 binding problem: System.MethodAccessException: Attempt to access the method failed

This an easy and simple problem I faced recently but I waste a lot of time to understand it

For me this problem occured with VS2012 and WP7 project! 

So I explained my project was a simple soundboard.
This soundoard is just composed by a ListBox, and the datatemplate is composed by two buttons and one textbox.

When I build the project and I run it to the emulator

  1. It tooks a lot of time to load and run
  2. Buttons and text filed are empty
But in the Xaml and code, every fields are binded correctly.

Just by looking at the output windows, I had this message

"System.Windows.Data Error: Cannot get 'Description' value (type 'System.String') from 'BoardField' (type 'BoardField'). BindingExpression: Path='Description' DataItem='BoardField' (HashCode=84854501); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.MethodAccessException: Attempt to access the method failed: .BoardField.get_Description()
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.RuntimePropertyInfo.InternalGetValue(PropertyInfo thisProperty, Object obA first chance exception of type 'Microsoft.Advertising.Shared.AdException' occurred in Microsoft.Advertising.Mobile.dll
A first chance exception of type 'Microsoft.Advertising.Shared.AdException' occurred in Microsoft.Advertising.Mobile.dll
A first chance exception of type 'Microsoft.Advertising.Shared.AdException' occurred in Microsoft.Advertising.Mobile.dll
A first chance exception of type 'Microsoft.Advertising.Shared.AdException' occurred in Microsoft.Advertising.Mobile.dll
A first chance exception of type 'Microsoft.Advertising.Shared.AdException' occurred in Microsoft.Advertising.Mobile.dll
The program '[247333058] TaskHost.exe: Managed' has exited with code 0 (0x0)."


So, it seems that there is an accesibility problem.. By reading the info coming from this exception. It looks like it came from the class that contains data. Here is the class that cause problem


Code:
class BoardField
    {
        public string Hero { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
        public string Description { get; set; }
        public string Language { get; set; }
    }

Just by adding the accessor "public" 
Code:
public class BoardField
    {
        public string Hero { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
        public string Description { get; set; }
        public string Language { get; set; }
    }


So it seems that the for a WP7 project on WS2012 has wrong settings at project start.

Good Work