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

How to change video resolution in the Media Plugin

$
0
0

Hi everyone,

in my project,I'm taking videos and saving them to the local storage. The videos are getting quite large, because the end user devices have quite a huge resolution that is not needed in my case :-)

There seems to be a bug in the Media Plugin, so that I can not change the video resolution?
On Github, there were several closed bugs with the same issue, but they have been closed in December 2018 and I could not find an update available for the NuGet package. I downloaded a newer version of the plugin's source code and tried to find out anything, but I did not have success.

Can anyone help me or give me an hint, how I can adjust the resolution? Because anything is getting very inperformant, if I have to handle such huge videos (a 10 seconds video gets a size of 60 MB).

I found out that setting the video quality does not have an effect in any case.
MaxWidthHeight has no effect at all.

                var file = await CrossMedia.Current.TakeVideoAsync(new StoreVideoOptions
                {
                    Name = "video.mp4",
                    Directory = "DefaultVideos",
                    MaxWidthHeight = 1024,
                    Quality = VideoQuality.High
                });

=> the video has a resolution of 3840 x 2160 px.
If I set the Quality to VideoQuality.Medium, the resolution remains the same.

Only setting it to Low has an effect, but a to great one ;-)

                var file = await CrossMedia.Current.TakeVideoAsync(new StoreVideoOptions
                {
                    Name = "video.mp4",
                    Directory = "DefaultVideos",
                    MaxWidthHeight = 1024,
                    Quality = VideoQuality.Low
                });

=> the video has a resolution of 176 x 144 px.

Is there a posibility to use custom values for Low / Medium / High resolution?

Thanks in advance!


Reference error. I do not get to fix

$
0
0

When i try to compile my project for IOS i get this error

/Volumes/Files/DEV/MicroPower/PerformaMobile/Git/Clients/excentric/PerformaMobile/PerformaMobile.iOS/MTOUCH: Error MT2101: Can't resolve the reference 'System.Void Xamarin.Forms.Button::set_ImageSource(Xamarin.Forms.ImageSource)', referenced from the method 'Xamarin.Forms.View PerformaMobile.Core.View.ThumbnailLargePlayerView::GetViewAll(System.Type)' in 'Xamarin.Forms.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null'. (MT2101) (PerformaMobile.iOS)

How do I solve this?

I use Visual Studio 2019 for Mac

Scrollview scrolls over content above on Android.

$
0
0

Hi, do anyone know why a scrollview in a stacklayout scrolls out of it's box on android, no problem on IOS? Is there someway to solve this? Added a image to show the problem.

Moved: LinkAssemblies" task failed unexpectedly.

MissingMethodException: Method not found: Amazon.S3.Transfer.TransferUtility.DownloadAsync

$
0
0

I'm getting this exception in a Xamarin.Forms app while testing both Android and UWP projects. (No iOS test yet.)

When I debug in Visual Studio 2017/2019, the instantiated TransferUtility object does not list any of the expected methods.

All Nugets have been updated. The Aws Nugets are in the Forms project, and I also tried adding them to the Android and UWP projects as well.

  • AWSSDK.CognitoIdentity v3.3.100.75
  • AWSSDK.Core v3.3.103.39
  • AWSSDK.S3 v3.3.104.27

Method not found: 'System.Threading.Tasks.Task Amazon.S3.Transfer.TransferUtility.DownloadAsync(System.String, System.String, System.String, System.Threading.CancellationToken)'.

Note that it's not just UploadAsync(), but also Upload() and I don't see any of the Download* methods either. As soon as I step into the the S3Upload method, I get the exception.

