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

I want to send image to dot net core api from xamarin forms

$
0
0

Here is the Api code

  public class FileUploadAPI
    {
        public IFormFile files { get; set; }
    }


    // POST: api/Image
    [HttpPost]
    public async Task Post(FileUploadAPI obj)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "upload");
        if (obj.files.Length > 0)
        {
            using (var fileStream = new FileStream(Path.Combine(uploads, obj.files.FileName), FileMode.Create))
            {
                await obj.files.CopyToAsync(fileStream);
            }
        }

    }

it works will i am using potman to send iamge
I tried to send image from xamarin forms application by following @AdamBennett.7253 code https://forums.xamarin.com/discussion/comment/391872#Comment_391872 here is the client side code but its not working

   private async void testuplo_Clicked(object sender, EventArgs e)
    {
        //variable
        var url = "http://localhost:4622/api/image";
        //variable
        // var url = "http://hallpassapi.jamsocialapps.com/api/profile/UpdateProfilePicture/";
        // var file = "C:/Users/MIS/source/repos/CCNPP/CCNPP/Images/Communitiesreached.png";

        var media = CrossMedia.Current;
        var file = await media.PickPhotoAsync();

        // wait until the file is written
        while (File.ReadAllBytes(file.Path).Length == 0)
        {
            System.Threading.Thread.Sleep(1);
        }


        try
        {
            //read file into upfilebytes array
            var upfilebytes = File.ReadAllBytes(file.Path);

            //create new HttpClient and MultipartFormDataContent and add our file, and StudentId
            HttpClient client = new HttpClient();
            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
            //StringContent studentIdContent = new StringContent("2123");
            content.Add(baContent, "files", "03-0302-M0018_6464_He_5.jpg");
            //content.Add(studentIdContent, "StudentId");


            //upload MultipartFormDataContent content async and store response in response var
            var response =  await client.PostAsync(url, content);

            //read response result as a string async into json var
            var responsestr = response.Content.ReadAsStringAsync().Result;

            //debug
            Console.WriteLine(responsestr);

        }
        catch (Exception ex)
        {
            //debug
            Console.WriteLine("Exception Caught: " + ex.Message.ToString());

            return;
        }

    }

Slow download using WebClient

$
0
0

I am trying to download file from url with progress bar. I am using WebClient for this and I have 150mb file to download. My code downloads the file upto 11 -12% and the download slows. Here is my code. Can anyone help me with this?

        int receivedBytes = 0;
                    int totalBytes = 0;
                   // string ImageToDownload = "http://techslides.com/demos/sample-videos/small.mp4";
                    string ImageToDownload = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
                    WebClient client = new WebClient();                   
                    client.Proxy = null; 

             Downloadprogress.IsVisible = true;
                        using (var stream = await client.OpenReadTaskAsync(ImageToDownload))
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);
                                var buffer = new byte[totalBytes];
                                int read = 0;
                                int total = 0;
                                int received = 0;
                                float percentage = 0;

                                while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                                {
                                    ms.Write(buffer, 0, read);
                                    receivedBytes += read;
                                    received = unchecked((int)receivedBytes);
                                    total = unchecked((int)totalBytes);
                                    percentage = ((float)received) / total;
                                    await styledProgressBar.ProgressTo(percentage, 750, Easing.Linear);
                                    System.Diagnostics.Debug.WriteLine("Downloaded {0} bytes.", receivedBytes);
                                    textProgress.Text = Math.Round(percentage, 3) * 100 + " %";
                                }
                                Stream ALLstream = new MemoryStream(ms.ToArray());
                                System.Diagnostics.Debug.WriteLine("Downloaded Complete");
                                DependencyService.Get<IFileService>().SaveFile(items.id + ".mp4", ALLstream, "imagesFolder");
                                DependencyService.Get<IMessage>().LongAlert("Download Complete");                                
                                Downloadprogress.IsVisible = false;
                                //await Navigation.PopAllPopupAsync();
                            }
                            stream.Close();
                        }                   

Badge count when app is killed in Xamarin form for IOS

$
0
0

I am trying to set the Badge count in Xamarin Forms application for IOS. I am using Azure notification Hub. Everything is working fine except the badge is not getting set when app is killed. I am sending the badge value from backend service.

Please let me know what i need to do to make it work even when the app is killed. I received the notification even the app is killed but badge count is not changing.

Here is my code

