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

Display an image inside in a text

$
0
0

I guess my code says anthing... it works but it is ugly AF and wastes a lot of resources. So any advice how I can display the text with the image inside without such a ugly solution?

<controls:WrapLayout Grid.Row="2" Spacing="3" HorizontalOptions="Center" Margin="0,10">
    <Label Text="Use" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="the" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Image Source="Link.png" HeightRequest="14" WidthRequest="14" VerticalOptions="End" />
    <Label Text="Link" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="in" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="the" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="popup" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="to" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="show" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="the" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="entry" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="in" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="the" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="corresponding" FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
    <Label Text="checklist." FontSize="14" TextColor="{DynamicResource FrameTextColor}" LineBreakMode="NoWrap" />
</controls:WrapLayout>

Download files on Windows Phone 10 or UWP using C#

$
0
0

I want to download the pdf file from server "http://che.org.il/wp-content/uploads/2016/12/pdf-sample.pdf" and save the same in local.

I using below code to achieve this. however I'm not able to download the pdf file.

I'm using the below code to download.

var uriBing = new Uri(@"http://che.org.il/wp-content/uploads/2016/12/pdf-sample.pdf");
                try
                {
                    // Create sample file; replace if exists.
                    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                    StorageFile sampleFile = await storageFolder.CreateFileAsync("Prajesh.pdf", CreationCollisionOption.ReplaceExisting);
                    //var sampleFile = await DownloadsFolder.CreateFileAsync("ManualFile.pdf", CreationCollisionOption.ReplaceExisting);
                    var cli = new HttpClient();
                    var str = await cli.GetStreamAsync(uriBing);
                    var dst = await sampleFile.OpenStreamForWriteAsync();
                    await str.AsInputStream().AsStreamForRead().CopyToAsync(dst);// AsStreamForRead().CopyTo(dst);
                }
                catch (Exception ex)
                {
                }

Is there any other approach to download and save file.

Async Task not firing on button click

$
0
0

I am trying to enable authentication on a PCL app for users to log in. I have created a function to call the rest API with a post request with email and password parameters which should return a cookie for authentication in json format. I am using newtonsoft.josn and system.net.http to handle the josn and make http calls.

The when I load the application and click the button nothing seems to happen. I have debugged with various breakpoints within the login method but it doesn't even break. Its almost as if the function is not reached on the button click. Code here:

//login button click event handler
private void btnLogin_Clicked(object sender, EventArgs e)
    {
        email = emailEntry.Text;
        password = passwordEntry.Text;
        Login(email, password);
    }

//Async task to authenticate user
private async Task<string> Login(string email, string password)
    {
        var client = new HttpClient();
        var content = new StringContent(
            JsonConvert.SerializeObject(new { Email = email, Password = password }));
        var result = await client.PostAsync("***********url*********", content);

        var tokenJson = await result.Content.ReadAsStringAsync();
        if (tokenJson != null)
        {
            await Navigation.PushAsync(new MainPage());
        }
        else {
            await DisplayAlert("Warning", "Email or password not found, please try again", "OK");
        }
        return tokenJson;
    }

newbie question (Xaml, xaml.cs, .cs)

$
0
0

Hi everyone,

I am currently doing the xamarin university courses and I noticed that when, in the videos, a new Xamarin.Forms Blank App (PLC) is created, the IDE creates an App.cs and MainPage.cs.

When I create one, the IDE creates a App.XAML with App.Xaml.cs and MainPage.XAML with MainPage.Xaml.cs.

XAML is where the design is done are XAML.CS where the logic is done or I am wright.

My question is, why or where come this change from? Why doesnt create XAML files in the course videos? An update or just a configuration difference?

Thanks in advance :smile:

Xamarin forms iOS back button label disappears

$
0
0

Hoping somebody can help or point me in a direction or confirm a bug.

We are using a navigation page flow, where we push new pages on to the stack as you progress through the task.
On iOS, the back button will show an image (<) and the text from the previous page's 'BackButtonTitle'.

The problem is that we have a page where the title changes dynamically as you scroll (don't ask; its a Requirement). When the title gets set to a long string the back button text disappears automatically, presumably to make room.

That's fine. The problem is that when the title is set back to a short text or empty string, the back button text does not reappear, leaving you with just the arrow.

I've done just about everything I can think of - including in the NavigationRenderer in the iOS project - but cannot think of ANY way of refreshing the navigation bar to get that back button text to reappear. I can detect when the title is changing back to an empty string, but nothing I do makes any difference (I've tried SetNeedsDisplay etc from various controls accessible in the NavigationRenderer to no avail).

