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

HttpClient not responding at first attempt

$
0
0

Hi everyone,
I am developing a cross platform mobile app, whenever I sent my app to release on Apple's App Store, my app is rejected because of connection problem. I detect the problem and it is caused by my rest api. To connect my server, there are fields that take server ip and port number, and I use these inputs to create query. After click login button, query is generated and system is tried to connect to the server, but main problem here is that, first connection attempt is not happened. When I run both server and client sides in debug mode, my request do not recieve to the server side. This happens only if app is installed to new device (if app is not installed before that device). If I relaunch app after closing it, connection is established and everything works as expected.

I use try catch block to get what is the error message but the problem never happen on my device and iphone/android emulators. Here is the codes both client and server side.

Client:

public async Task getData()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");

        DataModel model = new DataModel();

string addr = "http://" + txtServer.Text + ":" + txtPort.Text + "/Service/api/test/getData";

        var response = await client.PostAsync(addr,
            new StringContent(JsonConvert.SerializeObject(model),
            Encoding.UTF8, "application/json"));

        var result = await response.Content.ReadAsStringAsync();

        var res = JsonConvert.DeserializeObject<ResultStruct>(result);

        return JsonConvert.DeserializeObject<DataModel>
            (res.Data.ToString());
    }

Server:

[HttpPost]
[Route("getData")]
public ResultStruct getData()
{
ResultStruct result = new ResultStruct();
result.Result = true;
try
{
result.Data = getDataFromDB();
result.Message = "Success";
}
catch (Exception ex)
{
result.Result = false;
result.Message = ex.Message;
}
return result;
}


Icon change when tapped

$
0
0

Hi,

I have a question: how do I change an icon when I tap on it?

CarouselView PropertyChanged always null

$
0
0

I have recently added the CarouselView plugin from Alex Rainman to my application.

The problem I have is that the PropertyChanged event in my view model is always null, therefore I can't push any property changes to the UI. Is this a known problem?

The page uses the DataTemplateSelector to allow my to add a different set of pages to the view, at runtime, could that be the problem? I'm using existing base classes that implement INotifyPropertyChanged and they work fine on all other pages except the CarouselView one.

Does NControl work with xamarin live player

$
0
0

Hello,

I was so amazed how xamarin live player works till I installed NControl library. It just does not show controls of this library in live mode.
Is there any additional work that has to be done to make Ncontrol work properly with xamarin live?

Greetings

DataTemplateSelector in custom control throwing exception

$
0
0

Hi Guys,

I am attempting to create a custom control which uses a DataTemplateSelector, it is basically a horizontally scrollable list.
I've hit a snag (as the title suggests), but I'm not 100% convinced that my code is to blame, as it's a pretty straightforward use case.

Basically, when iterating the ItemsSource when rendering, I call ItemTemplateSelector.CreateContent(). When I use a literal DataTemplate defined in the XAML, everything works as it should, but if I use a DataTemplateSelector which is defined as a StaticResource (as it instructs you to in XF docs) it blows up with the following exception.

(sorry for the non-links, not allowed to post them yet)
github.com/sparkeh9/XamarinFormsListViewIssue/blob/master/exception.jpg