The code lives in the Xamarin.Forms project, is very basic, and it works for a stand alone Xamarin Mac application, but not for Xamarin.Forms:

    public async Task S3Upload()
    {
        try // The exception occurs as soon as I try to step into this method
        {
            // Initialize the Amazon Cognito credentials provider
            var credentials = new CognitoAWSCredentials(
                "us-east-1:not-my-real-id", // Identity pool ID
                RegionEndpoint.USEast1 // Region
            );
            IAmazonS3 s3Client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);


            var filePath = $@"path-to-the-file"; // not the real path, but we never get to this line

            var info = new FileInfo(filePath);

            var xfer = new TransferUtility(s3Client);
            //var xfer = new TransferUtilityUploadRequest
            //{
            //    BucketName = bucketName,
            //    Key = info.Name,

            //};

            if (info.Exists)
            {
                //xfer.Upload(filePath, bucketName);
                await xfer.UploadAsync(filePath, bucketName);
            }
            else
            {
                //xfer.Download(filePath, bucketName, info.Name);
                await xfer.DownloadAsync(filePath, bucketName, info.Name);
            }
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                 amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                Console.WriteLine("Please check the provided AWS Credentials.");
                Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
            }
            else
            {
                Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
            }
        }
    }

Any tips or pointers appreciated!

Problem handling OpenUrl calls with XF on iOS

$
0
0

I'm working on a Xamarin.Forms project that can be called from another application using an url "testscheme://dosomething".
A OnePage should be shown if the application is called directly and AnotherPage if called through an url.
I have it working on UWP but I fail on iOS... I think I miss something but can't figure what. On iOS, only OnePage is shown but never AnotherPage.
Here is what I have now (just the essential):
iOS AppDelegate:

public partial class AppDelegate : Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        Xamarin.Forms.Forms.Init();
        LoadApplication(new App(null)); // url is sent to the XF App - null because direct call
        return base.FinishedLaunching(app, options);
    }
    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        Xamarin.Forms.Forms.Init();
        LoadApplication(new App(url)); // url is sent to the XF App
        return true;
     }
}

PCL App:

public class App : Application
{
    public App(Uri url = null)
    {
        if (url == null)
        {
            MainPage = new NavigationPage(new OnePage());
        }
       else
        {
            MainPage = new NavigationPage(new AnotherPage());
        }
    }
}

Debugger and some Debug.WriteLine in OnePage and AnotherPage constructors told me that AnotherPage constructor is called if url is not null and OnePage is updated. But iOS just keeps showing the default OnePage...

XF version: 2.1.0.6529
iOS 7.2 mini (tests on iPad iOS 9.2)

Any help is welcome, I was not able to find any example code on the internet nor discussions.

Does anyone know how to be able to locate a location on xamarin forms with google maps?

$
0
0

Does anyone know how to be able to locate a location on xamarin forms with google maps?

Change Background Navbar Bottom tabbed page

$
0
0

hi all,
how to change color this white navbar in bottom tabbed page!?

this is my using code in tabbed page:

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:app3="clr-namespace:App3" mc:Ignorable="d" xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core" android:TabbedPage.BarItemColor="LightBlue" android:TabbedPage.BarSelectedItemColor="Red" android:TabbedPage.ToolbarPlacement="Bottom" x:Class="App3.MainPage"> <app3:Page1 IconImageSource="insta" Title="mypage1"/> <app3:Page2 IconImageSource="icon" Title="mypage2"/> <app3:Page3 IconImageSource="location" Title="mypage3"/> </TabbedPage>


MvvmCross System.TypeLoadException on Forms.Init with Latest Xamarin.Forms

$
0
0

I am trying to get a simple MVVMCross Android Application working with XamarinForms 4.x. This uses two Project Application.Core and Application.Droid.

The MVVMcross Template defaults the Core project with Android.Forms 2.3.x and this build runs OK, but the VS2019 Visual Preview designer requires 3.6 or higher version of Xamarin.Forms. But as soon as I upgrade the MVVM Core Project with XamarinForms 4.2.x I start to get System.Type.LoadException 'could not resolve type with token 01000061 from typeof(expected class....

