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

Connect Xamarin App with Web app using random code pairing

$
0
0

I have a requirement.I am developing a Xamarin TV app which will receive notification from ASP.Net application.

If i want to add a new device to web application,

1.first open the TV App

2.generate a random code like XGYUIT on TV app (Something like google Chromecast pairing screen)

3.Input this Code code in Add Device screen in web application

4.Once its confirmed(paired),i should start receiving contents and notification for that particular Device Id

How to do this in Xamarin?


How can I speed up data added to sqlite database

$
0
0

Hi
I am developing an application with Xamarin Forms.
What I do is take the data provided as a service and add it to the sqlite database and update it if there is any.
But this process is very slow.
Is there any way I can speed this up?
I searched Bulk Insert but could not find an answer.
My code is here;

```Response<PagedList<ContractListDTO>> contractList = await _ContractService.GetContractList();

        if (contractList.CheckSuccess(ResponseSuccessType.ResponseMustSucceeded, ErrorLog, Position + " a ait son 100 sözleşmenin alınması"))
        {
            await Progress.ResetLevel(3, contractList.Content.Items.Count);

            foreach (ContractListDTO contractTerminate in contractList.Content.Items)
            {

            //progressBar.Progress += 2;

                await Progress.Increase(3, "Sözleşme Numarası: " + contractTerminate.ContractNumber);

                new ContractDAO().SaveOrUpdate(new Contract()
                {
                    ContractNumber = contractTerminate.ContractNumber,
                    ContractUniqueNumber = contractTerminate.ContractUniqueNumber,
                    CustomerCode = contractTerminate.CustomerCode,
                    CustomerName = contractTerminate.CustomerName,
                    CustomerType = contractTerminate.CustomerType,
                    WorkFlowApprovalStatusCode = contractTerminate.WorkFlowApprovalStatusCode,
                    StartDate = contractTerminate.StartDate,
                    EndDate = contractTerminate.EndDate
                },ContractDataSourceServiceType.ContractList);


                new ContractPromotionUserDAO().Save(new ContractPromotionUser()
                {
                    RelationshipType = (int)RelationshipType.ContractList,
                    ContractUniqueNumber = contractTerminate.ContractUniqueNumber,
                    UserId = Position.UserId,
                    PositionId = Position.PositionId,
                    Type = (int)EnumContractPromotion.Contract,
                });

                await _SyncTaskCommonService.GetFromOnlineContractDetailToLocale(contractTerminate.ContractUniqueNumber, Position.UserId, Position.PositionId, ErrorLog);

                await _SyncTaskCommonService.GetFromOnlineContractPropertyToLocale(contractTerminate.ContractUniqueNumber, ErrorLog);


public void SaveOrUpdate(Contract entity, ContractDataSourceServiceType dataSourceServiceType)
    {

        if (GetByContractUniqueNumber(entity.ContractUniqueNumber) != null)
        {
            //_connection.Update(entity);
            if (dataSourceServiceType == ContractDataSourceServiceType.PendingApprove
                || dataSourceServiceType == ContractDataSourceServiceType.LastApproved
                || dataSourceServiceType == ContractDataSourceServiceType.Rejected
                || dataSourceServiceType == ContractDataSourceServiceType.ContractList)
            {
                UpdateByPendingApproveOrLastApprovedOrRejected(entity);
            }
            else if (dataSourceServiceType == ContractDataSourceServiceType.Terminate)
            {
                UpdateByTerminate(entity);
            }
            else if (dataSourceServiceType == ContractDataSourceServiceType.Summary)
            {
                UpdateBySummary(entity);
            }
            else if (dataSourceServiceType == ContractDataSourceServiceType.ManVoyEnt)
            {
                UpdateByManVoyEnt(entity);
            }
        }
        else
            Add(entity);
    }
public void UpdateByPendingApproveOrLastApprovedOrRejected(Contract entity)
    {
        _connection.Execute(@"UPDATE Contract SET Id = ?, ContractNumber = ?, CustomerCode = ?, CustomerName = ?, CustomerType = ?, CoaStartDate = ? WHERE ContractUniqueNumber = ?",
                    entity.Id, entity.ContractNumber, entity.CustomerCode, entity.CustomerName, entity.CustomerType,
                                                           entity.CoaStartDate, entity.ContractUniqueNumber);
    }

```

