Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 79144 articles
Browse latest View live

Firebase Authentication .net Token Expired

$
0
0

I'm using Firebase Authentication and the auth token keeps on expiring.

My Auth Service

`
public class FirebaseAuthService
{
IFirebaseAuthProvider authProvider;

    public FirebaseAuthService()
    {
        authProvider = new FirebaseAuthProvider(new FirebaseConfig(Config.ApiKeys.FirebaseApiKey));
    }

    public async Task<FirebaseAuthLink> LoginUser(string email, string password)
    {
        var auth = await authProvider.SignInWithEmailAndPasswordAsync(email, password);

        SaveAuth(auth);
        // save the new token each time it is refreshed
        auth.FirebaseAuthRefreshed += (s, e) => SaveAuth(e.FirebaseAuth);
        // use the token and let it refresh automatically (can be part of FirebaseOptions for access to Firebase DB)
        return await auth.GetFreshAuthAsync();
    }


    public async Task<FirebaseAuthLink> SignupUser(string email, string password)
    {
        var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(email, password);

        SaveAuth(auth);
        // save the new token each time it is refreshed
        auth.FirebaseAuthRefreshed += (s, e) => SaveAuth(e.FirebaseAuth);
        // use the token and let it refresh automatically (can be part of FirebaseOptions for access to Firebase DB)
        return await auth.GetFreshAuthAsync();
    }


    private void SaveAuth(FirebaseAuth auth)
    {
        string json = JsonConvert.SerializeObject(auth);
        Settings.FirebaseAuthJson = json;
        Preferences.Set("logged", true);
    }

    public Task<string> GetFreshToken()
    {
        //load token from storage
        var auth = new FirebaseAuthLink(authProvider, LoadAuth()); // LoadAuth returns FirebaseAuth, that can be saved in local storage
                                                                   // save the new token each time it is refreshed
        auth.FirebaseAuthRefreshed += (s, e) => SaveAuth(e.FirebaseAuth);
        // use the token and let it refresh automatically (can be part of FirebaseOptions for access to Firebase DB)
        // Return token

        return Task.FromResult(auth.FirebaseToken);
    }

    private FirebaseAuth LoadAuth()
    {
        string json = Settings.FirebaseAuthJson;

        if (string.IsNullOrEmpty(json))
        {
            return null;
        }
        else
        {
            return JsonConvert.DeserializeObject<FirebaseAuth>(json);
        }

    }

    public Task<string> GetUserUID()
    {
        var auth = LoadAuth();

        if (auth != null)
        {
            return Task.FromResult(auth.User.LocalId);
        }

        return null;
    }

    public Task Signout()
    {
        Preferences.Clear();

        return null;
    }

}

}

`

And i can't get to refresh token


Calling a method in the viewmodel from OnAppearing in codebehind

$
0
0

Hi,

I'm trying to populate a username and password in my xaml page when the page loads.
The strings in class LoginViewPageModel are LoginEmail and LoginPassword and have bindings to my text boxes, they work fine if I call from a command binding, but I want to change them when the page loads using a threaded task, and it doesn't work/I don't know how to do it, please help :smile:

I have my mainpage.xaml, and then I call a modal page in front of it - LoginPage.xaml - All good.

I have overridden onappearing in my LoginPage.xaml, and then I have a task run as async:

    protected override void OnAppearing()
    {
        base.OnAppearing();
        Task.Run(async () =>
        {
            // LoginPageViewModel.SetLoginDetails(); // this doesn't work as SetLoginDetails is not static

    // This doesn't work either as I'm creating an instance of the LoginPageViewModel, and then I am changing
    // _loginPageViewModel.LoginEmail, instead of LoginPageViewModel.LoginEmail
            LoginPageViewModel _loginPageViewModel = new LoginPageViewModel();
            _loginPageViewModel.SetLoginDetails();
        });
    }

In LoginPageViewModel.cs, I've got my method:
public async void SetLoginDetails()
{
try
{
LoginEmail = await SecureStorage.GetAsync("username");
Console.WriteLine("*** *** *** LoginEmail is: " + LoginEmail);

            LoginPassword = await SecureStorage.GetAsync("password");
            Console.WriteLine("*** *** *** LoginPassword is: " + LoginPassword);

        }
        catch (Exception ex)
        {
            // Possible that device doesn't support secure storage on device.
            Console.WriteLine("*** *** *** SetLoginDetails() exception: " + ex);
        }

    }