I have tried delete bins and obj folders, clean project and restarting VS2019 to no change. Downgrading back to Android Forms 2.x. does not reconcile the problem.

Can anyone advise which MVVMcross Application development works with Android Forms and VS2019 Designer, so I can design layouts and use MVVMcross.

I have integrated Calendar event at cclarke.plugin.calendars example but IOS could not work

$
0
0

I have integrated the Calendar event at cclarke.plugin.calendars example but IOS could not work

Android: Getting XA3001: Could not AOT the assembly

$
0
0

Getting error on almost all assemblies (list bellow) no matter linker option. I don't figure out where is the problem with the AOT compiler. Do you have an idea?

Assemblies impacted:

2>Projet "Chronique.Android.csproj" (Install cibles) :
2>XA3001: Could not AOT the assembly: FFImageLoading.dll
2>XA3001: Could not AOT the assembly: Chronique.dll
2>XA3001: Could not AOT the assembly: FFImageLoading.Forms.dll
2>XA3001: Could not AOT the assembly: FFImageLoading.Transformations.dll
2>XA3001: Could not AOT the assembly: Chronique.Android.dll
2>XA3001: Could not AOT the assembly: FFImageLoading.Platform.dll
2>XA3001: Could not AOT the assembly: FFImageLoading.Forms.Platform.dll
2>XA3001: Could not AOT the assembly: FormsViewGroup.dll
2>XA3001: Could not AOT the assembly: IF.Lastfm.Core.dll
2>XA3001: Could not AOT the assembly: Hqub.MusicBrainz.API.dll

Configuration:

Microsoft Visual Studio Enterprise 2017
Version 15.8.5
VisualStudio.15.Release/15.8.5+28010.2036
Microsoft .NET Framework
Version 4.7.03056

Version installée : Enterprise

Mono Debugging for Visual Studio 4.11.11-pre (8fb558f)
Support for debugging Mono processes with Visual Studio.

Xamarin 4.11.0.776 (d15-8@1ae9b59d7)
Extension Visual Studio permettant de développer pour Xamarin.iOS et Xamarin.Android.

Xamarin Designer 4.15.9 (d000f568b)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates 1.1.116 (9619170)
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK 9.0.0.19 (HEAD/a8a3b0ec7)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK 12.0.0.15 (84552a4)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Dismiss Keyboard

$
0
0

This isn't so much an issue in Android with the physical back button to dismiss the keyboard but how do we resign the first responder in iOS within the Views? Is there an example of this?

Seting max lines in Label (Xamarin Forms) has a problem in Android with Label Height

$
0
0

To set number of lines to a label in Xamarin forms I created an DependencyProperty in a Custom Label Renderer and implemented in renderer of each platform to set number of lines. There's a implementation on each platform:

iOS

Control.Lines = Element.NumberOfLines;

Android

Control.SetMaxLines(Element.NumberOfLines);
Control.SetLines(Element.NumberOfLines);

There's an example of my XAML page with my custom labels:

image

And there's the diference betweeen plataforms:

Android:
image

iOS:
image

The problem is on Android with label's height. The Height of the label is considering all text, and not only the Height of number of lines that I defined, as you can see in images.

xamarin forms sometime crash because httpclient

$
0
0
                 string Url2 = "http://www.*********.com/******/******.php";
                    var uri = new Uri(string.Format(Url2, string.Empty));
                    var response = await _client.GetAsync(uri);
                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var tr = JsonConvert.DeserializeObject<IList<restss>>(content);
                        ObservableCollection<restss> trends = new ObservableCollection<restss>(tr);
                     }

Sometimes it works but for some reason gives the problem "A server with the specified hostname could not be found"
And when the client crashes
What is the solution ?

Design Layout and Absolute Layout

$
0
0


Hi, I'm brand new to Xamarin. I'm working on UI layout stuff but I'm a bit stuck on getting my Buttons in the positions I want.