All indications in the debugger appear to show that the text still exists, it just doesn't get displayed again

Any ideas? Is this a bug in Xamarin (using 2.3.4.224)?

Rest Service Doesn't Work on Android

$
0
0

Hi, I have created a web service. It works fine on iOS, but on Android it crashes in here: response = await client.PostAsync(uri, content);

My code:
`Estruturas.loginStruct retorno = new Estruturas.loginStruct();
user Utilizador = new user();
Utilizador.username = username;
Utilizador.password = password;

        var uri = new Uri(Constants.RestUrl) + "login";

        try
        {
            var json = JsonConvert.SerializeObject(Utilizador, Formatting.Indented);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = null;
            response = await client.PostAsync(uri, content);
            if (response.IsSuccessStatusCode)
            {
                var retornaString = await response.Content.ReadAsStringAsync();
                retorno = JsonConvert.DeserializeObject<Estruturas.loginStruct>(retornaString);
            }
            else
            {
                return new Estruturas.loginStruct();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"              ERROR {0}", ex.Message);
        }

        return retorno;`

Xamarin.Forms Android WebChromeClient

$
0
0

The point is, I need to do this in Xamarin.Forms:

Android.Webkit.WebView teste = FindViewById<Android.Webkit.WebView>(Resource.Id.navigation);
teste.SetWebChromeClient(new WebChromeClient());
teste.Settings.JavaScriptEnabled = true;
teste.LoadUrl("url");
butI using Xamarin.Forms, any one knows how to do this?

Just to explain, I try to create WebView in Xamarin.Forms that use the chrome and no the native browser to view my WebSite. Please, if any can help with example!

How do I get PCLStorage to wipe an existing file if the same file is re-opened for R/W?

$
0
0

Is there a way to get PCLStorage to open a file for writing and wipe all the current contents if the file already exists?

I have just found a slippery bug in my code whereby I was writing an XML file in which I had set a value to 'False', and then the file was being opened for R/W and the value was written as 'True', which resulted in the file having two '>' symbols at the end of the file. This appears to be because the string 'True' is one character shorter than the string 'False', so I am seeing the one character of the file's previous contents, if that makes sense.

I could just delete the file and re-create but that seems inefficient. I looked at the collision options, but there doesn't appear to be a way to use this with opening a file.

Any help would be very much appreciated.

  • Patrick

How do i align Toolbar Item to the left

$
0
0

I have two Toolbar Items Login and Home, I want to implement such that the Home item is aligned to the left and Logout on the right. I want to have the title in the middle of the two items..Can someone help me on how to implement this for both android and windows

Android memory allocation growing infinitly

$
0
0

I have been trying to figure out how to create android apps that includes navigation and images, it seems that Xamarin.Forms keeps the images on memory even if you leave the page. Not only that it doesn't recognize that the same image is already loaded in the memory.

So this is too obvious to be a bug so I imagine I'm doing something wrong, can somebody help me to understand how to fix this simple app that describes the problem I have?

namespace RandomApp
{
    public class App
    {
        public static Page GetMainPage()
        {
            var testPage = new ContentPage(){
                Title = "First Page"
            };

            var testPageButton = new Button(){
                Text = "Next Page"
            };

            testPageButton.Clicked += async (object sender, EventArgs e) => {
                await testPage.Navigation.PushAsync(new ContentPage(){
                    Title = "Second Page",
                    Content = new StackLayout(){
                        Children = {new Image(){Source = ImageSource.FromFile("random_image.jpg")}}
                    }
                });
            };

            testPage.Content = new StackLayout{
                Children = {testPageButton}
            };

            return new NavigationPage(testPage);
        }
    }
}

Getting error “SecurityError (DOM Exception 18): The operation is insecure” when storing data in web

$
0
0

I am developing one sample Xamarin.Forms Application and in this application I'm using WebView for tyro payment gateway integration and also create WebViewRenderer for store data in localStorage of UIWebView. and I'm getting security error (SecurityError (DOM Exception 18): The operation is insecure). Tyro payment gateway web url is "https://iclient.test.tyro.com".

Please have a look below my code and help me