PushNotificationService.cs
public class PushNotificationService: IPushNotificationService
{
public DeviceInstallation GetDeviceRegistration(params string[] tags)
{
if (AppDelegate.DeviceToken == null)
{
return null;
}

    var registrationId= AppDelegate.DeviceToken;

    var installation = new DeviceInstallation
    {
        InstallationId = UIDevice.CurrentDevice.IdentifierForVendor.ToString(),
        Platform = "apns",
        PushChannel = registrationId
    };
    System.Diagnostics.Debug.WriteLine($"[service]: {installation.InstallationId}");
    // Set up tags to request
    installation.Tags.AddRange(tags);
    // Set up templates to request
   PushTemplate genericTemplate = new PushTemplate
    {

        Body = "{\"aps\":{\"alert\":{\"title\":\"$(messageTitleParam)\",\"body\":\"$(messageBodyParam)\"},\"content-available\":1,\"badge\" : \"$(badge)\",\"sound\":\"$(messageSound)\"},\"custom\":{\"orderid\":\"$(orderid)\",\"page\":\"$(page)\",\"dataBaseId\":\"$(notificationId)\"}}"
    };
    installation.Templates.Add("genericTemplate", genericTemplate); 
    return installation;
}

public string GetDeviceId()
{

    return UIDevice.CurrentDevice.IdentifierForVendor.ToString();
}

}
AppDelegate.cs

public override void DidReceiveRemoteNotification(
UIApplication application,
NSDictionary userInfo,
Action completionHandler)
{
NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

    var badgecount= new NSString("badge");
    if (aps.ContainsKey(badgecount))
    {
       string count = (aps[badgecount] as NSString).ToString();
        BadgeImplementation badge = new BadgeImplementation();
        badge.SetBadge(Convert.ToInt16(count));
    } 

}

Calling Web API's In Xamarin Forms

$
0
0

I'm a newbie to Xamarin and i try to learn how to call Web API's from Xamarin Forms. I was trying to run this example https://docs.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/webservices-todorest/ , at my Android Phone(Visual Studio Debugger), but i am getting a System.NotImplementedException in this methode:
[assembly: Dependency(typeof(HttpClientHandlerService))]
namespace TodoREST.Droid
{
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;
}
}
}

The exception occurs at this line:
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert.Issuer.Equals("CN=localhost"))
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};

Can anyone help me with this?

Thanks in advance.

More elegant solution for converter?

$
0
0

Hello. I would like to know your opinion about this code. The logic is simple. There are several values in Entry and you need to ensure that they synchronize with each other.
Is there a more elegant solution?

Link to project
github.com/vkorotenko/SquareApp/blob/master/SquareApp/SquarePage.xaml.cs