The buttons don't seem to have height attributes that I can assign them, so looking around I came across Absolute Layout.
This seems to do almost exactly what I need allowing me to put elements in any x,y position that I want. I found the flags that allow me to scale using proportions as well.

The issue is that Y proportion doesn't seem to work for me, X is working fine. Is something overwriting it somewhere? I can't spot the problem.

I have three buttons and I want to center X align them and y align:

Button A at 0.6
Button B at 0.78
Button C at 0.94

In the image example, Y should be set to 0.5 but it will not leave the top of the page.

I can edit it's position by switching flags to XProportional and giving Y an absolute value, but then I'm missing out on any scaling.


Error inflating class android.support.v7.widget.Toolbar after updaring to v7.AppCompat Version 23.3

$
0
0

I am creating a Xamarin Forms Project and using android.support.v7.widget.Toolbar with FormsAppCompatActivity. The code I'm posting below was working with Xamarin.Android.Support.v7.AppCompat Version: 23.0.1.3

But after I upgraded to 23.3.0 this has started throwing Android.Views.InflateException: Binary XML file line #1: Error inflating class android.support.v7.widget.toolbar exception.

Here is my code for MainActivity

[Activity(Label = "AppMob.Client", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {

        protected override void OnCreate(Bundle bundle)
        {
            FormsAppCompatActivity.ToolbarResource = Resource.Layout.toolbar;
            FormsAppCompatActivity.TabLayoutResource = Resource.Layout.tabs;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            Xamarin.FormsMaps.Init(this,bundle);                        
            GoogleAnalyticsHelper.GetGASInstance().Initialize_NativeGAS(Application.Context);  //For GA initialization
            LoadApplication(new App());
        }
}

This is my code for Resource.Layout.toolbar

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_scrollFlags="scroll|enterAlways" />

Xamarin forms CFB notification: How to refresh token after once registeration device?

$
0
0

I created the application with Xamarin.forms.iOS and use Plugin.FirebasePushNotification to send the notification through firebase.

once I registered the device there no problem with getting Token, but, after I delete app and test again the app doesn't get the Token. I cannot receive the notification anymore.

AppDelegate.cs

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    NSDictionary _launchOptions;
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        ImageCircleRenderer.Init();
        LoadApplication(new App());
        AnimationViewRenderer.Init();

        _launchOptions = options;

        Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
        SQLitePCL.Batteries.Init();

        ZXing.Net.Mobile.Forms.iOS.Platform.Init();
        FirebasePushNotificationManager.Initialize(options, true);

        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound,
                                                                    (granted, error) =>
                                                                    {
                                                                        if (granted)
                                                                            InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                                                                    });
        }
        else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
        }
        else
        {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
        }


        CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
        {
            System.Diagnostics.Debug.WriteLine($"TOKEN : {p.Token}");
            UIPasteboard clipboard = UIPasteboard.General;
            clipboard.String = p.Token;
            Helper.Settings.Token = p.Token;

        };

        CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
        {
            Dictionary<string, object> dic = p.Data as Dictionary<string, object>;
            if (dic["targetUserId"].ToString() != null && Helper.Settings.UserId == dic["targetUserId"].ToString())
            {
                System.Diagnostics.Debug.WriteLine("Received");
                Helper.Settings.userWhoSentNotiId = dic["userWhoSentNotiId"].ToString();
                Helper.Settings.callingStatus = true;                 FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Alert;
                MessagingCenter.Send<object, string>(this, "CallingNotifications", dic["callingName"].ToString());
            }
        };

        CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
        {
            Dictionary<string, object> dic = p.Data as Dictionary<string, object>;
            Helper.Settings.userWhoSentNotiId = dic["userWhoSentNotiId"].ToString();
            Helper.Settings.callingStatus = true;
            MessagingCenter.Send<object, string>(this, "CallingNotifications", dic["callingName"].ToString());
        };
        return base.FinishedLaunching(app, options);
    }

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
    }

    public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
    {
        FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);
    }

    public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        FirebasePushNotificationManager.DidReceiveMessage(userInfo);
        completionHandler(UIBackgroundFetchResult.NewData);
    }
}