Navigation Title not centering on Android

$
0
0

I’ve set the navigation title in my Xamarin forms application as below:

    <NavigationPage.TitleView>
        <Grid>
            <Label Text="Settings" Style="{StaticResource NavTitle}"/>
            <Button Text="&#xf060;" Style="{StaticResource LeftNavButton}" Clicked="BackButtonClicked"/>
        </Grid>
    </NavigationPage.TitleView>

The Label has been centered, on iOS the positioning is fine but on Android it is shifted over to the right. I've set the navigation back button to be hidden with NavigationPage.SetHasBackButton(this, false) but it seems to still be pushing it over, does anybody have any insight to why it's shifted over on Android and not iOS?

Images attached, Thanks in advance!

Below is the styles for reference:

         <Style x:Key="LeftNavButton" TargetType="Button">
            <Setter Property="BackgroundColor" Value="Transparent"/>
            <Setter Property="TextColor" Value="White"/>
            <Setter Property="HeightRequest" Value="20"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="FontFamily" Value="{StaticResource FontAwesomeSolid}"/>
            <Setter Property="Padding" Value="0"/>
            <Setter Property="HorizontalOptions" Value="Start"/>
            <Setter Property="WidthRequest" Value="30"/>
            <Setter Property="Margin" Value="{StaticResource LeftButtonMargin}"/>
        </Style>

        <Style x:Key="NavTitle" TargetType="Label">
            <Setter Property="FontAttributes" Value="Bold"/>
            <Setter Property="TextColor" Value="White"/>
            <Setter Property="HeightRequest" Value="20"/>
            <Setter Property="FontSize" Value="17"/>
            <Setter Property="VerticalTextAlignment" Value="Center"/>
            <Setter Property="HorizontalTextAlignment" Value="Center"/>
            <Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
            <Setter Property="VerticalOptions" Value="CenterAndExpand"/>
        </Style>

Check GPS/location state

$
0
0

I need help with a simple task:

My app needs to check if the user has turned on gps/location or not. I cannot find a way to do this. I tried Plugin.Geolocator but cannot solve it although this seems to be a really basic task...

I'm facing the problem on Xamarin.Forms Android

Android app started crashing after updating to Visual Studio 16.7.0

$
0
0

I had two android apps that I have been working on start crashing on start up after updating to this VS 16.7.0 when debugged on a actual android device.
Both crash before any breakpoints can be hit.

In the output I got this (for both apps):

08-11 12:57:35.716 D/Mono (11135): DllImport error loading library '__Internal': 'Could not load library: Library '/system/lib64/libmonodroid.so' not found.'.
.
.
.
Native Crash Reporting
Got a SEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries

used by your application.
No native Android stacktrace (see debuggerd output).

=================================================================

Basic Fault Address Reporting
Memory around native instruction pointer (0x5f656b6f766e69):0x5f656b6f766e59
08-11 12:57:37.769 W/idjoey.hemproa(11135): 0xebadde09 skipped times: 0
08-11 12:57:37.770 F/libc (11135): Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x5f656b6f766e59 in tid 11135 (id.road), pid 11135 (idjoey.hemproad).

After trying a ton of things…
I had to create a blank mobile app, placed the android project into Road and carefully replace all the code and all the libraries in that empty android project with the original android road code and libraries. After doing that it now works fine.

But my question is why??? Why did this happen?
And for my second project do I need to fix it the painful way I fixed my first app?

How Handle Start/End Call events

$
0
0

Hi there,

I´m premising that I´m new with mobile development and actually I´m developing an App using Xamain.Forms and Xamarin.Essentials

Now my goal is to start a call programmatically and handle the events of start call and end call.

To start the call I´m using Xamarin.Essentials PhoneDialer and it is not a problem, but I cannot found the way to handle the events of that call, and in particular StartOfCall and EndOfCall.

Somebody can help ?

Thank you in advance

Can we consume REST with HTTPS self-signed as a Release (not as Debug)?

$
0
0