`
public partial class SquarePage : ContentPage
{
private readonly Model _vm;

    public SquarePage()
    {
        InitializeComponent();
        BindingContext = _vm = new Model();
    }

    private void OnButtonFocused(object sender, FocusEventArgs e)
    {
        if (sender is Entry cell) _vm.ActiveButton = cell.ReturnCommandParameter as string;
    }

    private class Model : BaseViewModel
    {
        private const double InitialMs = 1000;

        public Model()
        {
            Title = Resource.ConverterSquareTitle;
            ActiveButton = nameof(MsValue);
            MsValue = InitialMs;
        }

        #region Propertyes

        /*
        Квадратный метр (км2)       SquareMsLabel       MsValue
        Квадратный километр (км2)   SquareKmsLabel      KmValue
        Ар «соток» (а)              SquareArLabel       ArValue
        Гектар (га)                 SquareGaLabel       GaValue
        Акр                         SquareAcrLabel      AcrValue
        Квадратная миля             SquareMileLabel     MileValue
        Квадратный ярд (yd2)        SquareYardLabel     YardValue
        Квадратный фут (ft2)        SquareFtLabel       FtValue
         */

        private double Ms2Km() => MsValue / 1000000;


        private double Km2Ms() => KmValue * 1000000;

        private double Ms2Acr() => MsValue / 4046.86;

        private double Acr2Ms() => AcrValue * 4046.86;


        private double Ms2Ga() => MsValue / 10000;


        private double Ga2Ms() => GaValue * 10000;


        private double Ms2Ar() => MsValue / 100;

        private double Ar2Ms() => ArValue * 100;

        private double Ms2Mile() => MsValue / 1000000 / 2.58999;


        private double Mile2Ms() => MileValue * 2.58999 * 1000000;


        private double Ms2Yards() => MsValue * 1.19599;


        private double Yr2Ms() => YardValue / 1.19599;


        private double Ms2Ft() => MsValue * 10.7639;


        private double Ft2Ms() => FtValue / 10.7639;


        #region MsValue

        private double _ms = InitialMs;

        public double MsValue
        {
            get => _ms;
            set
            {
                SetProperty(ref _ms, value);
                if (ActiveButton != nameof(MsValue)) return;
                SetValues();
            }
        }

        public void SetValues()
        {
            KmValue = Ms2Km();
            ArValue = Ms2Ar();
            GaValue = Ms2Ga();
            AcrValue = Ms2Acr();
            MileValue = Ms2Mile();
            YardValue = Ms2Yards();
            FtValue = Ms2Ft();
        }

        #endregion

        #region KmValue

        private double _km;

        public double KmValue
        {
            get => _km;
            set
            {
                SetProperty(ref _km, value);
                if (ActiveButton != nameof(KmValue)) return;
                MsValue = Km2Ms();
                SetValues();
            }
        }

        #endregion

        #region ArValue

        private double _arValue;

        public double ArValue
        {
            get => _arValue;
            set
            {
                SetProperty(ref _arValue, value);
                if (ActiveButton != nameof(ArValue)) return;
                MsValue = Ar2Ms();
                SetValues();
            }
        }

        #endregion

        #region GaValue

        private double _gaValue;

        public double GaValue
        {
            get => _gaValue;
            set
            {
                SetProperty(ref _gaValue, value);
                if (ActiveButton != nameof(GaValue)) return;
                MsValue = Ga2Ms();
                SetValues();
            }
        }

        #endregion

        #region AcrValue

        private double _acrValue;

        public double AcrValue
        {
            get => _acrValue;
            set
            {
                SetProperty(ref _acrValue, value);
                if (ActiveButton != nameof(AcrValue)) return;
                MsValue = Acr2Ms();
                SetValues();
            }
        }

        #endregion

        #region MileValue

        private double _mileValue;

        public double MileValue
        {
            get => _mileValue;
            set
            {
                SetProperty(ref _mileValue, value);
                if (ActiveButton != nameof(MileValue)) return;

                MsValue = Mile2Ms();
                SetValues();
            }
        }

        #endregion

        #region YardValue

        private double _yardValue;

        public double YardValue
        {
            get => _yardValue;
            set
            {
                SetProperty(ref _yardValue, value);
                if (ActiveButton != nameof(YardValue)) return;
                MsValue = Yr2Ms();
                SetValues();
            }
        }

        #endregion

        #region FtValue

        private double _ftValue;

        public double FtValue
        {
            get => _ftValue;
            set
            {
                SetProperty(ref _ftValue, value);
                if (ActiveButton != nameof(FtValue)) return;

                MsValue = Ft2Ms();
                SetValues();
            }
        }

        #endregion

        #endregion

        #region ActiveButton

        private string _activeButton = "";

        public string ActiveButton
        {
            get => _activeButton;
            set => SetProperty(ref _activeButton, value);
        }

        #endregion
    }
}

`

is it possible to bold UITextView text

How to add BoxView in relative layout with WidthConstraint dependent on external data

$
0
0

Hi guys,

I'm currently trying to display tasks with BoxViews like this

However the width of this BoxViews should be dependent on the length of the task at hand.
I tried this with RelativeLayout + BoxViews and tried DataBinding on the Constraint Factor but then found out DataBinding is not useable in ConstraintExpressions.
Does anyone has a straight forward solution to this issue that doesn't come to my mind?

Also if you have an idea how I can archieve the same outcome with another method, please let me know

Sorry if its something obvious I'm not aware of yet, I'm a newbie in Xamarin Forms.
Thanks in advance!

PRISM / NavigateAsync not working within await

$
0
0

I am using Dapper to connect to a SQL-Server. When I start my App I want to make sure that there is a connection before I open my Page.
Everything works perfectly except the Page is not showing or is kind of "Empty".
The result ==result.Success, no errors are shown and all steps are executed in the ViewModel of my Page. And there are also no errors in the Constructor of the "CodeBehind" (InitializeComponent();)