on shell is it possible on bottom tabbar or top navigation put top border or bottom border line ?

$
0
0

on shell is it possible on bottom tabbar or top navigation put top border or bottom border line ?

Severity Code Description Project File Line Suppression State Error Xamarin.Android ?

$
0
0

Severity Code Description Project File Line Suppression State Error Xamarin.Android for Visual Studio requires Android SDK. Please install it or set Android SDK path on Tools->Options->Xamarin->Android Settings menu.

ADB1000: Deployment Failed... (Deployment Error)

$
0
0

Hi. I just updated Visual Studio 2019, and I keep getting the following deployment error message: "ADB1000: Deployment failed..." and "ADB1000: System.ComponentModel.Win32Exception(0x80004005): The system cannot find filed specified".
Also worth noting, I thought this only happened with the project I have been working on for a couple months now. But it also shows even when I create a NEW project.
Is this kind of a bug in the new update? Is anybody else experiencing this? And most importantly... how to fix it?
Thanks!

frame 's height seems can not be set too small?

$
0
0
    <Frame BorderColor="#000000" HasShadow="False" CornerRadius="23" HorizontalOptions="StartAndExpand" IsClippedToBounds="True"
                    WidthRequest="68.67" HeightRequest="23.33" VerticalOptions="StartAndExpand">
     </Frame>

the height of the frame seems can not be set smaller than 23 . nothing changed while i reduce the height.

Data is not getting deleted using web api in xamarin forms

$
0
0

Hello Sir,
Below is the code for deleting data from database using web api, but here the data is not getting deleted. please help
//code for web api
public Response deleteprogressnotes(Progressnotes notes)
{
Response response = new Response();
try
{
SqlCommand cmd = new SqlCommand("crm_sp_delete_progressnotes", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@notesId", notes.notesId);

            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                response.Message = "Deleted successfully";
                response.Status = 1;
            }
            else
            {
                response.Message = "Failed to delete"
                response.Status = 0;
            }
        }
        catch (Exception ex)
        {
            response.Message = ex.Message;
            response.Status = 0;

        }
        return response;
    }

code delete.xaml.cs
private async void Button_Clicked_1(object sender, EventArgs e)
{
Progressnotes progress = new Progressnotes();
progress.notesId = Convert.ToInt32(notes.Text);
string url = "http://******/api/Delete/deleteprogressnotes";
HttpClient client = new HttpClient();
string JsonData = JsonConvert.SerializeObject(progress);
StringContent content = new StringContent(JsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.DeleteAsync(url);
string result = await response.Content.ReadAsStringAsync();
Response responsedata = JsonConvert.DeserializeObject(result);
if (responsedata.Status == 1)
{
await Navigation.PushAsync(new Progress_notes());
NavigationPage.SetHasNavigationBar(this, true);
}
else
{
noelse.Text = "Welcome";

        }
    }

Please help
Thanks

Viewing a local SQL Database (based on tutorial)

$
0
0

Hi!

I'm not new to Xamarin, but I'm new to SQL databases in Xamarin. I want to create a simple app (practise-app) where I can save values to a local database and read these values. I used the following tutorial to get me started: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases
This tutorial does help, tho it can be a bit difficult sometimes.

However, my problem is the following: I wanted to see the database myself, so I located it (on Android) and opened it with DB Browser for SQLite. At this point I added nothing to the app database. so my home screen is empty. This database is located in Todo.Android\Resources\raw\TodoSQLite.db3

This is what I see:

I cannot see these items in my app and when I do add something new, the app shows this item but I cannot see this in the database.

What am I missing here?

Hope someone can help.


How to do a list of devices on the local network ?

$
0
0

Hello,
I m working on a home automation project and I have to do an application.
To be in communication with a hub I must scan the local network to detect him.
I tried to do a ping test but I had a timeout for every devices.
I tried to send a request to the hub but after a few request I have a strange exeptions.
After, I tried a ping with shell but the devices don't replied.
Have you an idea ?
Thank You

Xamarin forms: Contact search returns no values

$
0
0

I have done the fetching of contacts from the phone using this blog.

My Code:

XAML

<StackLayout>
        <SearchBar x:Name="filterText"
                    HeightRequest="40"
                    Text="{Binding SearchText}" />
        <ListView   ItemsSource="{Binding FilteredContacts}"
                    HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10"
                                     Orientation="Horizontal">
                            <Image  Source="{Binding Image}"
                                    VerticalOptions="Center"
                                    x:Name="image"
                                    Aspect="AspectFit"
                                    HeightRequest="60"/>
                            <StackLayout VerticalOptions="Center">
                                <Label Text="{Binding Name}"
                                   FontAttributes="Bold"/>
                                <Label Text="{Binding PhoneNumbers[0]}"/>
                                <Label Text="{Binding Emails[0]}"/>
                            </StackLayout>

                            <Switch
                                Toggled="OnToggledEvent"
                                HorizontalOptions="EndAndExpand"
                                VerticalOptions="CenterAndExpand"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Viewmodel

public class MainViewModel: INotifyPropertyChanged
{
    IContactsService _contactService;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Title => "Contacts";

    public string SearchText { get; set; }
    public ObservableCollection<Contact> Contacts { get; set; }
    public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }
    public MainViewModel(IContactsService contactService)
    {
        _contactService = contactService;
        Contacts = new ObservableCollection<Contact>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts, null, ObservableCollectionCallback);
        _contactService.OnContactLoaded += OnContactLoaded;
        LoadContacts();
    }


    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        // `lock` ensures that only one thread access the collection at a time
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    private void OnContactLoaded(object sender, ContactEventArgs e)
    {
        Contacts.Add(e.Contact);
    }
    async Task LoadContacts()
    {
        try
        {
            await _contactService.RetrieveContactsAsync();
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Task was cancelled");
        }
    } 
}

