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

How to turn on/off Wifi and Bluetooth programmatically?

$
0
0

How to turn on/off Wifi and Bluetooth programmatically?


How do I create a periodic background job for iOS?

$
0
0

I am creating an app for a customer used by their staff which requires the ability to send data back to a main repository via an API. If there is no internet connection the data is flagged, and a periodic background job will check for outstanding data requiring uploading if a connection is available.

I have this working for the Android version of the application using a dependency service (I'm following the Microsoft architecture example from here https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/).

When the app starts it calls my android implementation:-

public void SetupBackgroundSync()
        {
            Context context = Application.Context;
            var schedule = 30;

            using (var manager = (AlarmManager)context.GetSystemService(Context.AlarmService))
            {
                var syncIntent = new Intent(context, typeof(BackgroundSync));
                var pendingIntent = PendingIntent.GetService(context, 0, syncIntent, PendingIntentFlags.CancelCurrent);
                manager.SetRepeating(AlarmType.RtcWakeup, 1000 * 60 * schedule, 1000 * 60 * schedule, pendingIntent);
            }
        }

I can't seem to find a good example of how to do this for iOS. I've read the documentation on the background task options and it seems I would be looking at a Long Running Task - but it seems 'hacky' to have a timer within that to check for data I need to send back to an API every 30 minutes.

Does anybody have any examples/suggestions I could use?

Is there a way i can use the webview.postURL on xamarin.forms?

$
0
0

I'm creating an app wrapping my website with Xamarin.forms. I want to implement login page on my mobile app that will by pass the login on the website using webview.postURL. Does postURL works for both iOS and android ? or android only? If it only works on android is there a way to do it for both platform?

I'm new to xamarin and c#, example codes or a github link would help me a lot.

SocketAsyncResult.CheckIfThrowDelayedException () exception on Android

$
0
0

I have below exception when i want to connect to my api. This exception is happening in some special cases. for example, when I am in my gym, i am able to reproduce it. my gym is having a wireless connection using this service https://www.freefii.de/
when I connect to it, general internet connection is fine and fast but somehow my app is returning this exception every time i make api request.
Any idea what could be the problem?

"type": "System.Net.WebException",
"message": "Error: ConnectFailure (Network subsystem is down)",
"stackTrace": " at System.Net.WebConnection.Connect (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) [0x00217] in :0 \n at System.Net.WebConnection.InitConnection (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) [0x000cc] in :0 \n at System.Net.WebOperation.Run () [0x0009a] in :0 \n at System.Net.WebCompletionSource1[T].WaitForCompletion () [0x00094] in <a13a876c512b4bd799407c195d4b8176>:0 \n at System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func`1[TResult] aborted, System.Threading.CancellationTokenSource cts) [0x000f8] in :0 \n at System.Net.Http.HttpClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002e7] in :0 ",

here is the code I am using;

 private static HttpClient getClient()
        {
                  HttpClientHandler handler = new HttpClientHandler
                    {
                        Proxy = Xamarin.Forms.DependencyService.Get<Helpers.IProxyInfoProvider>().GetProxySettings()
                    };
                     HttpClient _client= new HttpClient(handler);

                  return _client;
     }

 using (HttpClient client = getClient())
       {
                 HttpResponseMessage response = await client.GetAsync(uri, ct)
        }

In Android Project

 public class ProxyInfoProvider : IProxyInfoProvider
    {
        public WebProxy GetProxySettings()
        {
            string proxyHost = JavaSystem.GetProperty("http.proxyHost");
            string proxyPort = JavaSystem.GetProperty("http.proxyPort");

            return !string.IsNullOrEmpty(proxyHost) && !string.IsNullOrEmpty(proxyPort)
                ? new WebProxy($"{proxyHost}:{proxyPort}")
                : null;
        }
    }

Xamarin Forms Map becomes unresponsive if used in new shell

$
0
0

Hello,

Does anyone has this problem that when a page with forms map is used as menu item in new shell navigation, the map becomes quite unresponsive to drag events.

How to bind the logged in `player data` retrieved from database to populate in Register.xaml view.

$
0
0

In my Xamarin Forms app, how to bind the logged in player data retrieved from database to populate in Register.xaml view. This should be done on OnProfilePicClicked method

Register.xaml

<ContentPage.Content>







</ContentPage.Content>

MainPage.xaml.cs class:

private async void OnProfilePicClicked(object sender, EventArgs e)
{
//Navigate to Register screen with player data loaded:
var emailText = emailEntry.Text;
await Navigation.PushAsync(new Register(){});
List details = (from x in conn.Table() where x.Email == emailText select x).ToList();
if (details!= null)
{
// found the record here, but how to pass to view...

            PlayerDetails playerDetails = new PlayerDetails();
            playerDetails.FullName = details[0].FullName;
            playerDetails.Mobile = details[0].Mobile;
            playerDetails.SoccerPosition = details[0].SoccerPosition;
        }

    }

**PlayerDetails model class : **

string fullname;
string mobile;
string soccerposition;

    public PlayerDetails()
    {

    }

    public string FullName
    {
        set
        {
            if (fullname != value)
            {
                fullname = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("FullName"));
                }
            }
        }
        get
        {
            return fullname;
        }
    }

    public string Mobile
    {
        set
        {
            if (mobile != value)
            {
                mobile = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Mobile"));
                }
            }
        }
        get
        {
            return mobile;
        }

    }

    public string SoccerPosition
    {
        set
        {
            if (soccerposition != value)
            {
                soccerposition = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("SoccerPosition"));
                }
            }
        }
        get
        {
            return soccerposition;
        }
    }