Without the (if(await...) the Page is opening.

if (await DapperEngine.CheckConnection(Prefs.ConnectionString) == true)
{
    result = await NavigationService.NavigateAsync("NavigationPage/MainView");
    if (result.Success == false)
    {

    }
}

Any Ideas ?


CollectionView how to disable scrolling ?

SkiaSharp DrawText from Touch event

$
0
0

I need to find any way to set text and place the value dynamically using the x and y coordinates.

private void OnTouch(object sender, SKTouchEventArgs e)
{
string str = "Hello SkiaSharp!";

    SKPaint textPaint = new SKPaint
        {
            Color = SKColors.Chocolate
        };

        float textWidth = textPaint.MeasureText(str);

        SKRect textBounds = new SKRect();
        textPaint.MeasureText(str, ref textBounds);

        switch (e.ActionType)
        {
            case SKTouchAction.Pressed:
                // start of a stroke
                var p = new SKPath();
                float coordinatesX = e.Location.X;
                float coordinatesY = e.Location.Y;
                  p.MoveTo(e.Location);
                  temporaryPaths[e.Id] = p;
                break;
            case SKTouchAction.Moved:
                if (e.InContact)
                    temporaryPaths[e.Id].LineTo(e.Location);
                break;
            case SKTouchAction.Released:
                // end of a stroke
                paths.Add(temporaryPaths[e.Id]);
                temporaryPaths.Remove(e.Id);
                break;
            case SKTouchAction.Cancelled:
                // we don't want that stroke
                temporaryPaths.Remove(e.Id);
                break;
        }

        // we have handled these events
        e.Handled = true;

        // update the UI
        ((SKCanvasView)sender).InvalidateSurface();
    }

App.xaml ResourceDictionary

$
0
0

Is it possible to set values programmatically or by binding?

I want to get values from another file.

I tried:

<prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms"
                        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                        xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms"
                        x:Class="Common.App">
    <prism:PrismApplication.Resources>
        <ResourceDictionary>
            <Style TargetType="ContentPage">
                <Setter Property="BackgroundColor" Value="{Binding PageBackgroundColor}"/>
            </Style>

And in App.xaml.cs:

public partial class App : PrismApplication
{
    private IConfiguration Configuration => Container.Resolve<IConfiguration>();
    public Xamarin.Forms.Color PageBackgroundColor => Configuration.PageBackgroundColor;

But it gets ignored.

The name 'InitializeComponent' does not exist in the current context

$
0
0

This is really strange and inconsistent. Sometimes it runs fine and sometimes I get the following error

'The name 'InitializeComponent' does not exist in the current context'

There is absolutely no change in code and project settings. Just sometimes it runs and sometimes it throws this compilation error. How to resolve this?

Deleting threads from the account

$
0
0

Hi @Jingleton

Could you please delete the below mentioned threads created by me?

https://forums.xamarin.com/discussion/76372/building-a-desktop-application-on-xamarin#latest
https://forums.xamarin.com/discussion/74757/application-does-not-wait-till-api-response-is-getting#latest
https://forums.xamarin.com/discussion/72190/localization-within-an-application-in-xamarin-forms#latest
https://forums.xamarin.com/discussion/68119/session-data-getting-oveerided-while-execution
https://forums.xamarin.com/discussion/66921/replacement-of-selectedindexchanged-event-in-extended-picker
https://forums.xamarin.com/discussion/66458/popup-layout-issue
https://forums.xamarin.com/discussion/66206/picker-data-not-getting-refreshed-while-changing-it
https://forums.xamarin.com/discussion/66036/xlabs-extended-button-not-taking-in-ios
https://forums.xamarin.com/discussion/65671/implementing-swipe-in-all-devices-in-xamarin-forms
https://forums.xamarin.com/discussion/65663/dismissing-the-popup-on-clicking-outside-the-popup
https://forums.xamarin.com/discussion/65509/center-alignment-of-stack-items
https://forums.xamarin.com/discussion/65432/page-not-showing-in-ios-device
https://forums.xamarin.com/discussion/65385/formatting-styling-for-datepicker-and-extended-picker
https://forums.xamarin.com/discussion/65153/rounded-button-and-changing-text-inside-it
https://forums.xamarin.com/discussion/65003/xamarin-pcl-and-rest-api-synchronus
https://forums.xamarin.com/discussion/63749/debugging-xamarin-app-in-ios-device
https://forums.xamarin.com/discussion/63723/popuplayout-using-mvvm
https://forums.xamarin.com/discussion/63623/button-click-inside-listview-using-mvvm-concept
https://forums.xamarin.com/discussion/63477/binding-data-in-picker-using-mvvm-concept
https://forums.xamarin.com/discussion/63236/button-click-inside-a-list-view-in-xaml

Can't call API from Xamarin Forms

$
0
0

Hallo,

I installed my API in my development machine under IIS. I can call the API using a browser.
Now i want to call it via my Xamarin Forms app(using VS 2017 and a android phone connected via USB), but it doesn't work. This is my code:
protected async override void OnAppearing()
{
base.OnAppearing();
await RefreshDataAsync();
}
public async Task RefreshDataAsync()
{
Uri uri = new Uri(string.Format("http://192.168.1.85:8080/api/Loods", string.Empty));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
}
}
When is set a breakpoint on the 'RefreshDataAsync' method, it disappears on this line:
HttpResponseMessage response = await client.GetAsync(uri);
The app starts without any results or exceptions.
I also opened the port 8080 via Windows Firewall.

When calling Api then it return "Null object cannot be converted to a value type".

$
0
0

Problem is occur when we calling Api and when in response body any key value is null then it goes in catch.my question is how to accept null value in api response body.

Error come in this line:
var jsonResponse = JsonConvert.DeserializeObject(responseData);


Connectivity.NetworkAccess OnResume

$
0
0

Hi all,
my App needs to act different depending on having or not internet connection on resume.
In OnResume method I check the Connectivity.NetworkAccess property, which is first "Local" and after some time it becomes "Internet".
This occurs always, even just minimize for moment, and internet is always there.
Is this a Bug or why does it behave like this?

Currently I have a workaround by making an Task.Delay but I would prefer to get the right value instead.

Greets
Niko

In XF App PopModalAsync not invoking OnAppearing in called page on iOS13

$
0
0

A details page is called using

await Navigation.PushModalAsync(new NavigationPage(new DetailsPage(Item)));

The details page returns control to called page using

await Navigation.PopModalAsync();

Then on returning to the called page the OnAppearing() is invoked. This is still happening in Android app but not in app deployed to iOS13. But in iOS 12.x OnAppearing() is still invoked.

Any reasons? Is it a bug?

Xamarin Forms: How to parse an .epub file?

$
0
0

I am using EpubReader.Cross NuGet Package for reading epub files. For this, I have added a sample .epub book file to my main project and set the Build Action to EmbedResource. As per the document I try to parse the title, author, and coverImage details like below. But details are not correct, please have a look at the below code.

My Code

string fileName = "content.epub";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
EpubBook epubBook = EpubReader.ReadBook(stream);
// Book's title
string title = epubBook.Title;
Debug.WriteLine("title:>>"+title);
// Book's authors (comma separated list)
string author = epubBook.Author;
Debug.WriteLine("author:>>" + author);
// Book's authors (list of authors names)
List<string> authors = epubBook.AuthorList;
Debug.WriteLine("authors:>>" + authors.Count);
// Book's cover image (null if there is no cover)
byte[] coverImage = epubBook.CoverImage;
Debug.WriteLine("coverImage:>>" + coverImage);

Output

[0:] title:>>be023aa39d417e1493850a0b9de6220c
[0:] author:>>Unknown
[0:] authors:>>1
[0:] coverImage:>>

I think the issue is with reading the .epub file added on the project. My .epub file generated by converting a .opf file, is that cause the issue?

Slider Behavior in ScrollView

$
0
0

I have a fairly complicated hierarchy of controls, going from a ScrollView to a ListView, to a StackLayout with a combination of buttons and a slider. If a user scrolls the page, they can start the swipe from most anywhere, including on top of a button, and the page will scroll without triggering any UI control events. However, if they try to scroll and accidentally start swiping up or down from on top of a slider, the slider moves instead of the page scrolling.

Is there any reason this is different from the way the buttons work? Is it possible to wait until the gesture is confirmed to be horizontal before allowing the slider to activate? It's frustrating to users when they are just trying to scroll through the page but accidentally change a slider value. I can change the workflow a bit to require confirmation of a slider change, or unlock the slider first somehow, but it'd be nice to keep things simple like they are.

How to alter your sqlite tables/class without crashing the app?

$
0
0

How to alter your sqlite tables/class without crashing the app?
on some devices i got an app crash without any error msg.. usually dropping tables will result with a quick fix.. with data loss.

so: does anybody have experience with this?
do I need to write a migration code?
some components that I can use?
best practice??

thanks

Viewing all 79144 articles
Browse latest View live


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