Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all 204402 articles
Browse latest View live

Using Xamarin.Auth with Xamarin.Forms

$
0
0

How you can use Xamarin.Auth when you're using Xamarin.Forms?

I have this:

async public System.Threading.Tasks.Task<bool> LoginWithFacebook (object dialog, string FacebookAppID)
        {
            var user = new ParseUser ();
            var auth = new OAuth2Authenticator (
                           clientId: FacebookAppID,
                           scope: "",
                           authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
                           redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
            auth.AllowCancel = true;
            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += async (object sender, AuthenticatorCompletedEventArgs ee) => {

                // Now that we're logged in, make a OAuth2 request to get the user's info.
                var accessToken = ee.Account.Properties ["access_token"].ToString ();
                var expiresIn = Convert.ToDouble (ee.Account.Properties ["expires_in"]);
                var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);

                // Now that we're logged in, make a OAuth2 request to get the user's id.
                var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, ee.Account);
                var response = await request.GetResponseAsync ();
                var obj = JObject.Parse (response.GetResponseText ());
                var id = obj ["id"].ToString ().Replace ("\"", ""); // Id has extraneous quotation marks
                user = await ParseFacebookUtils.LogInAsync (id, accessToken, expiryDate);

            };
            var dvc = ((DialogViewController)dialog);
            dvc.PresentViewController (auth.GetUI (), true, null);  
            return user.IsAuthenticated;
        }

But I can't cast ContentPage to DialogViewController or an Activity


Memory Leaks, Events, Android Views (Java peers), Finalizers, GC and Disposing...

$
0
0

Hello,
I have read a lot about Finalizer tricks, Disposing and Java <> .NET bridge for "peered" instances that are accessible from the C# side but actually have a Java counterpart.
Mostly this is used when manipulating Java UI objects.

I know that all Android UI stuff implements Finalizers so that "Dispose" gets called at some point.
This also means that when a GC occurs they will be promoted to the next generation and stay around for longer than they need to.

This should not be an issue if they represent small amounts of memory by themselves and their Java counterpart gets deallocated properly via Dispose.

I am studying about a memory leak that looks to be happening in our application. I am not 100% sure now if it would lead to a crash or not... There used to be a crash related to a memory leak but most was fixed and for the rest well depending on the answer it may be ok...

I saw one of our object inherited from a FrameLayout registers to the Android View's Click event by doing:

OnCreateView() {
    this.Click += MyClickEvent;
}

Then this object removes the handler by doing:

Dispose(bool disposing) {
    this.Click -= MyClickEvent;
}

However "Dispose()" method is never called by our code. I saw that sometimes it is called by the Finalizer thread.

Are the following assumptions correct:

1) As long as Dispose is not called, there is a reference from Java to C#. Does this reference prevent the collection of the object? I think it doesn't, it must be some kind of weakreference.

2) So our object stays around for a while, and may be collected on the next GC after the finalizer decided to run. Is it correct?

For reference I already checked the following on the web (copy paste the links in ur browser):
docs.microsoft.com/en-us/xamarin/android/internals/garbage-collection
stackoverflow.com/questions/28863058/xamarin-android-finalizer-not-getting-called-when-leaving-the-activity-to-go-to
www.slideshare.net/Xamarin/advanced-memory-management-on-ios-and-android-mark-probst-and-rodrigo-kumpera

ZXing.Net into standard .net 2.0 library and Xamarin application

$
0
0

Hi,
I'm new to Xamarin and this whole .NET, I,m starting a new project and I was creating .NET library 2.0 to put the commun code. I have a need to extract multiple barcode from an image and was using ZXing as demo on Window with full .NET Framework 4.7. Now I would like to port this to Xamarin and I'm having some trouble to integrate it into my library. Here's my project structure:

  • GF-Trace.Android (Xamarin Android)

    • Reference to:
      • GF-Trace
      • NuGet packages:
      • Xamarin.Forms
      • ZXing.Net
        * Android.*
  • GF-Trace (.Net Standard 2.0 lib)

    • Build Dependencies:

      • GF-Imaging
    • NuGet packages:

      • Xamarin.Forms
      • ZXing.Net
  • GF-Imaging (.Net Standard 2.0 lib)

    • NuGet packages:
      • Xamarin.Forms
      • ZXing.Net

