Using CefBrowser.ExecuteScriptAsync with BindObjectAsync Not Working - cefsharp

I am using the below code to try to bind a c# class that has been registered but do not see "dwgData" anywhere under Scope when debugging the webpage. What would dwgData be bound to?
private void ChromiumBrowserForm_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
ChromiumWebBrowser browser = new ChromiumWebBrowser("http://localhost:3000");
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.JavascriptObjectRepository.Register("dwgData", new DwgData(), true, null);
browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
browser.LoadingStateChanged += Browser_LoadingStateChanged;
}
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (e.IsLoading == false)
{
await Task.Run(() => browser.ExecuteScriptAsync("CefSharp.BindObjectAsync(\"dwgData\");"));
}
}
private void Browser_IsBrowserInitializedChanged(object sender, EventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (browser.IsBrowserInitialized)
{
browser.ShowDevTools();
}
}
public class DwgData
{
public void showMessage()
{
MessageBox.Show("HELLO FROM JS");
}
}

Related

how to stop my FileSystemWatcher in start/stop button

I have a FileSystemWatchers monitoring 1 location in a Start/stop Button, but I can´t manage to stop it, the button works pretty much well as when I click on it, it reads the code when it is off (the text changes to "start Watching") but it does not manage to stop monitoring, also I have tried "watcher.EnableRaisingEvents = false;" but it does not work could you please help me??
using System
using System.ComponentModel
using System.Diagnostics
using System.Drawing
using System.IO
using System.Windows.Forms
namespace Watcher
{
public partial class Form1 : Form
{
private bool isWatching
bool on = true
bool togglelight = true
Timer t = new Timer()
public Form1()
{
InitializeComponent()
}
private void button1_Click(object sender, EventArgs e)
{
if (isWatching)
{
stopWatching()
}
else
{
startWatching()
}
}
private void startWatching()
{
isWatching = true
button1.Text = "Stop Watching"
t.Start()
on = false;
var watcher = new FileSystemWatcher(#"C:\location1")
watcher.NotifyFilter = NotifyFilters.CreationTime
| NotifyFilters.CreationTime
| NotifyFilters.FileName
watcher.Changed += OnChanged
watcher.Error += OnError
watcher.Filter = "*.xlsx"
watcher.IncludeSubdirectories = false
watcher.EnableRaisingEvents = true
private void stopWatching()
{
isWatching = false;
button1.Text = "Start Watching"
button1.BackColor = Color.Gray
t.Enabled = false
t.Stop()
on = true
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return
}
Console.WriteLine(DateTime.Now + " tipo de cambio: " +
e.ChangeType + ". " + e.FullPath)
kNime_Bat(#" C:\Users\BAT\Knime_eSTORE.bat")
Console.WriteLine(DateTime.Now + " se proceso correctamente")
}
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException())
private static void PrintException(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}")
Console.WriteLine("Stacktrace:")
Console.WriteLine(ex.StackTrace)
Console.WriteLine()
PrintException(ex.InnerException)
}
}
private static void kNime_Bat(string ruta_del_archivoBat_knime)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo()
psi.UseShellExecute = false
psi.CreateNoWindow = true
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = ruta_del_archivoBat_knime
Process.Start(psi)
}
catch (Win32Exception)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Start Watching"
t.Interval = 1000
t.Tick += new EventHandler(t_Tick)
}
private void t_Tick(object sender, EventArgs e)
{
if (togglelight)
{
button1.BackColor = Color.DarkBlue
togglelight = false
}
else
{
button1.BackColor = Color.Gray
togglelight = true
}
}
}
}
I have tried watcher.EnableRaisingEvents = false in Stopwatching event but it seems like if it works in a new instance as it does not stop the watcher, how I know? because after I click on "stop" I make a new change in the watched folder and I get an answer in OnChanged event.

Xamarin.Forms Slider.Clicked event?