string subkey = "window.localStorage.setItem('webTta.integrationKey','integrationKey')";
string key ="try { "+subkey +"; } catch (e) { alert(e); }";
IntegrationKey = _uiWebView.EvaluateJavascript(key);

Working with graphical elements

$
0
0

Hi,
I've been working with Xamarin Forms now for a couple of moths and actually accomplished quiet a few things that I didn't thought would be possible when I started and got a few apps ready for release, mostly location based stuff and museum guides.

But now it's time to really start to convert some of our old apps into xamarin to make them cross plattform, so this will not be a "please give me some code"-question instead more conceptual question, like how to approach this in Forms?.

We've worked alot with apps for education and children. Started in flash where this kind of apps is super simple to create, then went to Swift where there actually was a lot easier then I thought to do simple 2D graphical stuff, like frame animations and so on. But on Xamarin it feels like I'm running with my head first into walls all the way with these apps.

I will give to examples from a music- and dance app for small children that I'm should just start to convert, It's mostly a library of movies with songs and dances and that is no problem at all but then is two small games and there's where the problem starts.

I'll attach some Images, explain how I works and how I solved it in Swift and hopefully some of you can point me in the right direction on where to start looking for solutions in Forms or maybe just tell me that Xamarin forms isn't the tool for this go back to Flash and do it cross-platform there! :)!

First Game

In Swift:
This "game" works like a simple piano where each of the main roots play a tone when you click on it, the root also lights up.
In Xcode this is built up with 10 images, the background image(with the tree, the sky, the earth) and then 9 images of the different roots in the same size as the background but with a big part of transparency.This makes it easy to make sure that all get rendered on the right location.
When the user clicks on the screen, the clicked pixel value get registered and I loop through the images and check if there isn't transparancy and if so register that as a hit on that branch. Much like explaind here

Problems in Xamarin:
I don't think it's a big problem to get the pixel that is tapped on using the "Mr Gestures library" but after that I'm totally lost :(

Second Game
(Image got attaced bellow for some reason)

Swift:
Here the user touch the screen and the bumblebee flies to the finger and then follows the finger as the user "drag" over the screen. At the same time there a buzz sound is getting played and pitches depending where on the screen the bumblebee flyes. Also random eyes in the tree gets visible everytime the user start touching the screen.
While the bee flyes theres a small animation that consist of then pngs of the bee with wings in different position. Witch in Swift is just an UIimage with these images as sources and then I can stat and stop the animation by just calling the image.

Xamarin:
Here is the first real problem the frame animation of the bee, I cant find anyway to do this cross plattform. Also looked if i might be possible to work with animated gifs instead but didn't really find a way that felt good for this scenario.

As you see this isn't very complex things but very important if you like to make small simple 2d games and others apps like that and I can't really bthink that it shouldn't be possible to do this things but I find very little written about it.

So sorry for my long post but to start finding answer for this kind of interaction is extremely crucial for my continued work in xamarin. Next steps is to get deeper in to drag and drops + hit detection, something that we also worked a lot with in Flash and children games and that also seems a little hard in Forms.

Best regards!
/magnus

Custom Header in Webview

$
0
0

Hi guys,

I'm building an app with authentification, then I need to send the Token I get in every page url call. I'm using xamarin.forms and all the logic of my code is shared

I manage to get the page content using an http client (but the css and html are not "recognized" therefore the result is very bad)

I started to implement WebViewRenderer for Android and iOS to add header when I load url but I struggle to display it well in the webview.

Class in PCL
namespace SageMCOApp
{
public class BaseUrlWebView : WebView {

    public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
            returnType: typeof(string),
            declaringType: typeof(BaseUrlWebView),
            defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value);}
    }

}

}

**Class in android **
namespace SageMCOApp.Droid
{
//public class AuthWebViewRenderer : ViewRenderer<BaseUrlWebView, Android.Webkit.WebView>
//{
public class AuthWebViewRenderer : WebViewRenderer
{

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {
        base.OnElementChanged(e);

        Log.Info("Test", "A l'intérieur du renderer");

        BaseUrlWebView formsWebView = e.NewElement as BaseUrlWebView;

        Control.Settings.JavaScriptEnabled = true;

        this.Control.SetWebViewClient(new AuthWebViewClient());
    }



}

}

