Problem with async and await

Hi,

Why when i put the "await GetImageAsBase64Url" in the foreach loop i get an error?

If i use it outside of the loop it works... This is my first time i work with async and await...

var content is for testing, normally i will use html from web.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Xamarin.Forms;

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using HtmlAgilityPack;

namespace Agora
{
public class Test : ContentPage
{
public Test()
{
}

    protected override async void OnAppearing()
    {
        var content = @"<html><head></head>
                    <body>
                    <h1>Xamarin.Forms</h1>
                    <p>Testing images in webview!</p>
                    <img src='/documents/image.jpg'/>
                    </body>
                    </html>";

        var document = new HtmlDocument();
        document.LoadHtml(content);

        foreach (var image in document.DocumentNode.Descendants("img"))
        {
            var src = image.GetAttributeValue("src", null);

            string imageBase64 = await GetImageAsBase64Url(
                "https://www.mysite.com" + src,
                "login",
                "password"
                );

            image.SetAttributeValue("src", imageBase64); 
        }

        var htmlSource = new HtmlWebViewSource { Html = document.ToString() };
        var browser = new WebView { Source = htmlSource };
        Content = browser;
    }

    public async static Task<string> GetImageAsBase64Url(string url, string user, string pw)
    {
        var credentials = new NetworkCredential(user, pw);
        using (var handler = new HttpClientHandler { Credentials = credentials })
        using (var client = new HttpClient(handler))
        {
            var bytes = await client.GetByteArrayAsync(url);
            return "data:image/jpg;base64," + Convert.ToBase64String(bytes);
        }
    }
}

}

Thanks

Tagged:

Best Answer

Answers

  • PubuduGayanPubuduGayan ✭✭✭ NZMember ✭✭✭

    Hi @Jean-FrancoisBouchard.2645 can you post your error.

  • Jean-FrancoisBouchard.2645Jean-FrancoisBouchard.2645 ✭✭ USMember ✭✭

    When the program it this line in GetImageAsBase64Url function :

    var bytes = await client.GetByteArrayAsync(url);

    VS 2015 indicates "Frame not in module"

Sign In or Register to comment.