I'm making an mp3 player in Xamarin.Forms, in which the slider should both show time expired and allow jumping to locations in the track.
As far as I can tell, only the ValueChanged event is available, with the unfortunate sideeffect that every time my timer updates the slider value, I also trigger my player.SeekTo method, causing broken playback.
Is there any way to specifically pick up touch events on a slider?
If not, does anyone have any suggestions on how to make this work?
In case it's relevant, here's my code for the MainPage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MuZor
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
PlayButton.Clicked += PlayButton_Clicked;
PlaylistsButton.Clicked += PlaylistsButton_Clicked;
RandomButton.Clicked += RandomButton_Clicked;
RepeatButton.Clicked += RepeatButton_Clicked;
ChoiceButton.Clicked += ChoiceButton_Clicked;
PreviousButton.Clicked += PreviousButton_Clicked;
NextButton.Clicked += NextButton_Clicked;
TimeSlider.ValueChanged += TimeSlider_ValueChanged;
MessagingCenter.Subscribe<Interfaces.IAudioPlayer>(App.player, "PlayerPrepared", (args) =>
{
System.Diagnostics.Debug.WriteLine("Message received");
PlayerPrepared();
});
}
private void TimeSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Slider value changed, value = " + e.NewValue + "(int = " + (int)e.NewValue);
//App.player.SeekTo((int)e.NewValue);
}
private void NextButton_Clicked(object sender, EventArgs e)
{
if (!App.settings.RandomOn && App.settings.CurrentTrack < App.playlist.Count - 1)
{
Play((int)App.settings.CurrentTrack + 1);
}
}
private void PreviousButton_Clicked(object sender, EventArgs e)
{
if (!App.settings.RandomOn && App.settings.CurrentTrack > 0)
{
Play((int)App.settings.CurrentTrack - 1);
}
}
private void ChoiceButton_Clicked(object sender, EventArgs e)
{
}
private void RepeatButton_Clicked(object sender, EventArgs e)
{
}
private void RandomButton_Clicked(object sender, EventArgs e)
{
}
private void PlaylistsButton_Clicked(object sender, EventArgs e)
{
}
private void PlayButton_Clicked(object sender, EventArgs e)
{
if (App.settings.IsPaused || App.player.IsPlaying())
{
App.player.PauseResume();
if (App.settings.IsPaused)
{
UnPause();
}
else
{
Pause();
}
}
else
{
int trackToplay = App.settings.CurrentTrack != null ? (int)App.settings.CurrentTrack : 0;
Play(trackToplay);
}
}
private void Play(int currentTrack)
{
HelperClasses.SettingsHelper.SaveCurrentTrack(currentTrack);
App.player.LoadAndPlay(App.playlist[currentTrack].Path);
}
private void Pause()
{
HelperClasses.SettingsHelper.SavePausedState(true);
Device.BeginInvokeOnMainThread(() =>
{
PlayButton.Text = "Play";
});
}
private void UnPause()
{
HelperClasses.SettingsHelper.SavePausedState(false);
Device.BeginInvokeOnMainThread(() =>
{
PlayButton.Text = "Pause";
});
StartTimer();
}
private void StartTimer()
{
double position;
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
position = App.player.GetCurrentPosition();
TimeSpan runTime = TimeSpan.FromMilliseconds(position);
Device.BeginInvokeOnMainThread(() =>
{
TimeLabel.Text = runTime.ToString(#"mm\:ss");
TimeSlider.Value = position;
});
if (App.player.IsPlaying())
return true;
else
return false;
});
}
private void PlayerPrepared()
{
var totalDurationInMS = App.player.GetDuration();
TimeSlider.Maximum = totalDurationInMS;
TimeSlider.Minimum = 0;
TimeSpan totalDuration = TimeSpan.FromMilliseconds(totalDurationInMS);
Device.BeginInvokeOnMainThread(() =>
{
RemainingTimeLabel.Text = totalDuration.ToString(#"mm\:ss");
TimeLabel.Text = "00:00";
});
UnPause();
}
}
}
I think I've found a workaround. Since the valuechanged event contains both old and new values, I'll only fire SeekTo if the difference is negative or bigger than 2.

Listview change applies after 2nd postback?