WebViewClient
namespace SageMCOApp.Droid
{
public class AuthWebViewClient : WebViewClient
{

    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {

        var Token = "here is the token";
        Dictionary<String, String> headers = new Dictionary<String, String>();
        headers.Add("Authorization", "Bearer " + Token);

        view.LoadUrl(url, headers);

        return true;
    }

}

}

I know thnaks to the debug that the shouldoverrideurlloading is performed but the server doesn't received the header.. I pretty sure I missed something or something is wrong but the code I see in the forum doesn't work.

Thanks a lot for your help !

Labels disappear

$
0
0

WIth this code run on UWP Windows 10 desktop:
<?xml version="1.0" encoding="utf-8" ?>

  <ListView x:Name="DeviceView" ItemTapped="OnItemTapped">
    <ListView.ItemTemplate>
      <DataTemplate>

        <ViewCell>
          <StackLayout BackgroundColor="#eee"
          Orientation="Vertical">
            <StackLayout Orientation="Horizontal">
              <Label Text="{Binding Name}" TextColor="#f35e20" />
              <Label Text="Con" TextColor="#f35e20" />
              <Switch IsToggled="{Binding IsConnected}"/>
              <Label Text="Act" TextColor="#f35e20" />
              <Switch IsToggled="{Binding IsActive}"/>
              <ActivityIndicator Color="Black" IsRunning="{Binding IsWorking}" IsVisible="{Binding IsWorking}" />
            </StackLayout>
          </StackLayout>
        </ViewCell>
      </DataTemplate>

    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

All three labels disappear (but the place is held for them) once IsWorking changes from false to true and ActivityIndicator doesn't run even IsWorking changed from false to true. This can be fixed by e.g. resizing application window - then all three labels are rendered again and ActivityIndicator runs.

It seems that labels disappear only when ActivityIndicator element is present in the code.

How to fix it?

how can i recognize long press gesture in xamarin forms

$
0
0

Hi,

Could you please let me know how can i recognize long press gesture in xamarin forms application. Also let me know how can i implement left & right swipe

Thanks & Regards,
Siva


Listview, ContextActions and Gesture error

$
0
0

Hi guys,
I discover a problem with the ListView. When you slide a record to show its ContextAction MenuItem and then you scroll the list (with the menu opens), an error occurs.

Listview error

at UIKit.UIView.RemoveGestureRecognizer (UIKit.UIGestureRecognizer gestureRecognizer) [0x00041] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/build/ios/native/UIKit/UIView.g.cs:1411
at Xamarin.Forms.Platform.iOS.ContextScrollViewDelegate.ClearCloserRecognizer (UIKit.UIScrollView scrollView) [0x00015] in :0
at Xamarin.Forms.Platform.iOS.ContextScrollViewDelegate+<>c__DisplayClass24_0.b__0 () [0x00048] in :0
at UIKit.UIGestureRecognizer+ParameterlessDispatch.Activated () [0x00000] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/UIKit/UIGestureRecognizer.cs:71
at (wrapper managed-to-native) ObjCRuntime.Messaging:void_objc_msgSend_IntPtr (intptr,intptr,intptr)
at UIKit.UIView.RemoveGestureRecognizer (UIKit.UIGestureRecognizer gestureRecognizer) [0x00021] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/build/ios/native/UIKit/UIView.g.cs:1409
at Xamarin.Forms.Platform.iOS.ContextScrollViewDelegate.ClearCloserRecognizer (UIKit.UIScrollView scrollView) [0x00032] in :0
at Xamarin.Forms.Platform.iOS.ContextScrollViewDelegate+<>c__DisplayClass24_0.b__0 () [0x00048] in :0
at UIKit.UIGestureRecognizer+ParameterlessDispatch.Activated () [0x00000] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/UIKit/UIGestureRecognizer.cs:71
at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/4466/a04678c2/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at myInspection.iOS.Application.Main (System.String[] args) [0x00008] in /Users/enricorossini/Projects/myInspection/iOS/Main.cs:18

Uploading A Video

$
0
0

hello guys ,how do i open a folder and upload video to my application using xamarin forms so that i can send the videos to a server from the mobile application?

Webview for image display - fine with iOS/Android/WP but not UWP?

$
0
0

I'm using a XF Webview to display an image (click on image in page it brings up Webview to display image full screen) which I have working fine for Android and iOS and after a bit of searching also for Windows Phone 8.1 .. but .. I'm trying to get it working for Windows UWP (also Windows 8.1 although not so vital) but whatever I try in terms of image file reference it doesn't work.