I'm running the Xamarin tutorial at https://docs.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/webservices-todorest/ and it is working fine in Debug mode. The project implements an InsecureHandler, to permit HTTPS to be used locally with a self-signed certificate in Debug mode. I've read the blog article by @DavidBritch which provides helpful background.

However, this is fine for debugging, but it doesn't appear to work when I run it as a Release, even if I modify #if DEBUG to invoke the insecure handler in Release mode. This is important because I need to be able to demonstrate the application on a physical device connected to our office LAN.

I can't understand why it doesn't work in Release mode, even if I force the insecure handler. I think the application is maintained by David and wonder if anyone, perhaps including David, can enlighten on this. What do I need to do in order to make the insecure handler work in Release mode? I have even tried HTTP traffic, modifying the code (and the API) to support only HTTP on port 5000 and adding android:usesCleartextTraffic in the manifest, but for some reason that returns blank data also.

In RestService.cs it applies the test to determine if we're using Debug. It reads from the URL and deserialises the contents, but in Release mode, nothing is returned, despite overriding that compile-time directive.

        public RestService()
        {
#if DEBUG
            client = new HttpClient(DependencyService.Get<IHttpClientHandlerService>().GetInsecureHandler());
#else
            client = new HttpClient();
#endif
        }
        public async Task<List<TodoItem>> RefreshDataAsync()
        {
            Items = new List<TodoItem>();
            Uri uri = new Uri(string.Format(Constants.RestUrl, string.Empty));
            try
            {
                HttpResponseMessage response = await client.GetAsync(uri);
                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    Items = JsonConvert.DeserializeObject<List<TodoItem>>(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(@"\tERROR {0}", ex.Message);
            }
            return Items;
        }

Meanwhile, as I think I understand it, within HttpClientHandlerService.cs it implements an HttpClient returning a local certificate without errors.

[assembly: Dependency(typeof(HttpClientHandlerService))]
{
    public class HttpClientHandlerService : IHttpClientHandlerService
    {
        public HttpClientHandler GetInsecureHandler()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                if (cert.Issuer.Equals("CN=localhost"))
                     return true;
                return errors == System.Net.Security.SslPolicyErrors.None;
            };
            return handler;
        }
    }
}

FontAwesome in iOS doesn't work

$
0
0

In my app, I put the fonts in the main project and export the fonts from the AssemblyInfo.cs like:

[assembly: ExportFont("FontAwesome5BrandsRegular.otf", Alias = "FontAwesomeBrands")]
[assembly: ExportFont("FontAwesome5Solid.otf", Alias = "FontAwesomeSolid")]
[assembly: ExportFont("FontAwesome5Regular.otf", Alias = "FontAwesomeRegular")]

[assembly: ExportFont("InterMedium.ttf", Alias = "InterMedium")]

All fonts are working. I'm facing an issue only with FontAwesome in iOS. What I see on the iOS app is:

but in Android is working fine.


Bluetooth BLE help

$
0
0

Hi,
I'm relatively new to Xamarin, but I am trying to make an app that communicates from the phone/tablet to a BLE module (connected to a MCU). The app needs to be able to request specific data form the MCU, and then display the received data. I have looked into plugins like this one: github.com/xabre/xamarin-bluetooth-le but all the coding in this is a bit too advanced for me to understand at the moment. These plugins also seem to include the functionality of connecting to Bluetooth devices from the app itself, but is it also possible to connect to a device using the phones own Bluetooth menu (in settings) and then just deal with the communication in the app?
Any help on this is highly appreciated, as it is all very new to me at the moment.
Thanks,
Sophie

How To Store User Session To Stay Logged In

$
0
0

Hi everyone. How can i store the user session data to stay logged in?

Thanks!

Min required to handle deep links in Xamarin Forms

$
0
0

James Montemagno has some great blogs online to help Xamarin Forms developers with application indexing and deep linking, but what if we only need to handle deep links? What’s the bare minimum necessary?

It seems that I don’t need the Xamarin.Forms.AppLinks NuGet package or to register the application or website in Google's Developer Console. There’s also no need to create and register AppLinkEntry instances or place a Assets.json file. I just need to configure the intent filter.

My problem, however, is that all of the examples show the intent filter applied to the MainActivity. Because of that, each time a deep link is clicked it creates a new instance of the Forms app because of the LoadApplication(new App()) call. There’s a hefty performance hit for that, and in my case it kicks off a bunch of initialization and login stuff that really doesn’t need to be run more than once.

