Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all 204402 articles
Browse latest View live

Can't catch exceptions from HttpWebRequest after Xamarin update

$
0
0

Hi,

I recently updated everything in my Visual Studio Mac installation. I still use Xamarin Forms 3.1 though.

After this update, I have got a lot of crashes from Android users (I haven't released the iOS version yet) and it seems to be related to HttpWebRequest. I use it in the following way:

        WebRequest req = HttpWebRequest.CreateDefault(new Uri(url));
        req.Timeout = TimeoutMilis;
        ...
        using (Stream dataStream = req.GetRequestStream())
        {
            dataStream.Write(data, 0, data.Length);
        }

I have a try catch around it, but it seems like these errors are not caught. The stack traces I get are not very helpful either:

        android.runtime.JavaProxyThrowable: System.AggregateException: A Tasks exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.Net.WebException: The request was aborted: The request was canceled. 

        caused.AggregateException(s)
        System.Net.HttpWebRequest.<MyGetResponseAsync>d__243.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        --- End of inner exception stack trace ---
        ---> (Inner Exception #0) System.Net.WebException: The request was aborted: The request was canceled.
        System.Net.HttpWebRequest.<MyGetResponseAsync>d__243.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0

Another similar crash:

         android.runtime.JavaProxyThrowable: System.AggregateException: A Tasks exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.ObjectDisposedException: Cannot access a disposed object. 

        caused.AggregateException(s)
        Object name: 'System.Net.Sockets.Socket'.
        System.Net.Sockets.Socket.ThrowIfDisposedAndClosed()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.SocketTaskExtensions.<>c.<ConnectAsync>b__2_1(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Threading.Tasks.TaskFactory<TResult>.FromAsyncCoreLogic(IAsyncResult iar, Func<T, TResult> endFunction, Action<T> endAction, Task<TResult> promise, bool requiresSynchronization)<e7c4dd6cd0ad467d9712102a6791959b>:0
        System.Net.WebConnection.<Connect>d__16.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebConnection.<InitConnection>d__19.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<Run>d__57.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebCompletionSource<T>.<WaitForCompletion>d__15.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<GetRequestStream>d__49.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        --- End of inner exception stack trace ---
        ---> (Inner Exception #0) System.ObjectDisposedException: Cannot access a disposed object.
        Object name: 'System.Net.Sockets.Socket'.
        System.Net.Sockets.Socket.ThrowIfDisposedAndClosed()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.SocketTaskExtensions.<>c.<ConnectAsync>b__2_1(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Threading.Tasks.TaskFactory<TResult>.FromAsyncCoreLogic(IAsyncResult iar, Func<T, TResult> endFunction, Action<T> endAction, Task<TResult> promise, bool requiresSynchronization)<e7c4dd6cd0ad467d9712102a6791959b>:0
        System.Net.WebConnection.<Connect>d__16.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebConnection.<InitConnection>d__19.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<Run>d__57.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebCompletionSource<T>.<WaitForCompletion>d__15.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<GetRequestStream>d__49.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0

Has anyone had a similar problem?


How to Add a custom button on the top of keyboard

$
0
0

I want to add a button above keyboard. When I show the keyboard I want to show this button. There is an example here but unfortunately, it is for ios.

forums.xamarin.com/discussion/22438/trying-to-make-next-and-prev-buttons-on-keyboard-through-custom-renderer-any-suggestions

Resize View on content changed

$
0
0

I have the following situation:

On my xaml page I have a setup that looks like this:

Open Bracket ScrollView Close Bracket
Open Bracket local:MyView x:Name="Test" BackgroundColor="White" BackgroundImageFilePath="{Binding BackgroundAttachment.LocalAttachmentFilePath}"
StrokeColor="{Binding StrokeColor}" StrokeWidth="{Binding StrokeWidth}"/ Close Bracket
Open Bracket /ScrollView Close Bracket

This is, roughly, supposed to be a drawing pad. the user can set a background image and then draw all over it.

It has a Renderer, which contains these fields:

    ImageView imageView;
    Canvas sketchCanvas;
    Bitmap backgroundBmp; 

It has an OnElementChanged which does roughly:

protected override void OnElementChanged(ElementChangedEventArgs<SketchPadView> e)
        {
            base.OnElementChanged(e);
            if (Control == null && e.NewElement != null)
            {

                imageView = new Android.Widget.ImageView(Forms.Context);
                //imageView.SetMinimumHeight(2300);
                //imageView.SetMinimumWidth(2300);
                SetNativeControl(imageView);                
            }
            if(e.OldElement != null)
            {
                e.NewElement.SketchBytesRequested -= OnSketchBytesRequested;                
            }
            if (e.NewElement != null)
            {
                e.NewElement.SketchBytesRequested += OnSketchBytesRequested;
                Element.Reset = () => Reset();
                Element.Redo = () => Redo();
                Element.Undo = () => Undo();                
            }
        }

and then there are other methods that set sketchCanvas and backgroundBmp into imageView.

The problem comes when zooming.

I'm doing:

private void RescaleImage(float newParentScaling)
        {
            float oldParentScaling = ParentScaling;
            float removeOldParentScaling = 1 / oldParentScaling;
            ParentScaling = newParentScaling;
            sketchCanvas.Scale(removeOldParentScaling, removeOldParentScaling);
            sketchCanvas.Scale(newParentScaling, newParentScaling);
            foreach (var pInfo in sketchPathInfos)
            {
                Matrix m = new Matrix();
                m.SetScale(removeOldParentScaling, removeOldParentScaling);
                pInfo.Path.Transform(m);
                m.SetScale(newParentScaling, newParentScaling);
                pInfo.Path.Transform(m);
            }
        }

Which works well enough for handling the sketchCanvas, and backgroundBmp is also taken care of. But the imageView size doesn't change. I can give it a height/width in its constructor (up in onElementChanged), and if I make them very big there then my scrollView (all the way at the top in the xamarin page) dutifully lets me scroll up and down it. But most of it starts out as empty. That is, I can scroll around a big empty imageView with a small sketchCanvas up there in the corner.

What i'd like to do is change the size of my imageView along with my sketchCanvas, such that the scrollView would show a scrollbar when imageView got big, and not do so when it was small. In a perfect world it would also start out the same size as the scrollView, a la 'FillAndExpand' behavior.

But the only thing I can seem to set on the imageView is the minimumHeight/minimumWidth parameters, and while those affect the ScrollView if I set them at the beginning, they don't seem to do so if I set them at the end of my RescaleImage function. Is there a way to set the imageView's height/width, or in other ways resize it, such that I can have MyView grow and shrink with its content, with the user scrolling about in the scrollView when it is too large?

Xamarin with Azure IoT Hub

$
0
0

May I know how to show or plot the graph of sensors data from Azure IoT hub by using Xamarin.Forms?

Infinite Timeout with HttpWebRequest on some URLs

$
0
0

Hei Guys,

i need to communicate in an iOS App with an WCF - Service. So VS created some Proxy-Classes and all Works fine and well. Also the Timeouts work well. But if the Communication is made over a local adress, and we are not in the WIFI, the app hangs forever after the second call to the websevice is made. The Timeout works on the first Request well, but in the second request the timeout never will be executed.

The problem is not the WCF Generated Code it is reproducable with a Simple HttpWebRequest. After the second call, the app hangs forever.

Code that reproduces the Problem:

`public override void ViewDidLoad()
{
base.ViewDidLoad();
ServicePointManager.MaxServicePointIdleTime = 1000;
ServicePointManager.DnsRefreshTimeout = 1000;
}

partial void UIButton220_TouchUpInside(UIButton sender)
{
txtViewArea.Text += "\n URL-Reachable-Test: ";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https" + ":// + "sg.eurowig.local/");

request.Timeout = 1000;
request.ContinueTimeout = 1000;
request.ReadWriteTimeout = 1000;
request.KeepAlive = false;
request.ServicePoint.MaxIdleTime = 1000;
request.Method = "HEAD"; // As per Lasse's comment
try
{
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        txtViewArea.Text += "OK";
    }
}
catch (WebException exc)
{
    txtViewArea.Text += "ERROR\n--" + exc.Message;
}
finally
{
    request.Abort();
    request = null;
    GC.Collect();
}

}`

As you See i tried already some Timeouts-Props of the WebRequest-Object but nothing helps.

Does anyone have a clue how to do this the right way?

Thanks in advance.

PS: the formation of the link is, because i cant post here, links...

Xamarin.Forms Previewer Android is initialize forever

$
0
0

Hi,

As can see by the attached image Previewer on Android mode initialize forever.
No problem with iOS mode.

I am using VS 2017 with latest updates also all nuget packages are up to date.
Xamarin Android Settings is pointing to jdk1.8.0_131 version 64bit.
I have try Clean, Rebuild etc. but nothing get it to work.

Thanks for any advice,
AG

Store server return value

$
0
0

I receive return list with that

and I call to list with this

When clicking this list view item I want to call another page with position;

How to convert c# object to native NSObject

$
0
0

Hi , i am having the object data in which current datasource item is stored in forms. I need to map the item to native item.

NSObject obj = (NSObject) data;

It shows the error as cannot convert object to NSObject and Cast is not applicable .

Anyhelp is appreciated


Cannot open pdf document in Pdf viewer

$
0
0

Hi

i am currently trying to open a web pdf in xamarin forms page using following code

Device.OpenUri(new Uri(strWebUrl));

When i click , some pdf's are showing option as "Open with Drive PDF Viewer" . But some pdf's are showing only options of Chrome and IE

Please advice me on this

regards,
Vinay

OnDnsSdTxtRecordAvailable is not fired some times

$
0
0

I am developing the the application for transferring data in offline.I used the IDnsSdTxtRecordListener for sensing the near by device.And implement the function OnDnsSdTxtRecordAvailable,this function is not called some times.I need to get the IP address of the nearby devices.

If anyone have an idea,Please suggest me ,How to solve/Overcome this issue.

Thanks in advance

How to open PDF or TXT file in default app on Xamarin Forms

$
0
0

I am going to open document using default app in Xamarin Forms. I tried already this approach but it doesn't work for me and I am not sure what is the reason.

Device.OpenUri(new Uri(FILE_PATH));

Please give me great solution if anyone knows how to handle it. Thanks.

Xamarin Forms Application build problem missing DLL

$
0
0

**Error ** : The "ResolveLibraryProjectImports" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'DummyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'DummyApp.dll'
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection1 jars, ICollection1 resolvedResourceDirectories, ICollection1 resolvedAssetDirectories, ICollection1 resolvedEnvironments)
at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() DummyApp.Android C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets~~~~

**Error **: CS0006 Metadata file 'E:\Folder\DummyApp\DummyApp\DummyApp\DummyApp\bin\Debug\netstandard1.4\DummyApp.dll' could not be found DummyApp.iOS E:\Folder\DummyApp\DummyApp\DummyApp\DummyApp.iOS\CSC

How can we apply MVVM pattern in xamarin.android step by step

$
0
0

How can we apply MVVM pattern in xamarin.android step by step

MVVM pattern in xamarin.android

$
0
0

Can any one plz tell me that we can apply mvvm pattern in xamarin.android the same way like we apply in xamarin.forms if yes then plz give me a reference about that or any example will be helpful

TabbedPage icons not shown when set position to bottom

$
0
0

Hello All,

I am a beginner in Xamarin and trying to use TabbedPage for my application. When I used TabbedPage and set the icons, it works fine.

Then I set the TabbedPage position to bottom.

However, when I run the application, the TabbedPage icons are not visible and even the width is too long for one Tab

Below is my XAML code:

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="//xamarin.com/schemas/2014/forms"
            xmlns:x="//schemas.microsoft.com/winfx/2009/xaml"
            xmlns:views="clr-namespace:App5.Views"
            x:Class="App5.Views.MainPage"
            BarBackgroundColor="LightYellow"
            BarTextColor="Black"
            xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
            android:TabbedPage.ToolbarPlacement="Bottom"
            android:TabbedPage.BarItemColor="Black"
            android:TabbedPage.BarSelectedItemColor="Red">
    <TabbedPage.Children>
        <NavigationPage Title="Tab1" Icon="Tab1.png">
            <x:Arguments>
                <views:ItemsPage />
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Tab2" Icon="Tab2.png">
            <x:Arguments>
                <views:AboutPage />
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Tab3" Icon="Tab3.png">
            <x:Arguments>
                <views:AboutPage />
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Tab4" Icon="Tab4.png">
        <x:Arguments>
            <views:AboutPage />
        </x:Arguments>
    </NavigationPage>
    </TabbedPage.Children>
</TabbedPage>

Can anyone please help me on this?


Grid Column expands when Label break line

$
0
0

Greetings everyone, I'm having a problem when my Label binded with the text "displayString" inside the listview stacklayout is too large and breaks the line, expanding the column it belongs, its shown in the image below:

Here is the code of the ListView, have anyone faced this problem before?

<ListView
                x:Name="MyListView"
                Margin="5,0,0,0"
                CachingStrategy="RecycleElement"
                HasUnevenRows="True"
                IsGroupingEnabled="false"
                ItemsSource="{Binding DevicesList, Mode=TwoWay}"
                RowHeight="60">
                <ListView.Behaviors>
                    <local1:ListViewTappedItemBehavior Command="{Binding DeviceTappedCommand}" Converter="{StaticResource SelectedItemConverter}" />
                </ListView.Behaviors>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <!--<ViewCell.ContextActions>
                                <MenuItem
                                    Command="{Binding Path=BindingContext.ShareDeviceCommand, Source={x:Reference Name=MyListView}}"
                                    CommandParameter="{Binding .}"
                                    Text="Compartilhar" />
                                <MenuItem
                                    Command="{Binding Path=BindingContext.RemoveDeviceCommand, Source={x:Reference Name=MyListView}}"
                                    CommandParameter="{Binding .}"
                                    IsDestructive="True"
                                    Text="Excluir" />
                            </ViewCell.ContextActions>-->
                            <ViewCell.View>
                                <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal">
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="4*" />
                                            <ColumnDefinition Width="20*" />
                                            <ColumnDefinition Width="4*" />
                                            <ColumnDefinition Width="4*" />
                                        </Grid.ColumnDefinitions>
                                        <Image
                                            Grid.Column="0"
                                            Aspect="AspectFill"
                                            HeightRequest="50"
                                            Source="{Binding ImageResourceId}"
                                            VerticalOptions="Center" />
                                        <StackLayout Grid.Column="1" Orientation="Vertical">
                                            <Label
                                                FontAttributes="Bold"
                                                FontSize="Large"
                                                Text="{Binding name}"
                                                TextColor="Black" />
                                            <Label
                                                FontSize="Medium"
                                                Text="{Binding displayString}"
                                                TextColor="Black" />
                                        </StackLayout>
                                        <Image
                                            Grid.Column="2"
                                            HeightRequest="50"
                                            HorizontalOptions="EndAndExpand"
                                            Scale="1.2"
                                            Source="acceptShareIcon.png"
                                            VerticalOptions="Center">
                                            <Image.GestureRecognizers>
                                                <TapGestureRecognizer Command="{Binding Path=BindingContext.AcceptShareCommand, Source={x:Reference MyListView}}" CommandParameter="{Binding .}" />
                                            </Image.GestureRecognizers>
                                        </Image>
                                        <Image
                                            Grid.Column="3"
                                            HeightRequest="50"
                                            HorizontalOptions="EndAndExpand"
                                            Scale="1.2"
                                            Source="declineShareIcon.png"
                                            VerticalOptions="Center">
                                            <Image.GestureRecognizers>
                                                <TapGestureRecognizer Command="{Binding Path=BindingContext.DeclineShareCommand, Source={x:Reference MyListView}}" CommandParameter="{Binding .}" />
                                            </Image.GestureRecognizers>
                                        </Image>
                                    </Grid>
                                </StackLayout>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Very strange error

$
0
0

Hi all togehter,
as asked in this thread:

https://forums.xamarin.com/discussion/142159/strange-error-2#latest

I have a very strange error.
As before, running as UWP works perfectly, the problem is only in Android.

After updating all files with NuGet and Visual Studio 15.9.5 i get the following error.

try
{
await Table.PullAsync($"all{Identifier}", Table.CreateQuery()).ConfigureAwait(false);
}

        catch (MobileServicePushFailedException push_ex)
        {
            ShowPushError(this.ToString() + " -> PullLatestAsync", push_ex);
        }

        catch (Exception ex)
        {
            Debug.WriteLine("<PullLatestAsync()>Unable to pull items, that is alright as we have offline capabilities: " + ex);
            return false;
        }      
        return true;

The error raises in await Table...…..
and was catched in catch (Excepiion e)

{System.Net.Http.HttpRequestException} System.Net.Http.HttpRequestException
base {System.InvalidOperationException} System.InvalidOperationException
System.Net.WebExceptionStatus.NameResolutionFailure System.Net.WebExceptionStatus

Help is needed very urgend because i have no idea where to look and what to do...

Thanks in Advance
Peter

Is System.Net.Mqtt package reliable?

$
0
0

Hello everyone,
I need to have MQTT communication in my app and it seems that the most used package is this one: https://github.com/xamarin/mqtt
Do you guys use it or preffer other package?
I'm a bit afraid since it is in prerelease

How to set image title, description/caption & tags

$
0
0

Hello there,

I'm trying to set the image properties like title, caption/description & tags but failing with it. I'hv done it in my windows app but with the same code i'm failing in my mac application.

I have used "BitmapDecoder/BitmapEncoder" to set the above properties but this doesn't work on mac.
This requires Presentation.Core & WindowsBase dlls in windows but same dlls are not working for mac platform.

I have tried CGImageSource/ImageIO.CGImageProperties for it also but had no luck so far.

Can someone help me out please. Please let me know if any input is required from my side.

Thanks.

How to set increment counter in TextWatcher in getView method ?

$
0
0

I'm trying to add some results from a quiz so that when user gets each right answer it adds 1 to it but the code below never gives me the right answer the 'correctAns = correctAns+1' gives me all 5 at once, if I make the correctAns as local variable this will give me 1 for every right answer but it will not add up. Can any one please help.

```public class AdapterListView extends ArrayAdapter {

        private int correctAns = 0;

         public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
            super(context, resource);
            this.mContext = context;
            this.setQuestionsArrayList(questionsArrayList);
            this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        ....
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ...

            holder.editText.addTextChangedListener(new TextWatcher() {

                public void afterTextChanged(Editable s) {

                    if (holder.editText.getText().toString().trim().length() > 0) {
                        int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));

                        if (getAnswersList().get(position) != inputNum) {
                            holder.imgFalse.setVisibility(View.VISIBLE);
                            holder.imgTrue.setVisibility(View.GONE);
                        } else {

                            correctAns = correctAns+1;

                            holder.imgTrue.setVisibility(View.VISIBLE);
                            holder.imgFalse.setVisibility(View.GONE);
                        }                    
                    }
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            return convertView;
        }

        static class ViewHolder {
            TextView questionTextView;
            EditText editText;
            ImageView imgTrue, imgFalse;
        }
    }`
Viewing all 204402 articles
Browse latest View live


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