I was hoping someone could tell me whether my code is at fault or not :sweat_smile: - a distilled version of my issue (which I replicated on a brand new project is at github.com/sparkeh9/XamarinFormsListViewIssue

Existing S.O post for reference stackoverflow.com/questions/49825489/datatemplateselector-for-custom-control-invalidoperationexception

Much appreciated,
Nick

So dissapoineted

$
0
0

Every release of xamiran forms I get that we bit more excited but even still file new project forms does not build from the start ! Get the act together the stability of this platform is now so shocking !

Errors everywhere. Intellisense not working.

$
0
0

First of all, i'm new to Xamarin. I have never developed for any mobile device before. Most of my experience is with VB.NET but I can handle C# just fine.
I want to create a cross platform app so I start with a new project and select the Cross-Platform App (Xamarin Forms) and select the Blank App template to create the solution. I open the App.xaml.cs file and the first thing I see is red lines everywhere. The error list shows I have 19 errors and I haven't even touched one line of code! Clean and rebuild have no effect. Shutting down Visual Studio and reopening the solution does have effect. All the errors disappeared like magic. Ok, that's weird but maybe there is a good explanation... anyone?

I add a new item, the Master Detail Page and I name it "myMaster". It builds and runs fine. Then I want to rename the class in myMaster.xaml.cs to "myMaster2". Visual Studio suggest that I rename all references and that sounds good to me. I then get an error saying

The file '' could not be refactored. Object reference not set to an instance of an object.

I continue the refactoring and I see the same error multiple times. After that my project shows no errors but the build fails and running the app fails too. I close Visual Studio (again) and reopen the solution. Still no errors but Rebuild Solution keeps failing.
I also manually changed the x:Class in the XAML file to FormsTest.myMaster2 because that didn't change with the refactor. Bug?

Is Visual Studio 2017 still in beta or something? Is intellisense not working well? Or is it just me as a newbie?
It is very hard to start working with Xamarin if you cannot rely on the editor. These are just some examples of problems I have run into. No actual code has been written. It's just that I want to quit before even getting started with Xamarin. It all feels so buggy.

I'm working with Visual Studio Professional 2017 version 15.5.7.

[edit] I also notice that when changes are made in the xaml files the code behind xaml.cs does not notice the changes. A restart of VS is required to get them to show up.

Changed one image into item of CarouselPage

$
0
0

I am programming an application for light control. Each room of a house is represented by each page contained in a CarouselView.

each page is loaded with three images:
1: ImagenON
2: ImageOff
3: ImagenStatus

ImagenStatus is an image of a room with lights on. When I press the Off image, Image status should change to another image with the lights off.

With the MVVM model, I managed to change this image but it is replicated to all the pages contained in the CarouselView.

The idea is that only the event occurs on the page where I made the process ... do you have any ideas?

Could you help me with an example?
I am new to xamarin and I need a simple example to change objects inside a carousel view ... for example, I could change the text of a Label, or change an image with a button both inside a carousel view .. ..

Thanks Please. Help, this of the Itemtemplates is very complicated,


Has anyone got BadgeCount working with BottomNavigationBarXF?

$
0
0

I'm using a third-party plugin called BottomNavigationBarXF which display tabs at the bottom edge of the screen on Android. I got the tabs working but whenever I set the BadgeCount (as per their sample), I get following exception:

Position 11:110. Cannot assign property "BadgeCount": Property does not exists, or is not assignable, or mismatching type between value and property

Json.DeserializeObject Always Null

$
0
0

Hi Everybody,Could i ask for some help ?
I write the code but why everytime i used Json.DeserializeObject always got null value ?
I check null value with DisplayAlert but if content from readasstringasync not null

Thank You

protected async void OnGetList()
{
try
{
using (var cl = new HttpClient())
{
var formcontent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("key","getallimage")
//new KeyValuePair<string, string>("password","shah")
});
var request = await cl.PostAsync(Url, formcontent);

                request.EnsureSuccessStatusCode();
                var content = await request.Content.ReadAsStringAsync();
                
                //Activity indicator visibility on
                activity_indicator.IsRunning = true;

                var tr = JsonConvert.DeserializeObject<BarangCs>(content);
                //Getting JSON data from the Web
                //var content = await _client.GetStringAsync(Url);
                //We deserialize the JSON data from this line
                //After deserializing , we store our data in the List called ObservableCollection

                ObservableCollection<Resultbarang> trends = new ObservableCollection<Resultbarang>(tr.resultbarang);
                DisplayAlert("O", trends[0].nama, "Ok");
                //Then finally we attach the List to the ListView. Seems Simple :)
                myList.ItemsSource = trends;


                //We check the number of Items in the Observable Collection
                int i = trends.Count;
                if (i > 0)
                {
                    //If they are greater than Zero we stop the activity indicator
                    activity_indicator.IsRunning = false;
                }

                //Here we Wrap  the size of the ListView according to the number of Items which have been retrieved 
                i = (trends.Count * heightRowsList);
                activity_indicator.HeightRequest = i;
            }
        }
        catch (Exception ey)
        {
            Debug.WriteLine("" + ey);
        }


    }

Dynamically added List items on groupheader click only shows up in view after scrolling a bit.

$
0
0

Am trying to add List items dynamically to ListView on click of GroupHeader to achieve an expandable and collapsible effect.

The ListView is on rg.Plugins.Popup page.

Everything works fine except the List Item does not show up or hide unless I scroll till the GroupHeader is out of the view and then scroll back.

have attached screenshots for reference

Below is my XAML code