Contact and IContactsService

public class Contact
{
    public string Name { get; set; }
    public string Image { get; set; }
    public string[] Emails { get; set; }
    public string[] PhoneNumbers { get; set; }
}

public class ContactEventArgs : EventArgs
{
    public Contact Contact { get; }
    public ContactEventArgs(Contact contact)
    {
        Contact = contact;
    }
}
public interface IContactsService
{
    event EventHandler<ContactEventArgs> OnContactLoaded;
    bool IsLoading { get; }
    Task<IList<Contact>> RetrieveContactsAsync(CancellationToken? token = null);
}

My problem is the search feature in contacts returns no data.

Search Code in Viewmodel

public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }

I have attached a sample project with this question.

Style methods

$
0
0

Hi

I have come across two methods of styles as below; one of them uses ResourceDictionary. What are the pros and cons, or is it just individual preference?

Thanks

Regards

    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.ForegroundColor" Value="#333" />
                <Setter Property="Shell.TitleColor" Value="White" />
                <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
            </Style>
            <Style BasedOn="{StaticResource BaseStyle}" TargetType="TabBar" />
        </ResourceDictionary>
    </Shell.Resources>

and

    <Shell.Resources>
            <Style x:Key="BaseStyle"
               TargetType="Element">
                <Setter Property="Shell.BackgroundColor"
                    Value="#455A64" />
                <Setter Property="Shell.ForegroundColor"
                    Value="White" />
                <Setter Property="Shell.TitleColor"
                    Value="White" />
                <Setter Property="Shell.DisabledColor"
                    Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor"
                    Value="#95FFFFFF" />
            </Style>

            <Style TargetType="ShellItem"
               BasedOn="{StaticResource BaseStyle}" />

            <Style x:Key="DomesticShell"
               TargetType="Element"
               BasedOn="{StaticResource BaseStyle}">
                <Setter Property="Shell.BackgroundColor"
                    Value="#039BE6" />
            </Style>
    </Shell.Resources>

Getting an error while displaying the data

$
0
0

