I need to call C# event in xamarin.forms after the function is completed in js.Please guide
function readTextFile(file)
{
try
{
var blob = null;
var rawFile = new XMLHttpRequest();
rawFile.open(""GET"", file);
rawFile.responseType = ""blob"";//force the HTTP response, response-type header to be blob
rawFile.onload = function()
{
blob = rawFile.response;//xhr.response is now a blob object
wavesurfer.loadBlob(blob);
wavesurfer2.loadBlob(blob);
}
rawFile.send();//I need to call C# event here.Please guide.
}
catch(err)
{
}
}
Solution:
You can implement it by using CustomRenderer
1.create a HybridWebView in forms
public class HybridWebView : View
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create (
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri {
get { return (string)GetValue (UriProperty); }
set { SetValue (UriProperty, value); }
}
public void RegisterAction (Action<string> callback)
{
action = callback;
}
public void Cleanup ()
{
action = null;
}
public void InvokeAction (string data)
{
if (action == null || data == null) {
return;
}
action.Invoke (data);
}
}
in contentPage.xaml
<ContentPage.Content>
<local:HybridWebView x:Name="hybridWebView" Uri="xxx.html"
HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
</ContentPage.Content>
in code behind
public MainPage ()
{
...
hybridWebView.RegisterAction (data => DisplayAlert ("Alert", "JS action has been called", "OK")); //you can do something other as you want
}
in iOS project
[assembly: ExportRenderer (typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace xxx.iOS
{
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
WKUserContentController userController;
protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged (e);
if (Control == null) {
userController = new WKUserContentController ();
var script = new WKUserScript (new NSString (JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript (script);
userController.AddScriptMessageHandler (this, "invokeAction");
var config = new WKWebViewConfiguration { UserContentController = userController };
var webView = new WKWebView (Frame, config);
SetNativeControl (webView);
}
if (e.OldElement != null) {
userController.RemoveAllUserScripts ();
userController.RemoveScriptMessageHandler ("invokeAction");
var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup ();
}
if (e.NewElement != null) {
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", Element.Uri));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
}
}
public void DidReceiveScriptMessage (WKUserContentController userContentController, WKScriptMessage message)
{
Element.InvokeAction (message.Body.ToString ());
}
}
}
in Android project
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace xxx.Droid
{
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
{
const string JavascriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new Android.Webkit.WebView(_context);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));
SetNativeControl(webView);
}
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.LoadUrl($"file:///android_asset/Content/{Element.Uri}");
}
}
}
}
And
public class JavascriptWebViewClient : WebViewClient
{
string _javascript;
public JavascriptWebViewClient(string javascript)
{
_javascript = javascript;
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
in your Html
function readTextFile(file)
{
try
{
var blob = null;
var rawFile = new XMLHttpRequest();
rawFile.open(""GET"", file);
rawFile.responseType = ""blob"";//force the HTTP response, response-type header to be blob
rawFile.onload = function()
{
blob = rawFile.response;//xhr.response is now a blob object
wavesurfer.loadBlob(blob);
wavesurfer2.loadBlob(blob);
}
rawFile.send();
invokeCSharpAction(data); //you can pass some params if you need
}
catch(err)
{
}
}
For more detail you can refer here .
Related
Currently building out a mudblazor page with multiple expansion panels. I only want the panel to expand if the url contains the id of the panel in the hash of the url. That currently works, however when you click the panel it does this thing where it tries to expand, closes immediately, then notices the url and expands. It looks janky and laggy. Is there a way to prevent that default behavior and only expand using my code, even on click.
The expansion component
...
#inject NavigationManager NavManager
#inject IJSRuntime JsRuntime
#code
{
...
[Parameter]
public Action<string> SwitchActiveTab {get; set;}
private void InvokeSwitchActiveTab(string id) => SwitchActiveTab.Invoke(id);
private bool _isExpanded;
private bool _isDisabled;
private string href;
List<Func<Task>> AfterRenderAsyncJobs = new();
...
private async Task ScrollToNextQuestion()
{
var nextQuestion = assessment.AssessmentQuestions.FirstOrDefault( x=> x.Completed == false && x.ID > question.ID);
if(nextQuestion != null && nextQuestion.Section == question.Section )
{
var selector = $"{nextQuestion.ID}";
await JsRuntime.InvokeVoidAsync("scrollIntoView", selector, true);
}
else if(nextQuestion!= null && nextQuestion.Section != question.Section)
{
SwitchActiveTab(nextQuestion.Section);
var selector = $"{nextQuestion.ID}";
await JsRuntime.InvokeVoidAsync("scrollIntoView", selector, true);
}
}
private async Task ScrollToQuestion()
{
var selector = $"{question.ID}";
await JsRuntime.InvokeVoidAsync("scrollIntoView", selector, true);
}
protected override void OnInitialized()
{
href = $"#{question.ID}";
AfterRenderAsyncJobs.Add(SwitchTabsAndScroll);
NavManager.LocationChanged += HandleLocationChanged;
}
private async Task SwitchTabsAndScroll()
{
var uri = await JsRuntime.InvokeAsync<string>("returnHref");
if(uri.Contains('#'))
{
var q = assessment.AssessmentQuestions.FirstOrDefault(x => x.ID.ToString() == uri.Split('#')[1]);
if(q != null)
{
SwitchActiveTab(q.Section);
}
if(question.ID == q.ID)
{
_isExpanded = true;
AfterRenderAsyncJobs.Add(ScrollToQuestion);
}
}
}
private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
var uri = NavManager.Uri.ToString();
if(uri.Contains('#') && uri.Split('#')[1] != question.ID.ToString() && _isExpanded)
{
_isExpanded = false;
StateHasChanged();
}
if(uri.Contains('#') && uri.Split('#')[1] == question.ID.ToString() && !_isExpanded)
{
_isExpanded = true;
StateHasChanged();
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
while (AfterRenderAsyncJobs.Any())
{
var job = AfterRenderAsyncJobs.First();
AfterRenderAsyncJobs.Remove(job);
await job.Invoke();
}
}
public void Dispose()
{
// remove from the NavigationManager event
NavManager.LocationChanged -= HandleLocationChanged;
}
}
<MudExpansionPanel id="#question.ID" IsExpanded="#_isExpanded" HideIcon="true" >
<TitleContent>
<AnchorLink href="#href" disabled="#_isDisabled">
<MudElement Class="d-flex justify-space-between align-center" >
...
</MudElement>
</AnchorLink>
</TitleContent>
<ChildContent>
...
</ChildContent>
</MudExpansionPanel>
The anchor link component:
#using System.Collections.Generic;
#using System.Threading.Tasks;
#using Microsoft.AspNetCore.Components;
#using Microsoft.JSInterop;
#code
{
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();
[Parameter]
public RenderFragment ChildContent { get; set; } = null!;
[Inject]
protected IJSRuntime JSRuntime { get; set; } = null!;
private string targetId = string.Empty;
private bool preventDefault = true;
protected override void OnParametersSet()
{
if (Attributes.ContainsKey("href"))
{
var href = $"{Attributes["href"]}";
if (href.StartsWith("#"))
{
targetId = href[1..];
preventDefault = true;
}
}
base.OnParametersSet();
}
private async Task AnchorOnClickAsync()
{
if (!string.IsNullOrEmpty(targetId))
{
await JSRuntime.InvokeVoidAsync(
"scrollIntoView",
targetId, false
);
}
StateHasChanged();
}
}
<a #attributes="Attributes"
#onclick="AnchorOnClickAsync"
#onclick:preventDefault="#preventDefault">
#ChildContent
</a>
and the vanilla js scripts:
function scrollIntoView(elementId, fromComplete) {
debugger
let elem = document.getElementById(elementId);
if (elem ) {
elem.id = "tmp"
window.location.hash = elementId;
elem.id = elementId
if (fromComplete) {
const elementRect = elem.getBoundingClientRect();
const absoluteElementTop = elementRect.top + window.pageYOffset;
const middle = absoluteElementTop - (window.innerHeight / 2) + 150;
window.scrollTo(0, middle);
}
}
}
function returnHref(){
return window.location.href
}
In your code I would suggest to use the Disabled parameter for the expansion panel to disable the clicks. When the URL contains the data you want, you can switch the disabled to false and let the default behaviour do it's job. The check happens than before the click-event is fired.
Unless this doesn't work in your business case. Do let me know.
I'm building an app which will scrape some data from a website and shows a notification when some criteria are met.
Everything works well without problems when the app is open (because the WebView is being rendered) but when I close the app the WebView is disabled so I cannot use it to scrape data anymore.
The scraping code is inside a class called from a ForegroundService.
I've already looked on the internet but I'm unable to find a solution or a substitute to WebView, do you have any ideas?
I'm sorry if this question looks stupid to you, I've started to develop for mobile just one week ago
Below the JDMonitoring class which is called from the AlarmTask class
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace CGSJDSportsNotification {
public class JDMonitoring {
class Ticket {
string owner;
string title;
string store;
string lastUpdated;
string link;
public string ID { get; set; }
public string Owner {
get {
return owner == null ? "Nobody" : owner;
} set {
owner = value.Remove(0, value.IndexOf('(') + 1).Replace(")", "");
}
}
public string Title {
get {
return title;
} set {
if (value.StartsWith("(P"))
title = value.Remove(0, value.IndexOf(')') + 2);
}
}
public string Status { get; set; }
public string Store {
get {
return store;
} set {
store = value.Replace(#"\u003C", "").Replace(">", "");
}
}
public string LastUpdated {
get {
return lastUpdated;
} set {
string v;
int time = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(value, #"[^\d]+", ""));
// Convert to minutes
if (value.Contains("hours"))
time *= 60;
v = time.ToString();
if (value.Contains("seconds"))
v = v.Insert(v.Length, " sec. ago");
else
v = v.Insert(v.Length, " min. ago");
lastUpdated = v;
}
}
public string Link {
get {
return link;
} set {
link = "https://support.jdplc.com/" + value;
}
}
}
public JDMonitoring() {
WB.Source = JDQueueMainUrl;
WB.Navigated += new EventHandler<WebNavigatedEventArgs>(OnNavigate);
}
IForegroundService FgService { get { return DependencyService.Get<IForegroundService>(); } }
WebView WB { get; } = MainPage.UI.MonitoringWebView;
string JDQueueMainUrl { get; } = "https://support.jdplc.com/rt4/Search/Results.html?Format=%27%3Cb%3E%3Ca%20href%3D%22__WebPath__%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27%3Cb%3E%3Ca%20href%3D%22__WebPath__%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__Subject__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3ASubject%27%2C%0AStatus%2C%0AQueueName%2C%0AOwner%2C%0APriority%2C%0A%27__NEWLINE__%27%2C%0A%27__NBSP__%27%2C%0A%27%3Csmall%3E__Requestors__%3C%2Fsmall%3E%27%2C%0A%27%3Csmall%3E__CreatedRelative__%3C%2Fsmall%3E%27%2C%0A%27%3Csmall%3E__ToldRelative__%3C%2Fsmall%3E%27%2C%0A%27%3Csmall%3E__LastUpdatedRelative__%3C%2Fsmall%3E%27%2C%0A%27%3Csmall%3E__TimeLeft__%3C%2Fsmall%3E%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=LastUpdated%7C%7C%7C&Query=Queue%20%3D%20%27Service%20Desk%20-%20CGS%27%20AND%20(%20%20Status%20%3D%20%27new%27%20OR%20Status%20%3D%20%27open%27%20OR%20Status%20%3D%20%27stalled%27%20OR%20Status%20%3D%20%27deferred%27%20OR%20Status%20%3D%20%27open%20-%20awaiting%20requestor%27%20OR%20Status%20%3D%20%27open%20-%20awaiting%20third%20party%27%20)&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId=new";
bool MonitoringIsInProgress { get; set; } = false;
public bool IsConnectionAvailable {
get {
try {
using (new WebClient().OpenRead("http://google.com/generate_204"))
return true;
} catch {
return false;
}
}
}
async Task<bool> IsOnLoginPage() {
if (await WB.EvaluateJavaScriptAsync("document.getElementsByClassName('left')[0].innerText") != null)
return true;
return false;
}
async Task<bool> Login() {
await WB.EvaluateJavaScriptAsync($"document.getElementsByName('user')[0].value = '{UserSettings.SecureEntries.Get("rtUser")}'");
await WB.EvaluateJavaScriptAsync($"document.getElementsByName('pass')[0].value = '{UserSettings.SecureEntries.Get("rtPass")}'");
await WB.EvaluateJavaScriptAsync("document.getElementsByClassName('button')[0].click()");
await Task.Delay(1000);
// Checks for wrong credentials error
if (await WB.EvaluateJavaScriptAsync("document.getElementsByClassName('action-results')[0].innerText") == null)
return true;
return false;
}
async Task<List<Ticket>> GetTickets() {
List<Ticket> tkts = new List<Ticket>();
// Queue tkts index (multiple of 2)
int index = 2;
// Iterates all the queue
while (await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].innerText") != null) {
Ticket tkt = new Ticket();
tkt.LastUpdated = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index + 1}].getElementsByTagName('td')[4].innerText");
// Gets only the tkts which are not older than the value selected by the user
if (Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(tkt.LastUpdated, #"[^\d]+", "")) > Convert.ToInt32(UserSettings.Entries.Get("searchTimeframe")))
break;
tkt.ID = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].getElementsByTagName('td')[0].innerText");
tkt.Owner = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].getElementsByTagName('td')[4].innerText");
tkt.Title = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].getElementsByTagName('td')[1].innerText");
tkt.Status = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].getElementsByTagName('td')[2].innerText");
tkt.Store = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index + 1}].getElementsByTagName('td')[1].innerText");
tkt.Link = await WB.EvaluateJavaScriptAsync($"document.getElementsByClassName('ticket-list collection-as-table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[{index}].getElementsByTagName('td')[1].getElementsByTagName('a')[0].getAttribute('href')");
tkts.Add(tkt);
index += 2;
}
return tkts;
}
//async Task<string> QueueGetTkt
async void OnNavigate(object sender, WebNavigatedEventArgs args) {
if (MonitoringIsInProgress)
return;
if (IsConnectionAvailable) {
if (await IsOnLoginPage()) {
if (await Login() == false) {
// If the log-in failed we can't proceed
MonitoringIsInProgress = false;
FgService.NotificationNewTicket("Log-in failed!", "Please check your credentials");
// Used to avoid an infinite loop of OnNavigate method calls
WB.Source = "about:blank";
return;
}
}
// Main core of the monitoring
List<Ticket> tkts = await GetTickets();
if (tkts.Count > 0) {
foreach(Ticket t in tkts) {
// Looks only after the tkts with the country selected by the user (and if it was selected by the user, also for the tkts without a visible country)
// Firstly we look in the title
if (t.Title.Contains(MainPage.UI.CountryPicker.SelectedItem.ToString())) {
FgService.NotificationNewTicket($"[{t.ID}] {t.LastUpdated}",
$"{t.Title}\r\n\r\n" +
$"Status: {t.Status}\r\n" +
$"Owner: {t.Owner}\r\n" +
$"Last updated: {t.LastUpdated}");
break;
}
}
}
}
MonitoringIsInProgress = false;
}
}
}
AlarmTask class
using Android.App;
using Android.Content;
using Android.Support.V4.App;
namespace CGSJDSportsNotification.Droid {
[BroadcastReceiver(Enabled = true, Exported = true, DirectBootAware = true)]
[IntentFilter(new string[] { Intent.ActionBootCompleted, Intent.ActionLockedBootCompleted, "android.intent.action.QUICKBOOT_POWERON", "com.htc.intent.action.QUICKBOOT_POWERON" }, Priority = (int)IntentFilterPriority.HighPriority)]
public class AlarmTask : BroadcastReceiver {
IAlarm _MainActivity { get { return Xamarin.Forms.DependencyService.Get<IAlarm>(); } }
public override void OnReceive(Context context, Intent intent) {
if (intent.Action != null) {
if (intent.Action.Equals(Intent.ActionBootCompleted)) {
// Starts the app after reboot
var serviceIntent = new Intent(context, typeof(MainActivity));
serviceIntent.AddFlags(ActivityFlags.NewTask);
context.StartActivity(serviceIntent);
Intent main = new Intent(Intent.ActionMain);
main.AddCategory(Intent.CategoryHome);
context.StartActivity(main);
// Does not work, app crashes on boot received
/*if (UserSettings.Entries.Exists("monitoringIsRunning")) {
if ((bool)UserSettings.Entries.Get("monitoringIsRunning"))
FgService.Start();
}*/
}
} else
// Checks for new tkts on a new thread
new JDMonitoring();
// Restarts the alarm
_MainActivity.AlarmStart();
}
// Called from JDMonitoring class
public static void NotificationNewTicket(string title, string message, bool icoUnknownCountry = false) {
new AlarmTask().NotificationShow(title, message, icoUnknownCountry);
}
void NotificationShow(string title, string message, bool icoUnknownCountry) {
int countryFlag = Resource.Drawable.newTktUnknownCountry;
if (icoUnknownCountry == false) {
switch (MainPage.UI.CountryPicker.SelectedItem.ToString()) {
case "Italy":
countryFlag = Resource.Drawable.newTktItaly;
break;
case "Spain":
countryFlag = Resource.Drawable.newTktSpain;
break;
case "Germany":
countryFlag = Resource.Drawable.newTktGermany;
break;
case "Portugal":
countryFlag = Resource.Drawable.newTktPortugal;
break;
}
}
var _intent = new Intent(Application.Context, typeof(MainActivity));
_intent.AddFlags(ActivityFlags.ClearTop);
_intent.PutExtra("jdqueue_notification", "extra");
var pendingIntent = PendingIntent.GetActivity(Application.Context, 0, _intent, PendingIntentFlags.OneShot);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Application.Context, "newTktNotification_channel")
.SetVisibility((int)NotificationVisibility.Public)
.SetPriority((int)NotificationPriority.High)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate | (int)NotificationDefaults.Lights)
.SetSmallIcon(Resource.Drawable.newTktNotification)
.SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Application.Context.Resources, countryFlag))
.SetSubText("Click to check the queue")
.SetStyle(new NotificationCompat.BigTextStyle()
.SetBigContentTitle("New ticket available!")
.BigText(message))
.SetContentText(title)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
NotificationManagerCompat.From(Application.Context).Notify(0, notificationBuilder.Build());
}
}
}
And the ForegroundService class which is responsible to trigger for the first time the alarm
using Android.App;
using Android.Content;
using Android.OS;
namespace CGSJDSportsNotification.Droid {
[Service]
class ForegroundService : Service {
IAlarm _MainActivity { get { return Xamarin.Forms.DependencyService.Get<IAlarm>(); } }
public override IBinder OnBind(Intent intent) { return null; }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) {
// Starts the Foreground Service and the notification channel
StartForeground(9869, new ForegroundServiceNotification().ReturnNotif());
Android.Widget.Toast.MakeText(Application.Context, "JD Queue - Monitoring started!", Android.Widget.ToastLength.Long).Show();
_MainActivity.AlarmStart();
return StartCommandResult.Sticky;
}
public override void OnDestroy() {
Android.Widget.Toast.MakeText(Application.Context, "JD Queue - Monitoring stopped!", Android.Widget.ToastLength.Long).Show();
_MainActivity.AlarmStop();
UserSettings.Entries.AddOrEdit("monitoringIsRunning", false);
UserSettings.Entries.AddOrEdit("monitoringStopPending", false, false);
base.OnDestroy();
}
public override bool StopService(Intent name) {
return base.StopService(name);
}
}
}
Thank you!
[BETTER-FINAL-SOLUTION]
After several hours I've discovered Android WebView which does exactly what I need (I'm developing this app only for Android)
I've written this Browser helper class
class Browser {
public Android.Webkit.WebView WB;
static string JSResult;
public class CustomWebViewClient : WebViewClient {
public event EventHandler<bool> OnPageLoaded;
public override void OnPageFinished(Android.Webkit.WebView view, string url) {
OnPageLoaded?.Invoke(this, true);
}
}
public Browser(CustomWebViewClient wc, string url = "") {
WB = new Android.Webkit.WebView(Android.App.Application.Context);
WB.Settings.JavaScriptEnabled = true;
WB.SetWebViewClient(wc);
WB.LoadUrl(url);
}
public string EvalJS(string js) {
JSInterface jsi = new JSInterface();
WB.EvaluateJavascript($"javascript:(function() {{ return {js}; }})()", jsi);
return JSResult;
}
class JSInterface : Java.Lang.Object, IValueCallback {
public void OnReceiveValue(Java.Lang.Object value) {
JSResult = value.ToString();
}
}
}
[EDIT]
Improved the JS returning function with async callbacks (so the JS return value will be always delivered).
Credits to ChristineZuckerman
class Browser {
public Android.Webkit.WebView WB;
public class CustomWebViewClient : WebViewClient {
public event EventHandler<bool> OnPageLoaded;
public override void OnPageFinished(Android.Webkit.WebView view, string url) {
OnPageLoaded?.Invoke(this, true);
}
}
public Browser(CustomWebViewClient wc, string url = "") {
WB = new Android.Webkit.WebView(Android.App.Application.Context);
WB.ClearCache(true);
WB.Settings.JavaScriptEnabled = true;
WB.Settings.CacheMode = CacheModes.NoCache;
WB.Settings.DomStorageEnabled = true;
WB.Settings.SetAppCacheEnabled(false);
WB.Settings.UserAgentString = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
WB.LoadUrl(url);
WB.SetWebViewClient(wc);
}
public async Task<string> EvalJS(string js, bool returnNullObjectWhenNull = true) {
string JSResult = "";
ManualResetEvent reset = new ManualResetEvent(false);
Device.BeginInvokeOnMainThread(() => {
WB?.EvaluateJavascript($"javascript:(function() {{ return {js}; }})()", new JSInterface((r) => {
JSResult = r;
reset.Set();
}));
});
await Task.Run(() => { reset.WaitOne(); });
return JSResult == "null" ? returnNullObjectWhenNull ? null : "null" : JSResult;
}
class JSInterface : Java.Lang.Object, IValueCallback {
private Action<string> _callback;
public JSInterface(Action<string> callback) {
_callback = callback;
}
public void OnReceiveValue(Java.Lang.Object value) {
string v = value.ToString();
if (v.StartsWith('"') && v.EndsWith('"'))
v = v.Remove(0, 1).Remove(v.Length - 2, 1);
_callback?.Invoke(v);
}
}
}
Example:
Browser.CustomWebViewClient wc = new Browser.CustomWebViewClient();
wc.OnPageLoaded += BrowserOnPageLoad;
Browser browser = new Browser(wc, "https://www.google.com/");
void BrowserOnPageLoad(object sender, bool e) {
string test = browser.EvalJS("document.getElementsByClassName('Q8LRLc')[0].innerText");
// 'test' will contain the value returned from the JS script
// You can acces the real WebView object by using
// browser.WB
}
// OR WITH THE NEW RETURNING FUNCTION
async void BrowserOnPageLoad(object sender, bool e) {
string test = await browser.EvalJS("document.getElementsByClassName('Q8LRLc')[0].innerText");
// 'test' will contain the value returned from the JS script
// You can acces the real WebView object by using
// browser.WB
}
[FINAL-SOLUTION]
Finally I've found an easy and efficient alternative to WebView.
Now I'm using SimpleBroswer and works great!
[SEMI-SOLUTION]
Alright, I've written a workaround but I don't really like this idea, so please, if you know a better method let me know.
Below my workaround:
In my ForegroundServiceHelper interface I've added a method to check if the MainActivity (where the WebView it's rendered) is visible or not, if isn't visible the MainActivity will be shown and immediately will be hidden back.
And the app will be removed from the last used applications
Method inside my ForegroundServiceHelper Interface
public void InitBackgroundWebView() {
if ((bool)SharedSettings.Entries.Get("MainPage.IsVisible") == false) {
// Shows the activity
Intent serviceIntent = new Intent(context, typeof(MainActivity));
serviceIntent.AddFlags(ActivityFlags.NewTask);
context.StartActivity(serviceIntent);
// And immediately hides it back
Intent main = new Intent(Intent.ActionMain);
main.AddFlags(ActivityFlags.NewTask);
main.AddCategory(Intent.CategoryHome);
context.StartActivity(main);
// Removes from the last app used
ActivityManager am = (new ContextWrapper(Android.App.Application.Context)).GetSystemService(Context.ActivityService).JavaCast<ActivityManager>();
if (am != null) {
System.Collections.Generic.IList<ActivityManager.AppTask> tasks = am.AppTasks;
if (tasks != null && tasks.Count > 0) {
tasks[0].SetExcludeFromRecents(true);
}
}
}
}
The SharedSettings class is an helper class wrapped around the App.Current.Properties Dictionary
And in the OnAppearing and OnDisappearing callbacks I set the shared values to true/false
[EDIT]
This workaround works only if the user is on the homepage, so I need to find an another solution...
I have a webview in a Shell Xamarin.Forms app. I request a secure page and get forwarded to my company SSO (Single Sign On), I pass that and can see the secure content.
The webview:
<WebView x:Name="web1" HorizontalOptions="CenterAndExpand"
VerticalOptions="FillAndExpand" HeightRequest="1000" WidthRequest="1000"/>
When I then navigate to a new Shell page from the main menu or by tapping an item in a listview (think RSS Headline list, tap to read article) which has an almost identical WebView tag on the xaml page, set the Source to a secure page on the page constructor or override OnAppearing, expecting the session/cookie to still be active I instead get forwarded to a login page again.
Is there any way that anyone knows I can ensure that all webviews in my app (iOS & Android) use the same session so the user only has to login once.
I've tried creating a the webview in the app.xaml.cs file and adding it to my pages using Content.Children.Add(App.Web1) which in my simple mind should mean I'm using the same webview on all pages and therefore the same session!? but that doesn't seem to work either.
Any and all help is greatly appreciated.
Thank you.
Using cookieJs along with normal cookie insertion methods can solve the problem of setting cookies on the front-end side:
CookieJs:
!function(e){var n;if("function"==typeof define&&define.amd&&(define(e),n=!0),"object"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if("undefined"!=typeof document){"number"==typeof(i=e({path:"/"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():"";try{var c=JSON.stringify(t);/^[{[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var f="";for(var u in i)i[u]&&(f+="; "+u,!0!==i[u]&&(f+="="+i[u].split(";")[0]));return document.cookie=n+"="+t+f}}function c(e,t){if("undefined"!=typeof document){for(var r={},i=document.cookie?document.cookie.split("; "):[],c=0;c<i.length;c++){var f=i[c].split("="),u=f.slice(1).join("=");t||'"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,"",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});
Sample:
iOS Renderer:
public class DefaultWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>, IWKScriptMessageHandler, IWKNavigationDelegate
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
const string cookieJs = "!function(e){var n;if(\"function\"==typeof define&&define.amd&&(define(e),n=!0),\"object\"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if(\"undefined\"!=typeof document){\"number\"==typeof(i=e({path:\"/\"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():\"\";try{var c=JSON.stringify(t);/^[\\{\\[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\\(\\)]/g,escape);var f=\"\";for(var u in i)i[u]&&(f+=\"; \"+u,!0!==i[u]&&(f+=\"=\"+i[u].split(\";\")[0]));return document.cookie=n+\"=\"+t+f}}function c(e,t){if(\"undefined\"!=typeof document){for(var r={},i=document.cookie?document.cookie.split(\"; \"):[],c=0;c<i.length;c++){var f=i[c].split(\"=\"),u=f.slice(1).join(\"=\");t||'\"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,\"\",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});";
WKUserContentController userController;
public DefaultWebViewRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (Control == null && e.OldElement == null)
{
userController = new WKUserContentController();
var cookieValue = string.Empty; //Whatever you want
var jsScript = new WKUserScript(new NSString(cookieJs), WKUserScriptInjectionTime.AtDocumentStart, false);
var yourCookie = new WKUserScript(new NSString("Cookies.set('CookieKey','" + cookieValue + "',{expires : 30, domain : '.yourdomain.com' })"), WKUserScriptInjectionTime.AtDocumentStart, false);
userController.AddUserScript(jsScript);
userController.AddUserScript(yourCookie);
var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript(script);
userController.AddScriptMessageHandler(this, "invokeAction");
var config = new WKWebViewConfiguration { UserContentController = userController };
var webView = new WKWebView(Frame, config);
SetNativeControl(webView);
}
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
}
if (e.NewElement != null)
{
if (Element.Source is UrlWebViewSource urlSource)
{
var url = new NSUrl(urlSource.Url);
var storage = NSHttpCookieStorage.SharedStorage;
storage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
var request = new NSMutableUrlRequest(url);
Control.LoadRequest(request);
}
else if (Element.Source is HtmlWebViewSource htmlSource)
{
Control.LoadHtmlString(htmlSource.Html, null);
}
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
Element.JavascriptBridgeInvoked(message.Body.ToString());
}
}
Android Renderer:
public class DefaultWebViewRenderer : WebViewRenderer
{
const string JavaScriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
public DefaultWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null && e.NewElement is CustomWebView webView)
{
Control.SetWebViewClient(new WebViewTestClient());
Control.ClearSslPreferences();
Control.Settings.SetAppCacheEnabled(false);
Control.Settings.DatabaseEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.AllowFileAccessFromFileURLs = true;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.Settings.CacheMode = Android.Webkit.CacheModes.NoCache;
Control.Settings.AllowContentAccess = true;
Control.Settings.AllowFileAccess = true;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.JavaScriptCanOpenWindowsAutomatically = true;
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.SetAcceptThirdPartyCookies(Control, true);
try
{
Control.SetDownloadListener(new DownloadListener());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
}
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
InjectJS(JavaScriptFunction);
if (webView.Source is UrlWebViewSource webSource)
{
Control.LoadUrl(webSource.Url);
}
}
}
private void InjectJS(string script)
{
if (Control != null)
{
Control.LoadUrl(string.Format("javascript: {0}", script));
}
}
}
public class WebViewTestClient : WebViewClient
{
public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)
{
var cookieJs = "!function(e){var n;if(\"function\"==typeof define&&define.amd&&(define(e),n=!0),\"object\"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if(\"undefined\"!=typeof document){\"number\"==typeof(i=e({path:\"/\"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():\"\";try{var c=JSON.stringify(t);/^[\\{\\[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\\(\\)]/g,escape);var f=\"\";for(var u in i)i[u]&&(f+=\"; \"+u,!0!==i[u]&&(f+=\"=\"+i[u].split(\";\")[0]));return document.cookie=n+\"=\"+t+f}}function c(e,t){if(\"undefined\"!=typeof document){for(var r={},i=document.cookie?document.cookie.split(\"; \"):[],c=0;c<i.length;c++){var f=i[c].split(\"=\"),u=f.slice(1).join(\"=\");t||'\"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,\"\",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});";
var cookieValue = string.Empty; //Whatever you want
view.EvaluateJavascript(cookieJs, null);
view.EvaluateJavascript("Cookies.set('CookieKey','" + cookieValue + "',{expires : 30, domain : '.yourdomain.com' })", null);
base.OnPageStarted(view, url, favicon);
view.ClearCache(true);
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.ClearCache(true);
}
public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
{
handler.Proceed();
base.OnReceivedSslError(view, handler, error);
}
}
public class DownloadListener : Java.Lang.Object, Android.Webkit.IDownloadListener
{
public DownloadListener()
{
}
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out _))
return;
try
{
if (HasPermissions())
{
Android.Net.Uri contentUri = Android.Net.Uri.Parse(url);
DownloadManager.Request request = new DownloadManager.Request(contentUri);
request.SetMimeType(mimetype);
var cookies = Android.Webkit.CookieManager.Instance.GetCookie(url);
request.AddRequestHeader("cookie", cookies);
request.AddRequestHeader("User-Agent", userAgent);
request.SetDescription("Downloading file...");
request.SetTitle(Android.Webkit.URLUtil.GuessFileName(url, contentDisposition, mimetype));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted);
request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, ".pdf");
Android.App.DownloadManager dm = (Android.App.DownloadManager)CrossCurrentActivity.Current.Activity.GetSystemService(Android.Content.Context.DownloadService);
dm.Enqueue(request);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static bool HasPermissions()
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
string[] WriteLocation =
{
Android.Manifest.Permission.WriteExternalStorage,
Android.Manifest.Permission.ReadExternalStorage
};
var perm = CrossCurrentActivity.Current.AppContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage);
if (perm != (int)Android.Content.PM.Permission.Granted)
{
CrossCurrentActivity.Current.Activity.RequestPermissions(WriteLocation, 2);
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
public class JSBridge : Java.Lang.Object
{
private readonly WeakReference<DefaultWebViewRenderer> hybridWebViewRenderer;
public JSBridge(DefaultWebViewRenderer hybridRenderer)
{
hybridWebViewRenderer = new WeakReference<DefaultWebViewRenderer>(hybridRenderer);
}
[JavascriptInterface]
[Export("invokeAction")]
public void InvokeAction(string data)
{
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out DefaultWebViewRenderer hybridRenderer) && hybridRenderer != null && hybridRenderer.Element is CustomWebView webView)
{
webView.JavascriptBridgeInvoked(data);
}
}
}
I am developing my first WPF browser application.
I load invoices in a dataGrid then I filter with textBox or comboBox.
Because it takes few seconds to load, I'am trying to put a loading animation according the following example:
here
I want to filter my dataGrid depending on two comboBox.
But I have this error
This type of CollectionView does not support changes to its
SourceCollection from a thread different from the Dispatcher thread
at the line invoiceCollection.Clear();
and invoiceCollection.Add(inv); in SearchFilter();
I tried
App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE
{
//code here
});
but I still have the same error.
ViewModel
public class ConsultInvoiceViewModel : ViewModelBase
{
public Context ctx = new Context();
private ICollectionView _dataGridCollection;
private ObservableCollection<Invoice> invoiceCollection;
public ConsultInvoiceViewModel()
{
if (!WPFHelper.IsInDesignMode)
{
var tsk = Task.Factory.StartNew(InitialStart);
tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
}
private void InitialStart()
{
try
{
State = StateEnum.Busy;
DataGridCollection = CollectionViewSource.GetDefaultView(Get());
DataGridCollection.Filter = new Predicate<object>(Filter);
}
finally
{
State = StateEnum.Idle;
}
}
private void SearchFilter()
{
Task tsk = Task.Factory.StartNew(()=>
{
try
{
State = StateEnum.Busy;
using (var ctx = new Context())
{
var invs = ctx.Invoices
.Where(s.supplier == 1)
.GroupBy(x => new { x.suppInvNumber, x.foodSupplier })
.ToList()
.Select(i => new Invoice
{
suppInvNumber = i.Key.suppInvNumber,
foodSupplier = i.Key.foodSupplier,
totalPrice = i.Sum(t => t.totalPrice),
});
.
App.Current.Dispatcher.Invoke((Action)delegate
{
invoiceCollection.Clear();
});
if (invs != null)
foreach (var inv in invs)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
invoiceCollection.Add(inv);
});
}
}
}
finally
{
State = StateEnum.Idle;
}
});
tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
public static readonly PropertyChangedEventArgs StateArgs = ViewModelBase.CreateArgs<ConsultInvoiceViewModel>(c => c.State);
private StateEnum _State;
public StateEnum State
{
get
{
return _State;
}
set
{
var oldValue = State;
_State = value;
if (oldValue != value)
{
OnStateChanged(oldValue, value);
OnPropertyChanged(StateArgs);
}
}
}
protected virtual void OnStateChanged(StateEnum oldValue, StateEnum newValue)
{
}
}
ViewModelBase
public abstract class ViewModelBase : INotifyPropertyChanged
{
#region "INotifyPropertyChanged members"
public event PropertyChangedEventHandler PropertyChanged;
//This routine is called each time a property value has been set.
//This will //cause an event to notify WPF via data-binding that a change has occurred.
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
public void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
PropertyChanged(this, args);
}
public static PropertyChangedEventArgs CreateArgs<T>(Expression<Func<T, Object>> propertyExpression)
{
return new PropertyChangedEventArgs(GetNameFromLambda(propertyExpression));
}
private static string GetNameFromLambda<T>(Expression<Func<T, object>> propertyExpression)
{
var expr = propertyExpression as LambdaExpression;
MemberExpression member = expr.Body is UnaryExpression ? ((UnaryExpression)expr.Body).Operand as MemberExpression : expr.Body as MemberExpression;
var propertyInfo = member.Member as PropertyInfo;
return propertyInfo.Name;
}
}
There is a really nice way to solve this in .Net 4.5 and greater:
private object _lock = new object();
BindingOperations.EnableCollectionSynchronization("YourCollection", _lock);
So you don't need to use the Dispatcher everytime you want to manipulate your collection.
Here are some resources for further information:
http://10rem.net/blog/2012/01/20/wpf-45-cross-thread-collection-synchronization-redux
BindingOperations.EnableCollectionSynchronization mystery in WPF
https://msdn.microsoft.com/en-us/library/hh198845%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Maybe try another example:
Xaml:
<Grid>
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding .}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Code:
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Data();
}
}
public class Data
{
public ObservableCollection<int> Items { get; set; }
public Data()
{
Items = new ObservableCollection<int>();
Filters();
}
public void Filters()
{
Task.Factory.StartNew(DoWork);
}
public void DoWork()
{
int i = 0;
while (true)
{
System.Threading.Thread.Sleep(1000);
App.Current.Dispatcher.BeginInvoke(new Action(() => { Items.Add(++i); }));
}
}
}
}
I finally what it was working. It was pretty simple.
public class ConsultInvoiceViewModel : ViewModelBase
{
public Context ctx = new Context();
private ICollectionView _dataGridCollection;
private ObservableCollection<Invoice> invoiceCollection;
public ConsultInvoiceViewModel()
{
invoiceCollection = new ObservableCollection<Invoice>();
DataGridCollection = CollectionViewSource.GetDefaultView(Get());
if (!WPFHelper.IsInDesignMode)
{
var tsk = Task.Factory.StartNew(InitialStart);
tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
}
private void InitialStart()
{
try
{
State = StateEnum.Busy;
Get();
}
finally
{
State = StateEnum.Idle;
}
}
private void SearchFilter()
{
Task tsk = Task.Factory.StartNew(()=>
{
try
{
State = StateEnum.Busy;
using (var ctx = new Context())
{
var invs = ctx.Invoices
.Where(s.supplier == 1)
.GroupBy(x => new { x.suppInvNumber, x.foodSupplier })
.ToList()
.Select(i => new Invoice
{
suppInvNumber = i.Key.suppInvNumber,
foodSupplier = i.Key.foodSupplier,
totalPrice = i.Sum(t => t.totalPrice),
});
.
App.Current.Dispatcher.Invoke((Action)delegate
{
invoiceCollection.Clear();
if (invs != null)
foreach (var inv in invs)
{
invoiceCollection.Add(inv);
}
});
}
}
finally
{
State = StateEnum.Idle;
}
});
tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
private ObservableCollection<Invoice> Get()
{
using (var ctx = new Context())
{
var invs = ctx.Invoices
foreach (var inv in invs)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
invoiceCollection.Add(inv);
});
}
}
I have a Datasnap Server and i need consuming the data with a windows phone.
The TSituacaoProxy class, when i sends a parameter (Id), the return must be a JSON object.
But the error is shown:
Object reference not set to an instance of an object.
My Code:
private void clique(object sender, RoutedEventArgs e)
{
DSRESTConnection connection = new DSRESTConnection();
connection.setHost("10.0.0.10");
connection.setPort(8080);
connection.setProtocol("http");
connection.setUserName("master");
connection.setPassword("C28861C83BD5397187FD55D04C2547F9");
connection.setContext("datasnap/REST");
DSProxy.TSituacaoProxy Proxy = new DSProxy.TSituacaoProxy(connection, ExceptionCallback);
TJSONObject jObject = TJSONObject.Parse("22");
Proxy.Loader(jObject, (TJSONObject Result) =>
{
MessageBox.Show(Result.ToString());
}, ExceptionCallback);
}
public void ExceptionCallback(Exception e)
{
MessageBox.Show(e.Message);
}
TSituacaoProxy class:
public class TSituacaoProxy : DSAdmin
{
public TSituacaoProxy(DSRESTConnection Connection, ExceptionCallback ExCal)
: base(Connection, ExCal)
{
}
private DSRESTParameterMetaData[] TSituacaoProxy_teste_Metadata;
private DSRESTParameterMetaData[] get_TSituacaoProxy_teste_Metadata()
{
if (TSituacaoProxy_teste_Metadata == null)
{
TSituacaoProxy_teste_Metadata = new DSRESTParameterMetaData[]
{
new DSRESTParameterMetaData("xValue", DSRESTParamDirection.Input, DBXDataTypes.WideStringType, "string"),
new DSRESTParameterMetaData("", DSRESTParamDirection.ReturnValue, DBXDataTypes.WideStringType, "string"),
};
}
return TSituacaoProxy_teste_Metadata;
}
The Loader method:
public delegate void LoaderCallback(TJSONObject Result);
public void Loader(TJSONObject xId, LoaderCallback callback = null, ExceptionCallback ExCal = null)
{
DSRESTCommand cmd = getConnection().CreateCommand();
cmd.setRequestType(DSHTTPRequestType.POST);
cmd.setText("TSituacaoProxy.Loader");
cmd.prepare(get_TSituacaoProxy_Loader_Metadata());
InternalConnectionDelegate LoaderDel = () =>
{
if (callback != null)
{
try
{
callback.DynamicInvoke((TJSONObject)cmd.getParameter(1).getValue().GetAsJSONValue());
}
catch (Exception ex)
{
if (ExCal != null) getConnection().syncContext.Send(new SendOrPostCallback(x => ExCal.DynamicInvoke(ex.InnerException)), null);
else getConnection().syncContext.Send(new SendOrPostCallback(x => BaseExCal.DynamicInvoke(ex.InnerException)), null);
}
}
};
cmd.getParameter(0).getValue().SetAsJSONValue(xId);
getConnection().execute(cmd, this, LoaderDel, ExCal);
}
private DSRESTParameterMetaData[] TSituacaoProxy_Select_Metadata;
private DSRESTParameterMetaData[] get_TSituacaoProxy_Select_Metadata()
{
if (TSituacaoProxy_Select_Metadata == null)
{
TSituacaoProxy_Select_Metadata = new DSRESTParameterMetaData[]
{
new DSRESTParameterMetaData("xAssorts", DSRESTParamDirection.Input, DBXDataTypes.JsonValueType, "TJSONArray"),
new DSRESTParameterMetaData("", DSRESTParamDirection.ReturnValue, DBXDataTypes.JsonValueType, "TJSONArray"),
};
}
return TSituacaoProxy_Select_Metadata;
}
change code in dsrestconnection.cs
this
HttpWebRequest Client = (HttpWebRequest)WebRequest.Create(URL + "?" + DateTime.Now.Ticks.ToString());
to this
HttpWebRequest Client =(HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(URL + "?" + DateTime.Now.Ticks.ToString()));