Packages.Config build errors since updating Xamarin forms 3.6.0.344457

$
0
0

Hi,

i recently updated to Xamarin Forms 3.6.0.344457 and since then, my android build no longer builds, the errors are very odd, as in, it looks like packages.config has something wrong with it.

The XML in itself looks ok but upon building, i am getting the errors as identified in the pic.

Switch -> EventToCommand: Detect if Toggled from user interaction or from webservices/websocket sync

$
0
0

Hello,
first of all, sorry for my english

I have a page with a number of Switch..each switch turn on/off a remote light using webservices.
To make this I used behaviors and Command in ViewModel linked to Toggled event (we call it SetOnOffSwitchCommand)

At page appearing I call a command to load the real state of each switch (we call it OnAppearingCommand),
In this command I call a w.s. and I set on or off each Switch using a IsToggled binded property
Each time I set on or off a Switch, my 'SetOnOffSwitchCommand' is called, and this is not good.
To fix this problem I add in 'SetOnOffSwitchCommand' a way to exit the command without calling the ws:
if (isBusy) then return;
In fact in my OnAppearingCommand I have a 'IsBusy' boolean used to show an ActivityIndicator.

The problem is that I use websocket too, to update the switch status while the user has the page opened.
If a websocket specific message is received, I call a third command in my viewmodel (SetOnOffFromWebServicesCommand)
The problem is that, also using the 'IsBusy' trick, when I change the state of a Switch, the SetOnOffSwitchCommand is called, and the IsBusy flag is set to false form the SetOnOffFromWebServicesCommand before the SetOnOffSwitchCommand is called.

Exist a sure way to fix my problem?
Thanks!


Image Inside Picker control

$
0
0

Hii How to add an Image Inside picker as show below

How to disable the content when button was clicked

$
0
0

I need to disable the content or put an overlay in my project. I have a floating button when this floating button clicked I need to expand some images in the right corner(I did this part). Also, I need when the button clicked it needs to overlay the current content. the problem is I need custom code for that when button clicked it should overlay.

My content view

   <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     xmlns:customRenderes="clr-namespace:DipsDemoXaml.CustomRenderes;assembly=DipsDemoXaml"
     x:Class="DipsDemoXaml.Views.Page1"
     x:Name="navi">

<StackLayout >



        <customRenderes:NavigationImageButton Source="MenuSettings"                                                
                                                  x:Name="Button1"                                                        
                                                Margin="0"                                                       
                                                    IsVisible="{Binding Visibility1}"                                                                                                                                                                                                                                                                                                                       
            />