i have a listview and a button out of this list view, on button click i want to add a "insert" row defined in InsertItemTemplate. The problem is when i click the button, this row is added(i know this because when a do any postback aftewards this row really shows), but isnt shown/rendered. So the question is: why this change doesn´t apply on the first postback - button click? here is my code:
EDIT:
Whole Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem ByName = new ListItem("By name", "Name");
ListItem ByPhone = new ListItem("By phone", "Phone");
ListItem ByEmail = new ListItem("By email", "Email");
FilterTypeDDL.Items.Add(ByName);
FilterTypeDDL.Items.Add(ByPhone);
FilterTypeDDL.Items.Add(ByEmail);
FilterTypeDDL.DataBind();
}
}
//protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
//{
//switch (e.CommandName)
//{
//case "EditItem":
// break;
//case "InsertItem":
// if (Page.IsValid)
// {
// string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
// string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
// string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
// DAORestaurant.InsertRestaurant(NameTxt, PhoneTxt, EmailTxt);
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
// }
// break;
//case "CancelCreation":
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
//case "Articles":
// Session["Restaurant"] = e.CommandArgument.ToString();
// Control ArticlesCtrl = LoadControl("~/Controls/Article.ascx");
// ListViewItem Item = (ListViewItem)e.Item;
// Item.FindControl("CtrlPlaceHolder").Controls.Add(ArticlesCtrl);
//}
//}
protected void closeButton_Click(object sender, EventArgs e)
{
}
protected void newArticleButton_Click(object sender, EventArgs e)
{
}
protected void NewRestaurantBtn_Click(object sender, EventArgs e)
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
//SetDataSource();
//ListView.DataBind();
}
protected void ValidateName(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = (NameTxt.Length > 2 && NameTxt.Length < 51);
}
protected void ValidateUniqueness(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = DAORestaurant.IsUnique(NameTxt);
}
protected void ValidatePhone(object source, ServerValidateEventArgs args)
{
string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
Regex regex = new Regex(#"^\d{3}\s\d{3}\s\d{3}$");
args.IsValid = regex.IsMatch(PhoneTxt);
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
args.IsValid = regex.IsMatch(EmailTxt);
}
protected void ShowAllBtn_Click(object sender, EventArgs e)
{
Session["ALL"] = true;
ListView.DataSource = DAORestaurant.GetRestaurants();
ListView.DataBind();
}
protected void FilterBtn_Click(object sender, EventArgs e)
{
string filterType = FilterTypeDDL.SelectedValue;
string substring = StringTB.Text.Trim().ToUpper();
Session["ALL"] = false;
Session["FilterType"] = filterType;
Session["Substring"] = substring;
ListView.DataSource = DAORestaurant.GetRestaurants(substring, filterType);
ListView.DataBind();
}
protected void ListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView.EditIndex = e.NewEditIndex;
//SetDataSource();
//ListView.DataBind();
}
protected void ListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
ListView.InsertItemPosition = InsertItemPosition.None;
}
else
{
ListView.EditIndex = -1;
}
//SetDataSource();
//ListView.DataBind();
}
private void SetDataSource()
{
if ((bool)Session["ALL"])
{
ListView.DataSource = DAORestaurant.GetRestaurants();
}
else
{
ListView.DataSource = DAORestaurant.GetRestaurants((string)Session["Substring"], (string)Session["FilterType"]);
}
}
The code commented out is what i used before, i´ve switched to what you can see now, but the problem still persists. Only when i uncomment those 2 commented lines in each event, the changes apply instantly, but i know i cannot use such a method that many times, and it should not even be there.
Because of the order of execution. Try setting it in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack &&
!string.IsNullOrEmpty(Request.Form[NewRestaurantBtn.ClientID]))
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
}
}

User Control events

I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}
you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}

Asp.net long running process using asynch page

I have a report that takes about 2 or 3 minutes to pull all the data
So I am trying to use ASP.net Asynch pages to prevent a timeout. But can't get it to work
Here's what I am doing :
private delegate List<PublishedPagesDataItem> AsyncReportDataDelegate();
private AsyncReportDataDelegate longRunningMethod;
private List<PublishedPagesDataItem> reportData;
public PublishedPagesReport() // this is the constructor
{
reportData = new List<PublishedPagesDataItem>();
longRunningMethod = GetReportData;
}
protected void Page_Load(object sender, EventArgs e)
{
this.PreRenderComplete +=
new EventHandler(Page_PreRenderComplete);
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsynchOperation),
new EndEventHandler(EndAsynchOperation)
);
}
private List<PublishedPagesDataItem> GetReportData()
{
// this is a long running method
}
private IAsyncResult BeginAsynchOperation(object sender, EventArgs e, AsyncCallback cb, object extradata)
{
return longRunningMethod.BeginInvoke(cb, extradata);
}
private void EndAsynchOperation(IAsyncResult ar)
{
reportData = longRunningMethod.EndInvoke(ar);
}
private void Page_PreRenderComplete(object sender, EventArgs e)
{
reportGridView.DataSource = reportData;
reportGridView.DataBind();
}
So I have a delegate representing the Long running method (GetReportData).
And I am trying to call it as per this article :
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
The long running method does complete in the debugger but breakpoints on the EndAsynchOperation and Page_PreRenderComplete methods never get hit
any idea what I am doing wrong?
the code below works. not sure what the difference is, except that there is a if (!IsPostBack)
anyway, now solved
private delegate List<PublishedPagesDataItem> AsyncReportDataDelegate();
private AsyncReportDataDelegate longRunningMethod;
private List<PublishedPagesDataItem> reportData;
public asynchtest()
{
reportData = new List<PublishedPagesDataItem>();
longRunningMethod = GetReportData;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Hook PreRenderComplete event for data binding
this.PreRenderComplete +=
new EventHandler(Page_PreRenderComplete);
// Register async methods
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation)
);
}
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
return longRunningMethod.BeginInvoke(cb, state);
}
void EndAsyncOperation(IAsyncResult ar)
{
reportData = longRunningMethod.EndInvoke(ar);
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
Output.DataSource = reportData;
Output.DataBind();
}

Resources