From what I've been able to find on the web the "ms-appdata:///localpath" approach should work but it doesn't and no matter which variation I try I either get blank page or occasionally with some formats I get the small x icon.

Given the code below, does anyone know what's the correct format for the "image" and "path" to use for Windows UWP (& Windows 8.1 but less vital)

    public ui_ImagePage(string image) : base(false)
    {
        setTitle("test image");

        string path = PCLStorage.FileSystem.Current.LocalStorage.Path;
        path = path + "/0/blobs";

if IOS

        path = path;

elif ANDROID

        path = "file://" + path + "/";

elif WINDOWS_PHONE

        path = path + "\\";
        image = path + image;
        path = "";

elif WINDOWS_APP

        path = "ms-appdata:///" + path + "\\";
        image = path + image;
        path = "";

elif WINDOWS_UWP

        path = "ms-appdata:///" + path + "\\";
        image = path + image;
        path = "";

endif

        HtmlWebViewSource source = new HtmlWebViewSource
        {
            Html = "<html><body><img src=\"" + image + "\"/></body></html>",
            BaseUrl = path,
        };
        WebView wv = new WebView() { Source = source };
        Content = wv;
    }

Thanks,

Derek

Correct place to call ScrollToAsync when ItemsSource changes in view model

$
0
0

On my ContentPage, I use an ItemsControl (https://github.com/xamarinhq/xamu-infrastructure/blob/master/src/XamU.Infrastructure/Controls/ItemsControl.cs) to display a horizontal StackLayout of templated items bound to an ItemsSource, inside a ScrollView.

<ScrollView Orientation="Horizontal" x:Name="MyScrollView">
  <userControls:ItemsControl ItemsSource="{Binding MyItems}" x:Name="MyItemsControl">
    <userControls:ItemsControl.ItemTemplate>
      <DataTemplate>
      ...
      </DataTemplate>
    </userControls:ItemsControl.ItemTemplate>
  </userControls:ItemsControl>
</ScrollView>

When I navigate to my page, my view model sets MyItems to an ObservableCollection, and the ItemsControl may exceed the screen width. When this happens, I need to scroll to the end of the ScrollView so the last elements in MyItems are visible.

I have tried overriding LayoutChildren in both the page and the ItemsControl, and while it sometimes works, it also is inconsistent and sometimes stops the scroll view part of the way through the items.

protected override async void LayoutChildren(double x, double y, double width, double height)
{
  base.LayoutChildren(x, y, width, height);
  if (_previousWidth != MyItemsControl.Width)
  {
    _previousWidth = MyItemsControl.Width;
    if (MyItemsControl.Width > screenWidth)
    {
      //await Task.Yield();
      await BreadcrumbScrollView.ScrollToAsync(_previousWidth-screenWidth, 0, false);
    }
  }
}

Since LayoutChildren gets called multiple times (and varies by platform), is there any way to know when the layout is complete so that I can call ScrollToAsync once?

upload File/Media/Text

$
0
0

hello,
i am trying to implement upload files(photo,video,file,link)
for photo/Video i am using this plugin : https://www.nuget.org/packages/Xam.Plugin.Media/
photo uploaded as shown in this photo:

            //pickphoto
            pickph.Tapped += async (sender, args) =>
            {
                if (!CrossMedia.Current.IsPickPhotoSupported)
                {
                    await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                    return;
                }
                var file = await CrossMedia.Current.PickPhotoAsync();


                if (file == null)
                    return;

                imagephoto.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    file.Dispose();
                    return stream;
                });
            };

            //pick video
            pickvid.Tapped += async (sender, args) =>
            {
                if (!CrossMedia.Current.IsPickVideoSupported)
                {
                    await DisplayAlert("Videos Not Supported", ":( Permission not granted to videos.", "OK");
                    return;
                }
                var file = await CrossMedia.Current.PickVideoAsync();

                if (file == null)
                    return;

                await DisplayAlert("Video Selected", "Location: " + file.Path, "OK");
            };

i applied the video upload using the same plugin, but it gives me the file path in tmp folder in the device,
i want it to see the result as what i did with image, then after clicking publish the uploaded files will be sent to an external server, is my logic right or not?
and is there any better ressources to achieve the upload to the view first?
thank you in advance,

Viewing all 76418 articles
Browse latest View live