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

How to make a http get from Secured API with google account connection

$
0
0

Hello,

I did an api, for the exemple i will call it: https:// testapp.azurewebsites.net

I did the Authentication / Authorization in Azure for google Facebook and Microsoft account.

Then i want to consume it in xamarin for my Android/iOS app, so i did the login button etc but when I'm authentify i can't get the json of my api URL: "https:// testapp.azurewebsites.net/api/Test/allCoordinates".

It work's perfectly in my browser and in postman... This is my code in C#:
var requestCoord = new OAuth2Request("GET", new Uri(URL),null , e.Account); var responseCoord = await requestCoord.GetResponseAsync(); //it works for google userinfo but not for my Api... string coordJson = await responseCoord.GetResponseTextAsync(); var mapTest = JsonConvert.DeserializeObject<List<CustomPin>>(coordJson);

I got a message : System.Net.HttpStatusCode.Unauthorized for the var responseCoord .

If you have any idea to make this Http Get from protected webapi i will help me so much !!!

Thanks a lot

If you need more precision let me know;)
I use this tuto to be authentify : https:// github.com/CuriousDrive/PublicProjects/tree/master/OAuthNativeFlow and https:// docs.microsoft.com/fr-fr/xamarin/essentials/web-authenticator?tabs=android


Gesture recognizers and portability

$
0
0

I have a CollectionView and am using a gesture recognizer to trap a double-tap event. I also have the CollectionView enabled for Single select. This all seems to work with the UWP version, but on Android I don't get the double tap. I can see the single selection working, but the double taps don't seem to be recognized. Any help is greatly appreciated. Thanks.

How to find the cause of: Xamarin.Forms targets have been imported multiple times

$
0
0

I'm working my way thru the book "Creating Mobile Apps with Xamarin Forms" and a lot of the sample code requires some work to get it running, which is all very educational and helps me learn and remember. However I can't find the cause of this one;
Chapter 20, MandelbrotProgress, gives me an error in the Xamarin.Formsbook.Toolkit project:

Xamarin.Forms targets have been imported multiple times. Please check your project file and remove the duplicate import(s).

Can somebody point me at the root cause of this please. I cannot find any obvious duplicates in the project file, but there are some error conditions defined in there which I am suspicious of.

Also, is there a specific forum or support area for the above mentioned book?

Xamarin Forms Survey Binding Issues

$
0
0

Hello All,

I’m trying to create a survey within my main project and I’m having binding issues. The survey for the main project will have about 60 questions and there will be about 5 different ways to answer the questions. For example, there will be control types such as, DatePicker, Slider, Entry, Picker, and MultiSelect(Checkboxes). Through some research, I’ve been able to create 5 different DataTemplates for each control type and I’m using a CarouselView’s ItemTemplate to change each DataTemplate(Page). For convenience, I’ve created a small sample project that reads json from a text file which creates 6 questions. Each question is a page. When using the next & previous buttons, I’m keeping track of the current page with a property in the viewmodel. Also, I’m using a switch statement for the control types to assign values to the appropriate property in the codebehind. See small example below:
var page = _vm.SurveyPages.Where(p => p.PageNumber == _vm.CurrentPage).First();
switch (page.Question.ControlType) { case "entry": _vm.SelectedEntryAnswer.SelectedEntryAnswer = page.Question.SelectedEntryAnswer; break;

My problem is that my bindings lose their values when I go back using the previous button. For example, when I use the picker control to select “Male” or “Female”, go to next page and use the slider, go to next page and input text in the entry control, and click the next button. After that click the previous button until you get to the picker page again. You will notice that the selection you chose is no longer selected. When debugging, the last setter call to the property it’s bound to, the value is null, which is why the selection is no longer there. I cannot figure out why this is happening.

My goal is to for the pages to keep all the answers set on them even when moving to next or previous page. That way once the user finishes, I can submit the answers to the database. If anyone can help me figure out why my values are not persisting through the page navigation, it would be much appreciated. My other problem is I do not know how to access my controls in my datatemplates. I’ve tried solutions available such as FindVisualChildren, but I could not seem to get it to work. I’ve been on this for over 2 weeks now and I am at my wits end. I don’t want to write hacky code in order to move forward, because I believe there is a better way to achieve what I’m trying to do. I’m new to these forums, so if there’s anymore info needed please ask.

Thank you in advance!!!

P.S. This sample project uses Xamarin Forms, MVVM, and is tested using a Android Phone.

Xamarin.Forms CardsView nuget package

$
0
0

Hi all) I've released new package for Xamarin.Forms (Something like Tinder's CardsView)
Maybe, someone will be interested in it