I notice the app don't launch CrossFirebasePushNotification.Current.OnTokenRefresh
How can the app refresh the token and get the Token?

GC_MINOR: (Nursery full) -> Only on Galaxy S9 Plus of my friend

$
0
0

Hi to everyone,

a few days ago I installed my app on my friend's Samsung Galaxy S9 Plus.
Only on this device, the app is slow.
I think it's an absurd thing, considering that it is the last device released by the Samsung company.

I try to explain what happens, considering that in my app you can download multimedia content (2mb/5mb of files).

The problem appears when, after opening the page where it is possible to search and download the files (a list containing two icons and one label per line appears) I'm pressing the icon to start the download of file.
At that moment, the UI of the app freeze while all other Tasks continue to go (eg Task of download be able to download and save the file without problems).

I immediately thought that the problem was caused by too much work on the main thread (maybe caused by an animation that start as soon as the download starts). [Only on Galaxy S9 Plus of my friend?!]

I also tested the app on the Galaxy S9 Plus, available on browserstack.com, and on their devices, the application works perfectly without problems (even fast).
My friend's phone is fast and it's new (no root or similar).

I'll give you some examples with some images.

Steps:
1. List of files (icon on left, file name, icon on right. This list use FastCells)
2. Click on download (appear a new absolute layout with numer of downloads and progress bar, appear with an animation from bottom to top)
3. If you click on download info layout or swipe download info layout appear a list of separate progress for each file)

These animations work on all devices (Android and iOS), except on the Galaxy S9 Plus of my friend.

To manage the global percentage of downloads, I created an event (DownloadProgressChanged).

I show you some code.
Download method inside Android Service (called by DependencyService.Get().DownloadFile)