Hello Sir,
Below is the code for displaying the data using web api but I'm getting an error.please help.thanks
user_permission user = new user_permission();
user.UserId = Convert.ToInt16(userid.Text);
string url = "http://*******/api/accessuser/details";
HttpClient client = new HttpClient();
string JsonData = JsonConvert.SerializeObject(user);
StringContent content = new StringContent(JsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
var details = JsonConvert.DeserializeObject<List>(result);
Models1.ItemsSource = details;

Error
Newtonsoft.Json.JsonSerializationException
Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[App2.user_permission]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Message', line 1, position 11.

Salesforce mobile SDK for Xamarin.Forms

$
0
0

Is there a salesforce SDK library available for either Xamarin.Forms, or Xamarin.Android and Xamarin.iOS? I can create the Xamarin.Android and Xamarin.iOS binding with the native SDKs, but it relays to a lot of dependencies and it takes time in general. If you are aware of any good Xamarin SDK library for salesforce, please suggest me.

Android SDK : https://github.com/forcedotcom/SalesforceMobileSDK-Android
iOS SDK : https://github.com/forcedotcom/SalesforceMobileSDK-iOS

Thanks,
Prabakaran

PRISM / ListView ItemTapped Questions

$
0
0

I am using PRISM to catch the ItemTapped-Event, like so:

<ListView.Behaviors>
    <prism:EventToCommandBehavior EventName="ItemTapped" Command="{Binding BindingContext.ItemTappedCommand, Source={x:Reference viewModel}}" EventArgsParameterPath="Item" />
</ListView.Behaviors>

Question 1: How can I extend the logic to "DoubleTap" ?
Question 2: Now it reacts on every tap and I open a new page. If the user makes a Double-Tap, the Page opens twice ! How can I check, if a Page is already opened ?

How to keep the DisplayPromptAsync open?

$
0
0

Hi,

I am using below code to show the DisplayPrompt fo a password PIN but I want when the user clicks on Ok button to keep the DisplayPrompt open so user can try another PIN.

string pin = await DisplayPromptAsync("Password PIN", "Please enter the password PIN:", "Next", "Cancel", "Password PIN", 6, Keyboard.Numeric);

if (pin != password_pin)
{
    await DisplayAlert("Error", "Invalid Password PIN", "Try Again");
    return;
}

How can I do that?

Thanks,
Jassim


App Crashing while sending email attachment using Xamarin essentials

$
0
0

Hi Team,

App is crashing after launching email client with attachment (more than 400 kb) in android device using xamarin essential for email client.

Tried in native implementation as well, there also same result, sending txt file attachment.(using dependency service)

Please find the attached screenshot for your reference. Expecting the valuable suggestions.thanks in advance.

Below code for sending email:

   List<string> recipients = new List<string>() { recipient };
            var message = new Xamarin.Essentials.EmailMessage
            {
                Subject = subject,
                To = recipients,
                Body = "Body"
            };
            var logFile = Path.Combine(FileSystem.CacheDirectory, FileName);
            File.WriteAllBytes(logFile, Encoding.ASCII.GetBytes(LogFileText));
            message.Attachments.Add(new Xamarin.Essentials.EmailAttachment(logFile));
            AddAttachments(message);
           ** await Email.ComposeAsync(message);** // after executing this app will crash.

Support to convert the HTML to PDF in Xamarin Forms

$
0
0

Support to convert the HTML to PDF in Xamarin Forms

Barcode scanner with flash light is not working

$
0
0

In Xamarin forms for barcode scanner am using ZXing.Net.Mobile.Forms and Acr.BarCodes plugin but when i tried to scan the code with flash light plugin(kphillpotts.Lamp.Plugin) scanner is not working and i am getting error message java.lang.runtimeexception fail to connect to camera service.

Please someone help on this.

Open PDF from WebView

$
0
0

I need help with handling PDFs in my Xamarin.Forms WebView Application. I tried a few things and got to the point where I think it is the least complicated crossplattform solution to just leave the App and show the PDF in default PDF Viewer with

Xamarin.Essentials.Launcher.OpenAsync(Url);

This works but I have the following problem: The PDF files are stored on the same url scheme where my App is registered. So the chooser which opens after calling

Xamarin.Essentials.Launcher.OpenAsync(Url);

shows my App (which isnt able to display PDFs) as suitable program to open the PDF. I want to prevent that the user can choose my App to open the PDF.

I am a bit stuck now because there seems to be no way to exclude some urls from deeplinking and i dont want to put the PDFs on another url scheme.

Any advice?

Edit: Forgot to say that I am trying to solve this issue on Android atm. Didnt look too far in iOS.

is it possible multi color of indicator for each tabbed page?

$
0
0

is it possible multi color of indicator for each tabbed page? if is custom renderer please help me android and ios thanks..

Viewing all 79144 articles
Browse latest View live


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