I noticed that apps like Facebook and LinkedIn have created a separate activities to handle the intent filters for deep links, but when I try that I find that my OnAppLinkRequestReceived() method is never called.

All I’m really looking for here is to handle a deep link with minimum code and without spawning additional instances of the Forms app. Could anyone point me to an example on how to do that without all the indexing baggage?

Email with PDF

$
0
0

Found this to mail a txt file with some tekst using Xamarin.Essentials .

var message = new EmailMessage
{
    Subject = "Hello",
    Body = "World",
};

var fn = "Attachment.txt";
var file = Path.Combine(FileSystem.CacheDirectory, fn);
File.WriteAllText(file, "Hello World");

message.Attachments.Add(new EmailAttachment(file));

await Email.ComposeAsync(message);

On Android phone this is working but not PDF as attachment

With PDF from recourse i have an error , cannot find PDF

The PDF is as embedded recourse and copy always

What is wrong or am i missing ?

var message = new EmailMessage
            {
                Subject = "Hello Jopie",
                Body = "World",
            };


            var file = "Mailmetpdf. Doc.Baljeugd.pdf";


            message.Attachments.Add(new EmailAttachment(file));

            await Email.ComposeAsync(message);

Cannot find Mailmetpdf. Doc.Baljeugd.pdf

App crashing in android while sending email with attachment using Xamarin essential

$
0
0

App is crashing after launching email client with attachment (more than 400 kb) in android device using xamarin essential for email client.

Tried in native implementation as well, there also same result, sending txt file attachment.

Please find the attached screenshot for your reference.

Below code for sending email.

List<string> recipients = new List<string>() { recipient };
            var message = new Xamarin.Essentials.EmailMessage
            {
                Subject = subject,
                To = recipients,
                Body = "Body"
            };

            var logFile = Path.Combine(FileSystem.CacheDirectory, FileName);
            File.WriteAllBytes(logFile, Encoding.ASCII.GetBytes(LogFileText));
            message.Attachments.Add(new Xamarin.Essentials.EmailAttachment(logFile));
            AddAttachments(message);
         **   await Email.ComposeAsync(message);** // after executing this line app will crash

How to draw on Image captured from camera and then save it.

$
0
0

Hi,
I want to draw on image to highlight specific part of the image(draw circle etc.) and then save highlighted image.

Xamrin form

$
0
0


help me to desin this screen,how we split the screen and design this UI


SwipeView: Threshold for Execution

$
0
0

I would like to use a Swipe to execute a delete-action. But the User has to swipe up to 80% of the whole Swipe-Area to execute it. That is far too long. I would like to define my own threshold / length. How can I achieve that and why is this not implemented in the first place ? That is so obvious !?

Xamarin Forms: Selected items get cleared when perform search in listview

$
0
0

I have done the fetching of contacts from the phone using this blog.

Now I am trying to add the selection of contacts. Using a switch I have done the selection. But the selected contacts are clearing when performing a search operation.

xaml

<Switch
    Toggled="OnToggledEvent"
    HorizontalOptions="EndAndExpand"
    VerticalOptions="CenterAndExpand"/>

xaml.cs

public List<Contact> contactList;
public MainPage(IContactsService contactService)
{
    InitializeComponent();
    contactList = new List<Contact>();
    BindingContext = new ContactsViewModel(contactService);
}

void OnToggledEvent(object sender, EventArgs args)
{
    ViewCell cell = (sender as Xamarin.Forms.Switch).Parent.Parent as ViewCell;
    if (cell.BindingContext is Contact)
    {
        Contact contact = cell.BindingContext as Contact;
        if (contact != null)
        {
            if (contact != null && !contactList.Contains(contact))
            {
                contactList.Add(contact);
            }
            else if (contact != null && contactList.Contains(contact))
            {
                contactList.Remove(contact);
            }
        }
    }
    Debug.WriteLine("contactList:>>" + contactList.Count);
}

ContactsViewModel

public class ContactsViewModel : INotifyPropertyChanged
{
    IContactsService _contactService;

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public string Title => "Contacts";