private void DownloadFile(string fileName, string url, string source, string id, string uniqueId)
{
    if (NetworkState == NetworkState.ConnectedData || NetworkState == NetworkState.ConnectedWifi)
    {
        // Used inside list of current downloads
        var downloadInfo = new DownloadInfo
        {
            FileName = fileName,
            Progress = 0,
            IsWriting = false, // used to show infinite progress or percentage progress
            UniqueId = uniqueId,
            DownloadStatus = DownloadStatus.Idle // waiting (infinite progress)
        };
        // Add to singleton public list of not exist
        if (!DownloadHandlers.Instance.AtomicCheck(uniqueId))
        {
            DownloadHandlers.Instance.AtomicAdd(downloadInfo);
        }
        else
        {
            downloadInfo = DownloadHandlers.Instance.CurrentDownloadsInfo.First(u => u.UniqueId == uniqueId);
        }
        // Invoke DownloadProgressEvent
        InvokeDownloadProgress();
        try
        {
            var handler = new NativeMessageHandler();
            var httpClient = new HttpClient(handler);
            handler.DisableCaching = true;

            // Change value of IsWriting field
            if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
            {
                DownloadHandlers.Instance.AtomicWriting(uniqueId, true);
            }

            var webApiWrapper = new WebApiWrapper();
            Uri uri = new Uri(url);
            var credentials = XXXXXXXXXXXXXXXXXXXXXXX;
            httpClient = webApiWrapper.ExternalApiRequest(credentials?.access_token);

            // Only response header, because we download the file only after that the stream is ready to write file on disk
            using (var response = httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).Result)
            {
                var filePath = string.Empty;
                // If file not exist, write file to disk
                if (string.IsNullOrEmpty(fileName)) fileName = "Unknown_" + Guid.NewGuid().ToString("N") + ".xxx";
                fileName = Utils.Normalize(WebUtility.HtmlDecode(fileName), true);

                // Get full path where to save file
                if (!DependencyService.Get<IFilesHandler>().GetFilePath(fileName, out filePath))
                {
                    // Based on exception, throw error or retry if 401 unauthorize (with new token)
                    if (!response.IsSuccessStatusCode)
                    {
                        // Check error code and choose what to do
                        _webApiWrapper.HandleWebException(response, () =>
                        {
                            DownloadFile(fileName, url, source, id, uniqueId);
                        }, out ErrorResponse error);

                        if (error != null)
                        {
                            throw new ApiException("Unable to download file", error.Code);
                        }
                        return;
                    }

                    // Open stream to write file
                    using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        var copyTask = response.Content.CopyToAsync(stream);
                        // TOP ahah
                        var length = response.Content.Headers.ContentLength ?? 15000;
                        while (!copyTask.IsCompleted && !copyTask.IsFaulted && !copyTask.IsCanceled)
                        {
                            // While we receive file data, we calculate the percentage
                            var progress = (double)stream.Position / length;
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                // Set single percentage for current download list
                                if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
                                    DownloadHandlers.Instance.AtomicProgress(uniqueId, progress);

                                // Set status of current download
                                downloadInfo.DownloadStatus = DownloadStatus.Downloading;

                                // Invoke DownloadProgressEvent
                                InvokeDownloadProgress();
                            });

                            Thread.Sleep(100);
                        }
                        // Close stream and Delete file if CopyTask fail
                        if (stream.Length == 0 || copyTask.IsFaulted || copyTask.IsCanceled)
                        {
                            downloadInfo.IsWriting = false;
                            stream.Close();
                            if(File.Exists(filePath)) File.Delete(filePath);
                            throw new Exception("Download Error.");
                        }
                        // Max percentage
                        downloadInfo.Progress = 1d;
                        // Save other data
                        DependencyService.Get<IFilesHandler>().WriteInfoJson(fileName, source, id, uniqueId);
                    }
                }
                else
                {
                    response?.Dispose();
                    AlertError("WarningAlertTitle".Translate(), "FileAlreadyExist".Translate(), "OkButton".Translate());
                }
            }

            // Change value of IsWriting and Status field
            if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
            {
                DownloadHandlers.Instance.AtomicWriting(uniqueId, false);
                DownloadHandlers.Instance.AtomicStatus(uniqueId, DownloadStatus.Done);
            }

            // Download finished
            // Decrease number of current downloads
            Console.WriteLine("INFO: Perfect Download.");
            if (_downloadNumber > 0) _downloadNumber--;
            if (_downloadNumber == 0) _isDownload = false;

            // Invoke DownloadProgressEvent
            InvokeDownloadProgress();
        }
        catch (Exception ex)
        {
            .............
        }
    }
    else
    {
        // No internet connection
    }
}

InvokeDownloadProgress method

private void InvokeDownloadProgress()
{
    // Calculate total progress
    var progress = DownloadHandlers.Instance.TotalProgress();
    // Invoke with EventArgs
    DownloadProgressChanged?.Invoke(null, new DownloadProgressChangedEventArgs
    {
        DownloadNumber = _downloadNumber,
        TotalProgress = progress
    });
}

On form side, page code (OnAppearing)

DependencyService.Get<IServerTasks>().DownloadProgressChanged += DownloadProgressChanged;

where DownloadProgressChanged method