I have some hard time to make it work properly. The compiler complain about missing reference.
Severity Code Description Project File Line Suppression State
Error Can not resolve reference: zxing, referenced by GF-Trace. Please add a NuGet package or assembly reference for zxing, or remove the reference to GF-Trace. GF-Trace.Android

Under UWP, it does compile but when running I get a method missing exception error:
System.MissingMethodException
Message=Method not found: 'ZXing.Result[] ZXing.BarcodeReader.DecodeMultiple(Byte[])'.
Source=GF-Trace
StackTrace:
at GF_Trace.Views.XyMeasurementPage.ExtractQRCodeMessageFromImage(Byte[] bitmap) in ...\GF-Trace\GF-Trace\Views\Debug\XyMeasurementPage.xaml.cs:line 128
...

So I wonder how I should be doing this? GF-Imaging is a reusable lib that implement function to manipulate images and could do some processing to recover barcode with ZXing. GF-Trace is the common application library that also can use some ZXing types. GF-Trace.Android or GF-Trace.UWP consume the GF-Trace.

The ZXing.Net said it support .Net Standard 2.0 and Xamarin.Android. What is wrong or how does one ensure the function and lib are present for a given platform?

NOTE I did select ZXing.Net and not the mobile version because the image can come from different source and not only from the camera as stand still image. So I tried to avoid the ZXing.Net.Mobile which wrap all into a Form GUI.

Thanks, Maybe I'm doing something wrong into my setup, but I have no clue why it doesn't found the lib or the methods.

Why would OnPause and OnResume get called while the app is still the currently active app?

$
0
0

I'm running into an oddity where the OnPause and OnResume methods are being called after the app has been sitting, unused, for about 20 seconds or so. The screen isn't locking and the app isn't being backgrounded. It calls the OnPause method followed immediately by a OnResume call. Now this is a problem for the application because it's not uncommon to leave the app running on the phone. Much of the functionality limits what a user is able to do until the GPS has been able to accurately assess their location and detect that they are within a certain range of a pre-determined location. For some phones this can take a while, especially if they don't have a particularly good signal. When OnResume gets executed, it performs a couple of tasks to check some things and a loading screen is displayed. What ends up happening now is the loading screen is presented to the user after 20 seconds or so not doing anything. Depending on the connection, it can take a minute for everything to be analyzed and the loading screen to go away. I won't go into detail but this delay can present some problems for the user.

It's worth noting that we recently updated the SDK and are in the process of updating the APP to work with the latest tools. I don't recall anything like this occurring before the update. Is this normal behavior for Android?

Add image to UIAlertController -> UIAlertAction

$
0
0

Hello,
I think it's possible but couldnt find any sample.
I create a menü like this

  1. UIAlertController actionSheetAlert = UIAlertController.Create("Menu", null, UIAlertControllerStyle.ActionSheet);
  2. actionSheetAlert.AddAction(UIAlertAction.Create("option 1"), UIAlertActionStyle.Default, (action) => Console.WriteLine("Item one pressed.")));
  3. // Display the menu
  4. this.PresentViewController(actionSheetAlert, true, null);

How can add images left to item titles?

AppCenter push. Unable to receive offline/app closed messages ++

$
0
0

We have started using the AppCenter push messaging. Have used the tutorial: https://docs.microsoft.com/en-us/appcenter/sdk/push/android
Works fine when the app is running in the foreground.
Two issues:
1. Messages received when app is closed is not “registered” by the app. The app center responds with “202 Accepted”.
2. The AppCenter registration and event receiver is located in the splash activity OnStart()
Push.PushNotificationReceived += (sender, e) =>{…}
We are unable to show a dialog during the splash activity. (works fine when app is started.)

Websocket cannot connect when using mobile data

$
0
0

I have a hundred or so clients connected to my server using .NetStandard websockets. Yet, I have one client on 4g data using an Android OnePlus 5t (T-Mobile data) that cannot connect. My server never even receives a call to begin the connection. Note, that he can connect using wifi data. Below are the things I have tried. Has anyone had a similar issue or know what could be the problem and how it might be solved. This is a TCP connection over port 1334.

  • User has checked that the app has permission to use mobile data.
  • I have changed the protocol to use 'wss' instead of 'ws'.
  • The user can connect to the server through the following website: http://www.websocket.org/echo.html

How to use material components in application Xamarin.Android ?

$
0
0