<ListView Style="{StaticResource ListStyle}" ItemsSource="{Binding AssociatedStateCityList}" IsGroupingEnabled="True" HasUnevenRows="True">
                <ListView.GroupHeaderTemplate >
                    <DataTemplate >
                        <ViewCell Height="40">
                            <Grid x:Name="StateCitiesInfo">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width=".9*"/>
                                    <ColumnDefinition Width=".1*"/>
                                </Grid.ColumnDefinitions>
                                <Label Grid.Column="0" Style="{StaticResource ListLabel}" Text="{Binding StateName}" FontSize="{StaticResource MediumFontSize}">
                                    <Label.GestureRecognizers>
                                        <TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding Source={x:Reference AssociatedCityStateList}, Path =BindingContext.LoadAssociatedCityList}" CommandParameter="{Binding Source={x:Reference StateCitiesInfo}, Path=BindingContext}"/>
                                    </Label.GestureRecognizers>
                                </Label>
                            </Grid>

                        </ViewCell>
                    </DataTemplate>
                </ListView.GroupHeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Height="30">
                            <Label Grid.Column="0" Grid.Row="0" Style="{StaticResource ListLabel}" Text="{Binding Name}"  FontSize="{StaticResource SmallFontSize}"/>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

View Model code

public ObservableCollection<AssociatedCityList> AssociatedStateCityList { get; set; }

......
 foreach(State state in states)
                {
                    GetAssociatedCities(state);
                    var ascl = new AssociatedCityList
                    {
                        StateId = state.Id,
                        StateName = state.Name,
                        IsSelected = false
                    };
                    ascl.AddRange(new List<City>{ });
                    AssociatedStateCityList.Add(ascl);
                }
............

 LoadAssociatedCityList = new Command<AssociatedCityList>( async (AssociatedCityList StateCitiesInfo) => 
                {
                    if (StateCitiesInfo.IsSelected)
                    {
                        StateCitiesInfo.Clear();
                        StateCitiesInfo.IsSelected = false;
                    }
                    else
                    {
                        List<City> cities = await App.Database.GetCityListAsync(StateCitiesInfo.StateId);
                        StateCitiesInfo.AddRange(cities);
                        StateCitiesInfo.IsSelected = true;
                    }
                });


Grouped list class

 class AssociatedCityList : List<City>
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public bool IsSelected { get; set; }
        public List<City> CityList => this;
    }

How can create Xamarin Form Native App?

$
0
0

Hi guys,
I'm a beginner for the Xamarin Form. So I'll learn the strategy of Native Application development using Xamarin.Form. Please tell me how should start it. And please tell me what is the difference between "Shared project" and ".Net Standard". And also, what are the best one.

Encoding camera video in MJPEG (cross-platform)

$
0
0

How can I encode video being captured from camera as an MJPEG?

Perhaps using cross-platform versions of FFMPEG?

I need MJPEG since the analyses I'll perform on the video stills require a intra-frame only codec to be used (i.e. no inter-frame like H264 et al.)

Thank you,

Federico

Compile error in new project

$
0
0

I created a new project and copied files from an existing one. After resolving all errors (except this one), when I try and run it gives me an error "could not resolve reference .../bin/iphone/debug/system.enterpriseservices/wrapper.dll".

I saw a few articles but nothing I have tried fixes.

Running 15.6.4.

Ask user to turn on location and network in Xamarin Forms

$
0
0

Hello.

I am developing an app written in Xamarin.Forms (mainly for Android and iOS) with some services. In this services I need to request the location of the device and send them through the netowrk to request some data from a server.

My question here is the following:
How can I ask the user to turn on the location service and the network if they are not enabled ?

I am using the permissions plugin, connectivity plugin and geolocator plugin all developed by James Montemagmo. So far I searched for some snippets on this matter but I didn't find any suitable solution for my needs.
In my code I enabled the check for the location permission and the network permission and it works well either is it on or off, but I don;t know how can I ask the user to turn them on.