private int _downloadNumber = -1;

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    var downloadNumber = e.DownloadNumber;
    // Invoke main thread async for animation
    Device.BeginInvokeOnMainThread(async () =>
    {
        // Check current downloads
        if (Math.Abs(e.TotalProgress) < 0.0000001 || downloadNumber == 0)
        {
            progressBar.Progress = 0;
            return;
        }

        // Update progress bar value
        progressBar.Progress = e.TotalProgress / downloadNumber;

        // If there is at least one download, change value of label inside download info layout
        if (downloadNumber > 0 && _downloadNumber != downloadNumber)
        {
            _downloadNumber = downloadNumber;
            lbInfoDownload.Text = string.Format("MultipleDownloadInfoText".Translate(), downloadNumber);

            // If download info layout is not visible
            if (!infoDetailedView.IsVisible)
            {
                // Animate layout from bottom to top
                infoDetailedView.TranslationY = infoDetailedView.Height;
                infoDetailedView.IsVisible = true;
                await infoDetailedView.TranslateTo(0, infoDetailedView.Height - iosRow.Height.Value, 350, Easing.Linear);
            }

            // Change margin of List, so that by scrolling we can see all the elements hidden by download info layout
            layoutList.Margin = new Thickness(0, 0, 0, iosRow.Height.Value);
        }
    });
}

There are other methods used to animate the download info layout (touch and swipe) but it is not necessary to show them because the UI freeze before displaying this layout.

how to upload image to the server using api in xamarin forms?

my listview cell dose not load small icon sometimes.

$
0
0

Dear All
i have a listview in each cell there is an icon, but when i open list some cells show icon and some does not show. this icon has binding on tab it should show same size another icon. (by default it should show Active icon and when tab on that it will be hidden and incative icon should appear) below is xamal code for listview.

 <ListView HorizontalOptions="FillAndExpand" CachingStrategy="RecycleElement" SelectionMode="None"  HasUnevenRows="True" 
BackgroundColor="Transparent" ItemsSource="{Binding Data}" VerticalOptions="FillAndExpand">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid Margin="0,5,0,5" BackgroundColor="Transparent">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="8*" />
                                    <ColumnDefinition Width="45*" />
                                    <ColumnDefinition Width="30*" />
                                    <ColumnDefinition Width="20*" />
                                </Grid.ColumnDefinitions>
                                <Label VerticalOptions="Center" FontAttributes="Bold" Grid.Column="0" Text="{Binding SerialNumber}" BackgroundColor="Transparent"/>
                                <Label VerticalOptions="Center" FontAttributes="Bold" Grid.Column="1" Text="{Binding Name}" BackgroundColor="Transparent"/>

                                <Frame Grid.Column="2" BackgroundColor="Black" CornerRadius="5" Padding="0"  HeightRequest="36" IsClippedToBounds="true"  >
                                    <Button BackgroundColor="Black" HorizontalOptions="CenterAndExpand" Command="{Binding ProfileCommand}" VerticalOptions="StartAndExpand" TextColor="Yellow" Text="Profile"/>
                                </Frame>

                                <Frame Grid.Column="3" BackgroundColor="Transparent" CornerRadius="5" Padding="0"  HeightRequest="25" IsClippedToBounds="true" IsVisible="{Binding ShowActiveImage}" >
                                    <Image BackgroundColor="Transparent" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" IsVisible="{Binding ShowActiveImage}" Source="{u:ImageResource CricApp.Images.active.png}" Aspect="AspectFit">
                                        <Image.GestureRecognizers>
                                            <TapGestureRecognizer />
                                            <TapGestureRecognizer Command="{Binding PlayerActiveCommand}" />
                                        </Image.GestureRecognizers>
                                    </Image>
                                </Frame>

                                <Frame Grid.Column="3" BackgroundColor="Transparent" CornerRadius="5" Padding="0"  HeightRequest="25" IsClippedToBounds="true" IsVisible="{Binding HideActiveImage}" >
                                    <Image BackgroundColor="Transparent" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" IsVisible="{Binding HideActiveImage}" Source="{u:ImageResource CricApp.Images.inavtive.png}"  Aspect="AspectFit">
                                        <Image.GestureRecognizers>
                                            <TapGestureRecognizer />
                                            <TapGestureRecognizer Command="{Binding PlayerInactiveCommand}" />
                                        </Image.GestureRecognizers>
                                    </Image>
                                </Frame>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
Viewing all 76418 articles
Browse latest View live


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