Hello everyone
I develop currently a application Xamarin.Android and i would like to use material components (MDC) material.io, in my application because i like the design in contrary to the basic design of Xamarin.Android. do you have an idea to create binding java library for MDC please ?

PS : i already watch the tutorial a binding java


How check different entries in Stacklayout.Children?

$
0
0

Hi everyone, good work :)
I want only one Entrq.Text changed. My problem is that they all change at the same time
I check entries in my Stacklayout.Children. Try more way(ClassId,Id,tabındex) couldn't solve the problem.

My problem Video =

https://drive.google.com/file/d/1T6fts0gPxusFTDLWpw3UjurNNCEOYAVI/view?usp=sharing

## My Code =
public StackLayout Fill_Fields(string DataJson, StackLayout Design) { StackLayout res = Design; if(DataJson != null) { dynamic Data = JsonConvert.DeserializeObject(DataJson); foreach (var item in res.Children) { if (item.GetType() == typeof(Picker)) { Picker picker = (Picker)item; picker.SelectedItem = null; picker.SelectedItem = Data[picker.ClassId].ToString(); } else if (item.GetType() == typeof(Entry)) { Entry entry = (Entry)item; entry.Text = Data[entry.ClassId].ToString(); entry.SetDynamicResource(StyleProperty, "frmDesignerEntry"); } else if (item.GetType() == typeof(AccountEntry)) { AccountEntry accountEntry = (AccountEntry)item; if (DropdownSelectedItems.Title != null) { accountEntry.PropertyChanging += (object sender, PropertyChangingEventArgs e) => { var m = accountEntry.ClassId.ToString(); var s = accountEntry.Text; accountEntry.Text = DropdownSelectedItems.Title; }; } else { accountEntry.Text = Data[accountEntry.ClassId].ToString(); } } else if (item.GetType() == typeof(DatePicker)) { DatePicker datePicker = (DatePicker)item; DateTime date = new DateTime(); date = Convert.ToDateTime(Data[datePicker.ClassId].ToString()); datePicker.Date = date; datePicker.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)); } else if (item.GetType() == typeof(Editor)) { Editor editor = (Editor)item; editor.Text = Data[editor.ClassId].ToString(); } } } res.Children.Add(Form_Buttons(res, DataJson)); return res; }

Xamarin.iOS & Xamarin.Android Developer Experience

$
0
0

Hi All,

I've been playing with Xamarin.Forms and as a newcomer to the framework / tooling I've not been having a great experience being honest. XAML previewer not really working and randomly crashing, a few builds just not building then next try working, auto complete not working until I restart VS for my own XAML controls etc, all which has lowered my confidence of using Xamarin.

I know I'm not alone reading the forums and so on but also I know a lot of people make great apps with Xamarin and I love C# and the ecosystem so am investigating the possibility of using Xamarin.iOS and Xamarin.Android instead of Xamarin.Forms.

I have a base knowledge of native iOS app dev, Swift, Xcode etc so I can (for example) use Xcode to create a ToDo list type app just fine and am thinking Xamarin.iOS might be a better route for me to start with? Later on I can add an Android UI when I come up to speed with the basics of Android native dev and code share the business logic etc?

I wanted to ask what the experience is like generally for people using Xamarin.iOS and Xamarin.Android nowadays vs Forms? Are things generally better / less buggy do you feel? If I'm reading the wind right people generally have a better time with Xamarin.iOS & Xamarin.Android. Please be gentle if that's not the case lol

Hoping to find a way forward, appreciate any thoughts, cheers all!

FeatureSamples: Navigation sample on UWP throws exception.

$
0
0

This sample works with teleportation, but not with navigation. This sample for WinForms and WPF works fine.

When the endpoint is chosen by a mouse click, and then a press on the button 'Set', this line of code:

var result = navMesh.FindPath(jackNode.Position, endPos);

Throws this exception:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Have tried running this on hololens and same exception happens in the same way. All else works.

The CrowdNavigation sample uses a bit different approach to navigation, which is more complex, but works.

WebView error TLS 1.2 - Help

$
0
0

I have an application with WebView, on Android it works perfectly but in IOS I'm getting a TLS 1.2 error.