nuget.org/packages/CardsView/ -- nuget
github.com/AndreiMisiukevich/CardView -- source and samples

Is it possible to change binding behavior for Entry.Text

$
0
0

When I bind a view model property to Entry.Text the property is updated every time something changes in the Entry, literally after each button press. Maybe it is desired behavior for most but in my case a better behavior would be to update the view model property only after Entry loses the input focus. Is it possible to change the behavior to what I need? I assume I can figure out how to implement what I need in other way but first I would like to make sure that I didn't miss anything.

Dynamic Form data Binding to carousel view ItemSource property

$
0
0

Hello All,
I need to display dynamic forms in the carousel view. The form gets generated based on the JSON response from API and I have to show that particular form in the carousel view.

I am able to integrate my content view with some static content to the carousel view using this "CardsView(2.6.1) "package.

However, I am stuck at the data binding part because my content view is actually a dynamic form on which the data gets populated based on the JSON response from API. So, how can I create and bind the dynamic model to ItemSource Property of the carousel view?
Thanks in advance.

Dynamic Form data Binding to carousel view ItemSource property

$
0
0

Hello All,
I need to display dynamic forms in the carousel view. The form gets generated based on the JSON response from API and I have to show that particular form in the carousel view.

I am able to integrate my content view with some static content to the carousel view using this "CardsView(2.6.1) "package.

However, I am stuck at the data binding part because my content view is actually a dynamic form on which the data gets populated based on the JSON response from API. So, how can I create and bind the dynamic model to ItemSource Property of the carousel view?
Thanks in advance.


Writing to Android External Storage

$
0
0

I'm trying to copy an sqlite database file to an accessible location in the external storage.

Here's the code below:

`private void CopyDatabaseFile(string dbPath)
{
    var destPath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath, "database.db");

    // Destination
    var destFile = new Java.IO.File(destPath);
    var canWrite = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CreateNewFile();
    var canRead = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).CanRead();
    if (!destFile.Exists())
    {
        try
        {
            var result = destFile.CanWrite();
            destFile.CreateNewFile();
        }
        catch (Java.IO.IOException ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error Message: {ex.Message}");
            System.Diagnostics.Debug.WriteLine($"Error Source: {ex.Source}");
        }
    }
}`

This is catching a Java.IO.IOException and the error message is Permission denied.

Although i have tried enabling read / write permission for external storage in androidmanifest.xml like this:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

However, i'm getting the same error message.

Any suggestion would be appreciated. :)

How to use custom font (external font) in WebView as Embedded Resource in Xamarin Forms?

$
0
0

Xamarin Forms 4.5 introduced a new way to add Custom font (External font) as an Embedded Resource in our project, so that Font file needs to be added only in the shared project and not in every project such as Android iOS and UWP. Please note that I am using this approach.

Now coming to the question, I want to use Custom Font as an Embedded Resource in a WebView in Xamarin Forms. How to do it. I have done all the prerequisites for it, like Set Build Action - EmbeddedResource, added ExportFont Code as specified here. Also please note that I can use Custom font on a Label and Button in my Page. I just want to use the same Embedded Font in a WebView.

Here is my XAML code:

<WebView x:Name="SampleWebView" HeightRequest="400" />

The Code Behind C#:

private void RenderTextOnWebView()
{
    HtmlWebViewSource htmlSource = new HtmlWebViewSource();
    htmlSource.Html = @"<html>
                        <head>
                            <style>
                                @font-face {
                                    font-family: myFirstFont;
                                    src: url(MyApplication/Fonts/MonotypeCorsiva.ttf);
                                }

                                div {
                                    font-family: myFirstFont;
                                }
                            </style>
                        </head>

                        <body>
                            <h1>The font Example</h1>
                            <div>With CSS, websites can finally use fonts other than the pre selected web - safe fonts.</div>                
                        </body>
                        </html>";

    SampleWebView.Source = htmlSource;
}

Portons of Copy/Pasted XAML excluded from Preview

$
0
0

Hello,

What is the best way to include XAML snippets in forum questions? Seems that the edit control excises portions of the XAML -- at least when viewed in Preview.

Thanks.

  • Dean

How can I include a link?

$
0
0

Hello everyone, I have a problem with Xamarin.Forms, I want to ask the question in this forum but I cannot include links in the message to show details. How can I do it? Regrets.

SetCurrentValue - set value without blowing away binding

$
0
0

I'm trying to create a reusable xaml control with some BindableProperties. One example property is called Text. The business logic of the control sometimes requires that we clear the text property. However, if I set the Text property (Text = string.Empty or SetValue(TextProperty, string.Empty)), my understanding is that I overwrite any bindings that may have been applied to that property. Instead, I want to "push the value" back through any existing binding that might be set. In WPF I accomplished this via DepedencyObject.SetCurrentValue().

  1. Am I understanding things correctly, that setting the property directly would blow away any bindings?
  2. Is there a way to achieve my desired behavior?

Can't play MP4 video in Android

$
0
0

Hi. I am trying to play a video in my application.

I placed my video "Dice65.mpg" in Android /Resources/raw directory.