This is how I called this whenever I need that floating button

  <AbsoluteLayout>
   <views:Page1 AbsoluteLayout.LayoutFlags="PositionProportional"  AbsoluteLayout.LayoutBounds="1,1,-1,-1" ></views:Page1>
     </AbsoluteLayout>

I need to add an overlay also I cannot mess with all my pages so it should include in the ContentView page. How to do it, How to add a popup overlay in contentview

WebView.Navigated and ViewModel

$
0
0

Is it possible for to capture the Navigated Event of WebView Control in Xamarin Form when using Prism in View Model ? My Control Definition looks like following

How to implement below wavesurfar design?Please advice

How to do unit testing in xamarin forms?

$
0
0

I created one project using xamarin forms. There I need to do unit testing on following methods

private int _valueA;

        public int ValueA
        {
            get { return _valueA; }
            set
            {
                _valueA = value;
                OnPropertyChanged();
            }
        }

        private int _valueB;
        private int _result;

        public int ValueB
        {
            get { return _valueB; }
            set
            {
                _valueB = value;
                OnPropertyChanged();
            }
        }

        public int Result
        {
            get { return _result; }
            set
            {
                _result = value;
                OnPropertyChanged();
            }
        }

        public ICommand AddCommand
        {
            get
            {
                return new Command(() =>
                {
                    Result = _valueA + _valueB;
                });
            }
        }

        public ICommand MultiCommand
        {
            get
            {
                return new Command(() =>
                {
                    Result = _valueA * _valueB;
                });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        } 

In the view page, I am using Binding context

<ContentPage.BindingContext>
        <vm:MathViewModels />
    </ContentPage.BindingContext>

    <StackLayout Orientation="Vertical">
        <Entry FontSize="30" Text="{Binding ValueA}" />
        <Entry FontSize="30" Text="{Binding ValueB}" />
        <Button Text="Add" Command="{Binding AddCommand}"/>
        <Button Text="Multiply" Command="{Binding MultiCommand}"/>

        <Label Text="{Binding Result}"></Label>
    </StackLayout>

After this, I added unit test project there I created methods like following

[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void AddCommand1()
        {
            try
            {
                var vm = new MathViewModels();
                vm.ValueA = 4;
                vm.ValueB = 6;

                vm.AddCommand.Execute(null);

                Assert.AreEqual(10, "vm.Result != 10");
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        [TestMethod]
        public void MultiplyCommand1()
        {
            try
            {
                var vm = new MathViewModels();
                vm.ValueA = 4;
                vm.ValueB = 6;

                vm.MultiCommand.Execute(null);

                Assert.AreEqual(24, "vm.Result != 24");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

I added reference of xamrin forms project in the unit test project
When I run my test methods I am getting following error

What is the issue? How to overcome this?

Copy attached properties to new instance in xamarin forms

$
0
0

I am creating new instance of grid object which have two labels as following.


<Grid.ColumnDefinitions>


</Grid.ColumnDefinitions>
<Grid.RowDefinitions>

</Grid.RowDefinitions>


I am using Activator.CreateInstance method as given below:

Grid ClonedView =(Grid) Activator.CreateInstance(Grid.GetType());

        foreach (PropertyInfo propertyInfo in Grid.GetType().GetProperties())
        {
            if (propertyInfo.CanRead && propertyInfo.CanWrite  )
            {

                object PropertyValue = propertyInfo.GetValue(Grid, null);

                propertyInfo.SetValue(ClonedView, PropertyValue);

            }
        }

When I use this ClonedView in my page, but Cloned Grid don't understand that Label2 should appear in second column of grid. I did a lot of research on it but could not find any solution. Please let me know if anybody has any solutions.

thanks

Shell - Navigate into inner tab of a different Shell

$
0
0

Hello,
I have a main shell page 'AppShell.xaml' with Flyout navigation
In this shell I have 2 FlyoutItem with a single ShellContent (we call it Page1 and Page2) and 1 FlyoutItem with 4 ShellContent (4 tab pages)

From Page1 I need to go into a sandwitch page (with upper and bottom tabs)
For this way I write a second shell page (CoreShell.xaml) with Flyout disabled.

CoreShell.xml:
`<?xml version="1.0" encoding="UTF-8"?>

<Shell.Resources>
    <ResourceDictionary>

    <Style x:Key="BaseStyle" TargetType="Element">  
        <Setter Property="Shell.ShellTabBarBackgroundColor" Value="{StaticResource tabBarBackgroundColor}" />  
     </Style>

    <Style x:Key="SicurezzaStyle" TargetType="Element" BasedOn="{StaticResource BaseStyle}">            
        <Setter Property="Shell.ShellTitleColor" Value="{StaticResource tabSecurityFontColor}" />    
        <Setter Property="Shell.ShellTabBarTitleColor" Value="{StaticResource tabSecurityFontColor}" /> 
        <Setter Property="Shell.ShellForegroundColor" Value="{StaticResource tabSecurityFontColor}" />
    </Style>

    <Style x:Key="SmartHomeStyle" TargetType="Element" BasedOn="{StaticResource BaseStyle}">
        <Setter Property="Shell.ShellTitleColor" Value="{StaticResource tabSmartHomeFontColor}" />
        <Setter Property="Shell.ShellForegroundColor" Value="{StaticResource tabSmartHomeFontColor}" />
    </Style>

    <Style x:Key="ClimaStyle" TargetType="Element" BasedOn="{StaticResource BaseStyle}">
        <Setter Property="Shell.ShellTitleColor" Value="{StaticResource tabClimaFontColor}" />
        <Setter Property="Shell.ShellForegroundColor" Value="{StaticResource tabClimaFontColor}" />
    </Style>

    <Style x:Key="SistemaStyle" TargetType="Element" BasedOn="{StaticResource BaseStyle}">
        <Setter Property="Shell.ShellTitleColor"  Value="{StaticResource tabSistemaFontColor}" />
        <Setter Property="Shell.ShellForegroundColor" Value="{StaticResource tabSistemaFontColor}" />
    </Style>                  
    </ResourceDictionary>

</Shell.Resources>

<ShellItem>
    <Tab Icon="tab_security_unsel"  Title="Sicurezza" Style="{StaticResource SicurezzaStyle}" >    
        <ShellContent Title="Scenari"        ContentTemplate="{DataTemplate view:ScenariPage}" />
        <ShellContent Title="Aree e zone"   ContentTemplate="{DataTemplate view:AreeZonePage}" />
        <ShellContent Title="Telecamere"    ContentTemplate="{DataTemplate view:TelecamerePage}" />
    </Tab>

    <ShellContent Icon="tab_smart_home_unsel" Title="Smart Home" Style="{StaticResource SmartHomeStyle}" 
                  ContentTemplate="{DataTemplate view:SmartHomePage}" />

    <ShellSection Icon="tab_clima_unsel" Title="Clima" Style="{StaticResource ClimaStyle}">
        <ShellContent Title="Clima 1" ContentTemplate="{DataTemplate view:WaitingClimaPage}" />
    </ShellSection>

    <ShellSection Icon="tab_system_unsel" Title="Sistema" Style="{StaticResource SistemaStyle}">
        <ShellContent Title="Generali"  ContentTemplate="{DataTemplate view:GeneraliPage}" />
        <ShellContent Title="Guasti"  ContentTemplate="{DataTemplate view:GuastiPage}" />
        <ShellContent Title="Eventi"  ContentTemplate="{DataTemplate view:EventiPage}" />
    </ShellSection>        

</ShellItem>

`

To show the sandwitch page, I push this Shell page to Navigation;
CoreShell coreShell = new CoreShell();
await Shell.Current.Navigation.PushAsync(coreShell);

and all is working as expected. Of course in this way I see the first upper tab of the first bottom tab

My questions:
1) There is a way to open the coreShell page to a different inner tab?
2) There is a way to add ShellContent to a ShellSection programmatically from behind code? For example, for 'Clima' ShellSection the number of tab is not fixed, and I could build it runtime

Thanks
Matteo


How to know if a Label has been tail truncated?

$
0
0

I set MaxLines on a label to 5 and LineBreakMode to TailTruncation. How can I know if the text was indeed truncated so that I can show a "View More" button? Note that I'm setting FormattedText since I have Spans with different colors in the text. When I look at FormattedText in the debugger, I still see the original text.

How to get Navigating event of WebView in ViewModel in Xamarin.Forms ??

$
0
0

i want to get Navigating event of WebView in ViewModel in Xamarin.Forms. Please tell me how i can achieve it ??

List was not found. Verify that you are not missing an assembly reference

$
0
0

Hi,

Why I keep getting:

List was not found. Verify that you are not missing an assembly reference

although the:

using System.Collections.Generic;

I deleted the obj and bin files and rebuilt the solution but still getting the same error..

Kindly help..

Thanks,
Jassim

Xamarin.Forms bug? System.ObjectDisposedException: Cannot access a disposed object

$
0
0

Hi,

My Android Xamarin.Forms application uses a Navigation stack to display various views, I often have a list on a screen (A) that once a cell is clicked I push onto the stack a new screen (B), the user completes some form fields and then clicks a button to save. Once they click the 'save' button a task is created on the thread pool to asynchronously perform some work (no async/await and no dependency on any UI) and the view is popped back to screen (A).

Once the task is completed, it fires a simple event using the PubSub library, on the UI thread, so screen (A) has the opportunity to refresh from the local database and it does.

The problem is that when I go to drag the updated list on screen (A), the app crashes with an ObjectDisposedException intermittently (like 1 in 50 times)...

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Android.Views.GestureDetector'.
  at Java.Interop.JniPeerMembers.AssertSelf (Java.Interop.IJavaPeerable self) [0x00030] in /Users/builder/data/lanes/3819/c1d1c79c/source/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.cs:153
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualBooleanMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00002] in /Users/builder/data/lanes/3819/c1d1c79c/source/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:57
  at Android.Views.GestureDetector.OnTouchEvent (Android.Views.MotionEvent ev) [0x0002c] in /Users/builder/data/lanes/3819/c1d1c79c/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Android.Views.GestureDetector.cs:1546
  at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Android.Views.View.IOnTouchListener.OnTouch (Android.Views.View v, Android.Views.MotionEvent e) [0x0003f] in C:\BuildAgent2\work\aad494dc9bc9783\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:101
  at Android.Views.View+IOnTouchListenerInvoker.n_OnTouch_Landroid_view_View_Landroid_view_MotionEvent_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_v, System.IntPtr native_e) [0x00019] in /Users/builder/data/lanes/3819/c1d1c79c/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Android.Views.View.cs:3558
  at at (wrapper dynamic-method) System.Object:4eaabbb9-8c1c-4ea1-b505-44c325bbb1ab (intptr,intptr,intptr,intptr)

I'm not sure why it says that I cannot access a disposed object, I'm interacting with a list with a gesture detector, it's on-screen, so it's not disposed.

Is this a bug in Xamarin.Forms?

On a similar note, if I modify an MVVP property that notifies listeners that a property has changed (I always check it's on the UI thread first), then if that's bound to a Xamarin.Forms list but it's not currently on-screen, presumably Xamarin.Forms will not barf ? After-All it's just off-screen and should still bind okay?

Allow the Editor control to grow as content lines are added

$
0
0

I have been modifying the Todo app that uses Forms and replaced the note Entry class with the Editor class, so the todo can hold multiline notes. However the editor does not expand as new lines are entered. I have a Forms Editor Control nested inside a stack layout / scroll view - how do I allow the editor to grow each time the user enters another line of data? I had some success by count the '\n' characters in the text each time it changes and making a HeightRequest to the Editor, but I don't know how to calculate the exact extra height to add for each row in a reliable way. This process also feels clunky too. Can the editor control not be told to simply grow as new content is added by the user?

Viewing all 91519 articles
Browse latest View live


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