    string search;
    public string SearchText
    {

        get { return search; }

        set
        {

            if (search != value)
            {
                search = value;
                OnPropertyChanged("SearchText");

                if (string.IsNullOrEmpty(SearchText))
                {
                    FilteredContacts = new ObservableCollection<Contact>(Contacts);

                }

                else
                {

                    FilteredContacts = new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));

                }
            }

        }

    }

    public ObservableCollection<Contact> Contacts { get; set; }

    ObservableCollection<Contact> filteredContacts;
    public ObservableCollection<Contact> FilteredContacts
    {
        get { return filteredContacts; }

        set
        {

            if (filteredContacts != value)
            {
                filteredContacts = value;
                OnPropertyChanged("FilteredContacts");
            }
        }
    }
    public ContactsViewModel(IContactsService contactService)
    {

        _contactService = contactService;
        Contacts = new ObservableCollection<Contact>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts, null, ObservableCollectionCallback);
        _contactService.OnContactLoaded += OnContactLoaded;
        LoadContacts();
        FilteredContacts = Contacts;
    }


    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        // `lock` ensures that only one thread access the collection at a time
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    private void OnContactLoaded(object sender, ContactEventArgs e)
    {
        Contacts.Add(e.Contact);
    }
    async Task LoadContacts()
    {
        try
        {
            await _contactService.RetrieveContactsAsync();
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Task was cancelled");
        }
    }
}

I am adding the selected contact to a list when toggling the switch. If again click the switch I will remove the contact from the list. But the problem is when searching for a contact, already selected contacts get clear. I try to fix this using IsToggled property of switch, but no luck.

I have added a sample project here for the reference.

How to make xamarin.forms shell page's status bar transparent?

$
0
0

`var uiOps = SystemUiFlags.LayoutStable | SystemUiFlags.LayoutFullscreen | SystemUiFlags.ImmersiveSticky | SystemUiFlags.Immersive;
Window.DecorView.SystemUiVisibility = (StatusBarVisibility)uiOps;
Window.SetStatusBarColor(Android.Graphics.Color.Transparent);

        Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.KeepScreenOn);
        Window.AddFlags(WindowManagerFlags.TranslucentStatus);`

I have set the transparent flags but it still gray.

How to fire a "Complete" event from ViewModel?

$
0
0

I have a entry with complete action:
<local:BaseEntry Placeholder="Email Address" Keyboard="Email" x:Name="EmailEntry" ReturnType="Next" Completed="{Binding GoToPassword}"/>

I want to focus to the next entry when user press done button from keyboard.
So how to perform Completed action from ViewModel?

why the two elements' width not equal? in a collectionview line ?

$
0
0

Here is my code:

          <CollectionView Margin="10.33,0,10.33,0" ItemsSource="{Binding Items}" VerticalScrollBarVisibility="Never">
                    <CollectionView.ItemsLayout>
                        <GridItemsLayout Span="2" Orientation="Vertical" HorizontalItemSpacing="22.5" VerticalItemSpacing="10" SnapPointsAlignment="Center"/>
                    </CollectionView.ItemsLayout>
                    <CollectionView.ItemTemplate>
                        <DataTemplate>
                            <StackLayout BackgroundColor="Orange" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                                <ff:CachedImage HeightRequest="96.33" HorizontalOptions="FillAndExpand" Source="{Binding ImageUrl}" Aspect="AspectFit" VerticalOptions="FillAndExpand"/>
                                <StackLayout MinimumHeightRequest="44">
                                    <Label Text="{Binding Name}" TextColor="#000000" FontSize="14" Margin="0,7.67,16,7" LineBreakMode="TailTruncation" MaxLines="2" MinimumHeightRequest="31.33"/>
                                </StackLayout>
                                <FlexLayout JustifyContent="SpaceBetween" AlignItems="Center">
                                    <StackLayout Orientation="Horizontal">
                                        <Label Text="¥" FontSize="8.67" TextColor="#ff0000" VerticalOptions="CenterAndExpand"/>
                                        <Label Text="{Binding Price}" TextColor="#ff0000" FontSize="14"/>
                                    </StackLayout>
                                    <Image Source="icon_cart.png" WidthRequest="19.67" HeightRequest="16"/>
                                </FlexLayout>
                            </StackLayout>
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>

Here is the view:

The first one 's width is bigger than the second one

Viewing all 79144 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>