My Xaml looks like this: (used brackets because the forum code kept hiding stacklayout and media element.
<ContentPage.Content>
[StackLayout]
[MediaElement x:Name="VideoPlayer" ShowsPlaybackControls="False" /]
[/StackLayout]
</ContentPage.Content>

My Xaml.cs looks like this:
public DiceRoll()
{
InitializeComponent();
VideoPlayer.Source = "ms-appx:///Dice65.mp4";
}

I get this error:
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

The documentation didn't seem to imply that anything else was needed. Am I missing something?

Thank you.

How does one disable a ShellContent in a ShellSection using Shell in Xamarin.Forms

$
0
0
    I have this in my Shell.xaml.

  <FlyoutItem Shell.TabBarIsVisible="False" Route="header" x:Name="FlyoutItem1"              FlyoutDisplayOptions="AsMultipleItems">
                    <ShellContent x:Name="BookItItem" Route="bookit" Title="BOOK IT" ContentTemplate="{DataTemplate views:HomePage}" />
<ShellSection x:Name="ExploreItem" Route="explore" Title="EXPLORE">
                    <ShellContent ContentTemplate="{DataTemplate subs:ExplorePage}" />
</ShellSection>
                    <ShellContent x:Name="ContactItem" Route="contact" Title="CONTACT" ContentTemplate="{DataTemplate login:ContactPage}" />
                </FlyoutItem>

                 <FlyoutItem Shell.TabBarIsVisible="False" Route="main" FlyoutDisplayOptions="AsMultipleItems">
                    <ShellContent x:Name="MyReservationsItem" Route="reservation" Title="MY RESERVATIONS" ContentTemplate="{DataTemplate            reservations:MyReservationsPage}" />
                    <ShellContent x:Name="MyGuestItem" Route="guest" Title="MY GUESTS" ContentTemplate="{DataTemplate guests:MyGuestsPage}" />
                    <ShellContent x:Name="OverViewItem" Route="account" Title="OVERVIEW"  Icon="" ContentTemplate="{DataTemplate settings:OverViewPage}" />
                    <ShellContent x:Name="PasswordSecurityItem" Route="password"  Title="PASSWORD &amp; SECURITY" ContentTemplate="{DataTemplate settings:PasswordSecurityPage}" />
                    <ShellContent x:Name="EmailPreferencesItem" Route="email" Title="EMAIL PREFERENCES" ContentTemplate="{DataTemplate settings:EmailPreferencesPage}"  />
                </FlyoutItem>

How do I disable the shellcontent "ExplorePage"?
I tried this ExploreItem.Items[0].IsEnabled = false;

It did not disable the flyoutMenuItem.


How to display one object from the API?

$
0
0

MyScore.xaml.cs:

`

    private async void GetMine()
    {
        var token = Application.Current.Properties["MyToken"].ToString();

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await client.GetStringAsync("http://dearjean.ddns.net:44301/api/Rewards/GetMine");

        var tablicaW = JsonConvert.DeserializeObject<RewardsGetMine>(response);




    }
`

MyScore.xaml:

`<ContentPage.Content>

                                <Label Margin="10,0,10,0" Text="{Binding Nickname}" VerticalOptions="Center" />
                                <Label Margin="10,0,10,0" Text="{Binding Punkty}" VerticalOptions="Center" />

    </StackLayout>
</ContentPage.Content>`

public class RewardsGetMine { public string Nickname { get; set; } public string Id { get; set; } public int Punkty { get; set; } }

My API:

{ "Id": "7e5f8579-d5c7-484a-a144-eeb692ce6d48", "FirstName": null, "LastName": null, "Nickname": "bartek101998", "Punkty": 510, "Roles": [ "Creator" ] }

Binding Command in ListView ItemTapped

$
0
0

Hi,

I have a button which opens the Camera using a class called CameraModel. This is done with a Binding Command.

Button to open Camera:

Part of CameraModel.cs:

Besides that, I also have a ListView with several items. I use ItemTapped, where only one of the items performs something when tapped:

Now I face the following problem as you already see in the previous picture:
I want to call CameraModel.cs from one specific ListView Item.
For example:

Text1
Text2
Text3
Text4
Text5

When ‘Text3’ is tapped, you can see that the DisplayAlert will show something, but now I want to add that when I tap ‘Text4’ the Camera will be opened (using CameraModel).

I have no idea how to add the Binding Command to one specific ListView Item, or how to change the code so that a Binding Command is not needed.

How can I do this?

Hope someone can help.

Regards, Ganesh

Access denied at saving file in uwp

$
0
0

I tried to save a file in uwp, but the access denied.

                String fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Record", "record.opml");
                String dirName = Path.GetDirectoryName(fileName);

                if (!Directory.Exists(dirName))
                    Directory.CreateDirectory(dirName);

                if (!File.Exists(fileName))
                    File.Create(fileName);

                using (var streamWriter = new StreamWriter(fileName, true))
                {
                    streamWriter.WriteLine(doc);
                }

Having different app layout parameters (sizes) by device resolution (small vs regular) ?

$
0
0

On June 28th 2019 - XamGirl wrote a devblog about splitting up resources (styling-for-multiple-device-resolutions) (I am not allowed to post direct links to the article :) )

The main concept is this about having some layout parameters in two separate Resource files "SmallDevicesStyles" and "GeneralDevicesStyles" and merging in the App constructor based on device screen resolution.

if (IsASmallDevice())
{
dictionary.MergedDictionaries.Add(SmallDevicesStyle.SharedInstance);
}
else
{
dictionary.MergedDictionaries.Add(GeneralDevicesStyle.SharedInstance);
}

I have followed the example in my solution, the runtime merge works nicely in emulators (Android/iOS), both in Debug/Release mode. When I archive the solution for publishing, the application crashes on startup (both in online emulators and real phones) complaining that the dictionary cannot find missing StaticResource keys contained in the linked file.

So my question is:

  • Is there a reason why this approach would not work in "real life" ?
  • Is there a better way to separate resources based on screen resolution ?

how to hide Stacklayout inside listview

$
0
0

I have two Stacklayout in listview, I want to hide/ show the second Stacklayout on clicking list item what is the way to this?

Viewing all 89864 articles
Browse latest View live


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