I want to make something like (if it's possible), or to make a request to user to turn them on separately.

Any help on this matter would be deeply appreciated.
Thanks in advance :# !


Not Refreshing Xamarin.Forms.DataGrid List.

$
0
0

Hello, Xamarians I am using to Xamarin.Forms.DataGrid plugins and create a dynamic column in C#, I am retrieving data on monthly wise 3,6,12 months.
but when I call API first time is successfully showing next time only columns changes.
what can I do Plz help me ... :(

Loading Image

$
0
0

Hi,
I'm in front to a strange issue:

in my app I've encapsulated a certificate (*.cer) to use it to verifiy my server identity.

  • when I try to load a simple image from another server via SSL (this server has a public certificate),
    the image is not displayed.

  • when I try to display the same image from my server, the image is displayed.

  • when I try to do the same thing in a simple app with just one image (I sculpt the image link in the code) the image is displayed

this my code:

image load:

// get image path from Server
_imagePath = ServiceConnector.getProfileImageT(App.PersonalDetail.UID,App.PersonalDetail.Token).Result;
// set ImageSource
_imgProfile.Source = new UriImageSource { CachingEnabled = true, Uri = new System.Uri(_imagePath) };

...

loading de certificate

public static void getCert()
        {
            var assembly = typeof(Utility).GetTypeInfo().Assembly;

            // certificato self signed
            Stream stream = assembly.GetManifestResourceStream("Menu.telecomitalia.cer");
            Stream streamL = assembly.GetManifestResourceStream("Menu.telecomitalia_self.cer");

            // certificato pubblico
            //Stream stream = assembly.GetManifestResourceStream("Menu.timpeople.cer");
            ServiceConnector.getCert(Utility.ReadToEnd(stream));
            ServiceConnector.getCertLocal(Utility.ReadToEnd(streamL));
        }
public static byte[] ReadToEnd(System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
public static class ServiceConnector
{   
    public static X509Certificate Certificate { get; set; }
    public static void getCert(byte[] certificate)
    {
            int _iResult = 0;
            string _error = "";

            X509Certificate _cert = new X509Certificate();
            try
            {
                _cert.Import(certificate);
                Certificate = _cert;
            }
            catch (IOException ex)
            {
                _iResult = -1;
                _error = ex.Message;
            }
            catch (Exception ex)
            {
                _iResult = -2;
                _error = ex.Message;
            }

        CertificateImport = Tuple.Create(_iResult,_error);
    }

Has anyone solved the deployment pipeline problem? [DevOps]

$
0
0

I'm a purist at heart and DevOps is a passion of mine. One principle that I hold near and dear is the idea that an assembly should be built (compiled) once and then deployed to the various environments. This keeps your build versioning clean, and helps you identify where something went wrong because the build number is perfectly unique.

Let's take an example of an app that relies on an external Restful API.

In a typical .NET application, I'll build my dll as release, and then as I deploy it to dev, I'll update the app.config to point to the dev ApiUrl.
As I promote the application to qual/test, I'll do another xml config update, pointing the ApiUrl to the test endpoint.
Finally, I promote the application to production, and I do a final xml config update, and I point the ApiUrl to the production API.

Now, we have our wonderful Xamarin Forms application, and the concept of xml config is lost when we package the application. I don't want to re-compile the application per environment as that defeats the "Build it once" principle.

So has anyone solved this? For dev, I can just use a standard #ifdev

#if DEBUG
    ApiUrl = "dev.myapp.com";
#endif

This is easy. It gets trickier when we use HockeyApp for our Qual/Test environment. I need to rely (somehow) on the tooling to indicate where the app came from. I've asked if the do anything like that, but am still awaiting a response.

How to create customCell with custom data

$
0
0

As i'm understood,we use the method "SetBinding" for to obtain data
But if i'm use a custom class for data, i havn't that method. How i can extend the my class for that?

var image = new Image();
var nameLabel = new Label();
var typeLabel = new Label();

//set bindings
nameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
typeLabel.SetBinding(Label.TextProperty, new Binding("Type"));
image.SetBinding(Image.SourceProperty, new Binding("Image"));

my class:

public class TextTable
    {
        public string Name { get; set; }
        public string[] Column { get; set; }
        public DataFormat[] Data { get; set; }
     }

Unable to invoke Backdoor method

$
0
0

We are trying to invoke a backdoor method to bypass logging in as xamarin is unable to interact with the azure login page.

I have added the following to my MainActivity class

[Export("MyBackdoorMethod")]
    public void MyBackdoorMethod()
    {
        System.Diagnostics.Debug.WriteLine("In through the backdoor - do some work");
    }

I have also added this to my Test

    [Test]
    public void FirstLogin()
    {
        app.Screenshot("First screen.");
        app.Tap("Get Started");

        Thread.Sleep(TimeSpan.FromSeconds(10));

        app.Invoke("MyBackdoorMethod");

        app.Screenshot("Login Screen");
    }

But when executing the test I keep getting the following

    System.Exception : Error while performing Invoke("MyBackdoorMethod", null)
      ----> System.Exception : Invoke for MyBackdoorMethod failed with outcome: ERROR
    No such method found: MyBackdoorMethod()

How do I ensure the test is able to execute the method....??

Viewing all 58056 articles
Browse latest View live


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