2019-01-25 22:30:17.686174-0200 CIPLAN.iOS[3765:60722] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=3765
2019-01-25 22:30:17.686458-0200 CIPLAN.iOS[3765:60722] SecTaskCopyDebugDescription: CIPLAN.iOS[3765]/0#-1 LF=0
2019-01-25 22:30:17.742595-0200 CIPLAN.iOS[3765:60758] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=3765
2019-01-25 22:30:17.742875-0200 CIPLAN.iOS[3765:60758] SecTaskCopyDebugDescription: CIPLAN.iOS[3765]/0#-1 LF=0
2019-01-25 22:30:17.872320-0200 CIPLAN.iOS[3765:60758] [BoringSSL] boringssl_context_alert_callback_handler(3718) [C1.1:2][0x7fdf72e23390] Alert level: fatal, description: protocol version
2019-01-25 22:30:17.872801-0200 CIPLAN.iOS[3765:60758] [BoringSSL] boringssl_context_error_print(3670) boringssl ctx 0x600001402560: 140597682873608:error:100000f0:SSL routines:OPENSSL_internal:UNSUPPORTED_PROTOCOL:/BuildRoot/Library/Caches/com.apple.xbs/Sources/boringssl_Sim/boringssl-109.220.4/ssl/handshake_client.cc:557:
2019-01-25 22:30:17.873197-0200 CIPLAN.iOS[3765:60758] [BoringSSL] boringssl_context_get_error_code(3575) [C1.1:2][0x7fdf72e23390] SSL_AD_PROTOCOL_VERSION
2019-01-25 22:30:17.894320-0200 CIPLAN.iOS[3765:60758] TIC TCP Conn Failed [1:0x600002333d80]: 3:-9836 Err(-9836)
2019-01-25 22:30:17.897862-0200 CIPLAN.iOS[3765:60758] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9836)
2019-01-25 22:30:17.898090-0200 CIPLAN.iOS[3765:60758] Task <1A29C422-B713-4E6D-8F4A-A956D9D240E2>.<0> HTTP load failed (error code: -1200 [3:-9836])
2019-01-25 22:30:17.898278-0200 CIPLAN.iOS[3765:60757] NSURLConnection finished with error - code -1200

Debug as upgrade instead of new deployment to retain data?

$
0
0

Hi,

I am wanting to test how a user upgrade would impact their existing database with database table changes.. how can I do this using the debug on device from Monodevelop?

Every time I debug it removes all the old data from the application and starts fresh.

Cheers,
Le-roy

Putting a drop down list in a action bar button

$
0
0

Hi folks! I'm trying to put a drop down list in a button on my action bar. How can i achieve that?

I can insert new itens, but i need to insert a drop down list in the button action.

Thank you guys!

CarouselView is not working on iOS!

$
0
0

Hello all,

I've implemented CarouselView and its working fine on Android, but I can't see it on iOS. Can someone please help me out?


Best practice for authentication flow

$
0
0

Are there any recommended best practices for the flow/handling of authentication in a Xamarin app? Ie not how to do the actuall authentication but rathder how to handle back buttons after logout, sleep/resume, app going to background/foreground and such. And some recommendations on how to implement it.

Have seen some different examples but some seem to be a bit "rough" and relying on modal windows etc.

Spinner problem

$
0
0

Is there a way to change text only in the unrolled spinner? I mean the text that shows the selected option. I need the selected option to be white and smaller... The dropdownmenu will be in black and bigger. (Explained in the picture)

There is one thing I don't really understand and that's why the spinner uses only the first third of it's width? I need to use the extra space which is shown in the picture aswell to see the whole selected word without making the spinner wider.

I tried to change text color and size in spinner properties, but it chages the color and size in the dropdown menu too...

Thanks, tried to find solution everywhere...

Resize View on content changed

$
0
0

I have the following situation:

On my xaml page I have a setup that looks like this:

Open Bracket ScrollView Close Bracket
Open Bracket local:MyView x:Name="Test" BackgroundColor="White" BackgroundImageFilePath="{Binding BackgroundAttachment.LocalAttachmentFilePath}"
StrokeColor="{Binding StrokeColor}" StrokeWidth="{Binding StrokeWidth}"/ Close Bracket
Open Bracket /ScrollView Close Bracket

This is, roughly, supposed to be a drawing pad. the user can set a background image and then draw all over it.

It has a Renderer, which contains these fields:

    ImageView imageView;
    Canvas sketchCanvas;
    Bitmap backgroundBmp; 

It has an OnElementChanged which does roughly:

protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (Control == null && e.NewElement != null)
{

            imageView = new Android.Widget.ImageView(Forms.Context);
            //imageView.SetMinimumHeight(2300);
            //imageView.SetMinimumWidth(2300);
            SetNativeControl(imageView);                
        }
        if(e.OldElement != null)
        {
            e.NewElement.SketchBytesRequested -= OnSketchBytesRequested;                
        }
        if (e.NewElement != null)
        {
            e.NewElement.SketchBytesRequested += OnSketchBytesRequested;
            Element.Reset = () => Reset();
            Element.Redo = () => Redo();
            Element.Undo = () => Undo();                
        }
    }

and then there are other methods that set sketchCanvas and backgroundBmp into imageView.

The problem comes when zooming.

I'm doing:

private void RescaleImage(float newParentScaling)
{
float oldParentScaling = ParentScaling;
float removeOldParentScaling = 1 / oldParentScaling;
ParentScaling = newParentScaling;
sketchCanvas.Scale(removeOldParentScaling, removeOldParentScaling);
sketchCanvas.Scale(newParentScaling, newParentScaling);
foreach (var pInfo in sketchPathInfos)
{
Matrix m = new Matrix();
m.SetScale(removeOldParentScaling, removeOldParentScaling);
pInfo.Path.Transform(m);
m.SetScale(newParentScaling, newParentScaling);
pInfo.Path.Transform(m);
}
}

Which works well enough for handling the sketchCanvas, and backgroundBmp is also taken care of. But the imageView size doesn't change. I can give it a height/width in its constructor (up in onElementChanged), and if I make them very big there then my scrollView (all the way at the top in the xamarin page) dutifully lets me scroll up and down it. But most of it starts out as empty. That is, I can scroll around a big empty imageView with a small sketchCanvas up there in the corner.

What i'd like to do is change the size of my imageView along with my sketchCanvas, such that the scrollView would show a scrollbar when imageView got big, and not do so when it was small. In a perfect world it would also start out the same size as the scrollView, a la 'FillAndExpand' behavior.

But the only thing I can seem to set on the imageView is the minimumHeight/minimumWidth parameters, and while those affect the ScrollView if I set them at the beginning, they don't seem to do so if I set them at the end of my RescaleImage function. Is there a way to set the imageView's height/width, or in other ways resize it, such that I can have MyView grow and shrink with its content, with the user scrolling about in the scrollView when it is too large?

Xamarin forms android splash screen appear when navigation.pushasync and navigation.popasync

$
0
0

style.xml

<? xml version="1.0" encoding="utf-8"? >
< resources >
< style name = "MainTheme" parent="MainTheme.Base" >
< /style >
< item name = "windowNoTitle"> true < /item >
< item name="windowActionBar">false< /item>
< item name = "colorPrimary">#2196F3< /item>
< item name="colorPrimaryDark">#1976D2< /item>
< item name = "colorAccent">#FF4081< /item>
< item name="windowActionModeOverlay">true
< item name = "android:datePickerDialogTheme" > @style / AppCompatDialogStyle </ item >
</ style>
< style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog" >
< item name = "colorAccent" >#FF4081< /item>
< /style>
< style name="MyTheme.Splash" parent="Theme.AppCompat.Light.NoActionBar" >
< item name = "android:windowBackground"> @drawable / Splash_background < / item>
</ style>
</ resources>

and

mainActivity class

[Activity(Label = "xxx", Icon = "@mipmap/icon", Theme = "@style/MyTheme.Splash", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait, WindowSoftInputMode = SoftInput.AdjustResize)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{

    public FirebaseAnalytics firebaseAnalytics;

    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);
        LoadApplication(new App());
    }

}

help me to resolve the issue

Animation on xamarin forms using Lottie dont work!

$
0
0

Hi,
anyone use the Lottie nugget to play animations on xamarin forms.
I tested a simple example that dont run, just appear on android emulator a blank window.

I install the Lottie nugets.

Here is my xaml page:

<?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:forms="clr-namespace:Lottie.Forms;assembly=Lottie.Forms"

         x:Class="Example.Forms.MainPage">

    <forms:AnimationView 

            x:Name="AnimationView"

            Animation="LottieLogo1.json"

            Loop="True"

            AutoPlay="True"

            VerticalOptions="FillAndExpand"

            HorizontalOptions="FillAndExpand" />

I put the file "LottieLogo1.json" on Resources folder of the Droid Project.

Thanks

Viewing all 204402 articles
Browse latest View live


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