Cefsharp Custom Prompt - cefsharp

How can i make custom Prompt?
I tried with code below..
public static string ShowDialog(string text, string caption) {
Form prompt = new Form() {
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
And then am using it like below
public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) {
if(dialogType.ToString() == "Prompt") {
//Form prompt = ShowDialogClass.ShowDialog("as", "asd");
string promptValue = Components.ShowDialog("Test", "123");
if (promptValue != "") {
callback.Continue(true, promptValue);
} else {
callback.Continue(false, "");
};
};
But i am getting error.
System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'
return false;
}
How can i implement this dialog to show custom prompt?

Few months too late but, here you go.
You are trying to create a new Form(your prompt form) inside another thread. In this case your CEF browser thread that will create a object from class IJsDialogHandler will be on another thread than the prompt message thread so you have to Cross the thread to access it.
The way you do this is "Invoke"(saying something like "wo wo don't worry, i know what i'm doing"). When you use "Invoke" your asking for a witness, well that witness should have the same kind of capabilities as your prompt message box form so.... in this case form that creates the CEF browser. so the code should be something like this
public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) {
if(dialogType.ToString() == "Prompt") {
if (ParentForm.InvokeRequired)
{
ParentForm.Invoke((MethodInvoker)delegate ()
{
string promptValue = Components.ShowDialog(messageText, "Prompt Message");
if (promptValue != "") {
callback.Continue(true, promptValue);
} else {
callback.Continue(false);
}
}
}
suppressMessage = false;
return true;
}
}
ParentForm should be changed to the name of the form that initialize the CEF browser.

Related

Passing images from one page to another in Xamarin Forms

In my app I need to pass images from one page to another page image view to display. I am taking a photo from camera and do some stuffs, then I want to send that images to the second page.
if (await isCamAvailable())
{
MediaFile photo1 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { Directory = "NewBusiness", Name = "image1.jpg", PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 1024, CompressionQuality = 95 });
if (photo1 != null)
{
PhotoImage1.Source = ImageSource.FromStream(() => { return photo1.GetStream(); });
countList.Remove("a");
countList.Add("a");
}
}
Then I am added it to a string array by doing
private List<string> sendImgList = new List<string>();
sendImgList.Add(createImgByteString(photo1.GetStream()));
private string createImgByteString(Stream data)
{
var bytes = new byte[data.Length];
return Convert.ToBase64String(bytes);
}
Then from second page (for testing i just added only one image)
foreach (string ss in imgList) {
byte[] Base64Stream = Convert.FromBase64String(ss);
imgView.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
}
I followed this example. But image not showing.
https://forums.xamarin.com/discussion/139360/how-to-transfer-images-from-one-page-to-another
Also getting this in logcat..
[0:] ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource05-29 14:22:43.758 W/monodroid-assembly( 8737): typemap: unable to find mapping to a Java type from managed type 'System.Byte, mscorlib'
It seems that you used the Media.Plugin . Why don't you pass the ImageSource directly?
If you do want to convert it to byte array , check the following code
public byte[] GetImageStreamAsBytes(Stream input)
{
var buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
var imgDate = GetImageStreamAsBytes(photo1.GetStream());
It would be better to pass the byte array directly .
The best mode to pass parameter in pages is with Prism.
https://prismlibrary.com/docs/xamarin-forms/navigation/passing-parameters.html
>
_navigationService.NavigateAsync(new Uri("MainPage", new NavigationParameters
{
{ "key_parameter", image }
})));
And on other page:
>
public override void OnNavigatedTo(INavigationParameters parameters)
{
image = (Image)parameters["key_parameter"];
}

Inspite of checking for null with usercontrol checkboxlist is returning object reference not set to an instance of an object

I have a group of 7 checkboxes in checkboxlist user control. I build a string in the selectedIndexchanged event for the boxes checked, pass to ViewState and then pass ViewState to the Property. I do this because in the instance when no checkboxes are selected I want to handle null. The problem is no matter how I check for null, the system is throwing object reference error. This current setup works fine if at least one checkbox is checked but if none are checked it fails. How do I check for null? Should I be checking for null in the property or the host aspx page?
I have researched difference ways to do this and I have tried many. My thought is using IsNullOrEmpty or IsNullOrWhiteSpace would be the correct way to go but neither are working.
User Control class - global variable
private string _daysOffInputString = string.Empty;
User Control Property
public string DaysOffSelectedValues
{
get
{
if (string.IsNullOrEmpty(ViewState["DaysOff"].ToString()))
{
_daysOffInputString = string.Empty;
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
User Control event
protected void CbDaysOff_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList chkbx = (CheckBoxList)sender;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
{
sb.Append(chkbx.Items[i].Text + ", ");
}
if (!String.IsNullOrEmpty(sb.ToString()))
{
//Remove last comma & space from string
_daysOffInputString = sb.ToString().Substring(0, sb.ToString().Length - 2);
}
else
{
_daysOffInputString = string.Empty;
}
}
ViewState["DaysOff"] = _daysOffInputString;
}
aspx page - snippet where I retrieve uc property value:
case 2:
blnFlag = false;
ucDaysOff uc3 = row.Cells[3].FindControl("ucDaysOff3") as ucDaysOff;
strAnswer = uc3.DaysOffSelectedValues; //e.g. "Sat, Sun"
break;
SOLUTION: In the user control property DaysOffSelectedValues I was casting ViewState["DaysOff"] to string before checking for null which was the problem. Here's the code that works:
public string DaysOffSelectedValues
{
get
{
if (ViewState["DaysOff"] == null)
{
//_daysOffInputString = string.Empty; }
_daysOffInputString = "Nothing to see here.";
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
}
You should always check if the object, in this case ViewState, is null before using it. Lets say ViewState["DaysOff"] has not been created or has been removed.
Then this will throw a nullreference:
string str = String.IsNullOrEmpty(ViewState["DaysOff"].ToString());
Because you are not checking the ViewState object for null, but the string it is supposed to hold.
So do this
if (ViewState["DaysOff"] != null)
{
string str = ViewState["DaysOff"].ToString();
}

Xamarin.Forms refresh TextProperty of Editor

Is there a way to change the text in an Editor cell after an event?
I have an Editor cell that shows an address from an SQLite database. I also have a button that gets the current address and shows this in an alert that asks if they would like to update the address to this. If Yes, then I would like to show the new address in the Editor cell.
public class UserInfo : INotifyPropertyChanged
{
public string address;
public string Address
{
get { return address; }
set
{
if (value.Equals(address, StringComparison.Ordinal))
{
return;
}
address = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
My code for the editor cell is
Editor userAddress = new Editor
{
BindingContext = uInfo, // have also tried uInfo.Address here
Text = uInfo.Address,
Keyboard = Keyboard.Text,
};
and then this after it has got the current address I have this
bool response = await DisplayAlert("Current Address", "Would you like to use this as your address?\n" + currAddress, "No", "Yes");
if (response)
{
//we will update the editor to show the current address
uInfo.Address = currAddress;
}
How do I get it to update the Editor cell to show the new address?
You are setting the BindingContext of the control, but not specifying a binding to go with it. You want to bind the TextProperty of the Editor to the Address property of your context.
Editor userAddress = new Editor
{
BindingContext = uinfo,
Keyboard = Keyboard.Text
};
// bind the TextProperty of the Editor to the Address property of your context
userAddress.SetBinding (Editor.TextProperty, "Address");
This may also work, but I'm not positive the syntax is correct:
Editor userAddress = new Editor
{
BindingContext = uinfo,
Text = new Binding("Address"),
Keyboard = Keyboard.Text
};

Caliburn.Micro Screen.CanClose() and MessageDialog().ShowAsync()

I'm currently using Caliburn.Micro 2.0 for my Windows Phone 8.1 project (Universal App) and I'm having problem with conditionally cancelling page close after user clicks a MessageDialog button.
It seems that Caliburn closes page after leaving CanClose() method, not waiting for the callback which is called after async MessageDialog.
public class MyViewModel: Screen
{
public override async void CanClose(Action<bool> callback)
{
MessageDialog dlg = new MessageDialog("Close?","Confirmation");
dlg.Commands.Add(new UICommand() { Id = 0, Label = "Yes" });
dlg.Commands.Add(new UICommand() { Id = 1, Label = "No" });
var result = await dlg.ShowAsync();
callback((int)result.Id == 0);
}
}
The only solution I have at the moment is set a field with a flag indicating if the page can be closed. On the user attempt to navigate back I tell Caliburn to abort the close and I display the confirmation dialog. When I get the result I set the flag to true and navigate back manually. This causes another call to CanClose, but this time I set the callback to true and skip the dialog part.
I don't like this solution much, but it is only way I managed to solve this problem.
private bool canClose = false;
public override async void CanClose(Action<bool> callback)
{
callback(canClose);
if (!canClose)
{
MessageDialog dlg = new MessageDialog("Close?","Confirmation");
dlg.Commands.Add(new UICommand() { Id = 0, Label = "Yes" });
dlg.Commands.Add(new UICommand() { Id = 1, Label = "No" });
var result = await dlg.ShowAsync();
if ((int)result.Id == 0)
{
canClose = true;
navigationService.GoBack();
}
}
}
PS: I don't use MessageDialog directly in my ViewModel, I'm using a dialog service interface for popups. I just used it here to demonstrate the issue.
While the enhancement CanClose isn't set, this is my approach utilize Navigating event to solve this 'problem'
If user could just GoBack() would be easy to handle, but in my case, there's many options to navigate. So, the only way that I found to solve it is described below:
public MyViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
_navigationService.Navigating += OnGoBack;
}
private async void OnGoBack(object sender, NavigatingCancelEventArgs e)
{
e.Cancel = true;
var dlg = new MessageDialog("Close?", "Confirmation"); //Dialog for demo purpose only!
dlg.Commands.Add(new UICommand() { Id = 0, Label = "Yes" });
dlg.Commands.Add(new UICommand() { Id = 1, Label = "No" });
var result = await dlg.ShowAsync();
if ((int) result.Id != 0) return;
_navigationService.Navigating -= OnGoBack;
if (e.NavigationMode == NavigationMode.Back)
_navigationService.GoBack();
else
{
var myViewModel = Type.GetType($"YourNameSpaceViewModels.{e.SourcePageType.Name}Model");
_navigationService.NavigateToViewModel(myViewModel);
}
}
Explaination:
$"YourNameSpaceViewModels.{e.SourcePageType.Name}Model"
Here I get the full path to my class where user want to goto
And so, I navigate to it _navigationService.NavigateToViewModel(myViewModel);

How can I use the ContextKeys property for the AjaxFileUpload control?

I started looking at the AjaxFileUpload control, specifically the ContextKeys property. However, I do not understand how to use it.
The documentation says of AjaxFileUpload that the ContextKeys is used to pass information to the server when a file is uploaded. But no examples are provided. Are there any examples online that I could look at?
Though such functionality not implemented (I believe it was planned but by some reasons was postponed), nothing protect you from implement it yourself. To do this you need to download AjaxControlToolkit source code and tweak it for your needs.
There will be a lot of points so you may to prepare a cup of coffee before :)
I'll show changes with name of file that must being changed.
Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs file
First of all, add ContextKeys property to the AjaxFileUploadEventArgs.cs file (it located in same folder):
/// <summary>
/// Gets or sets the context keys.
/// </summary>
public string ContextKeys
{
get;
set;
}
After that open the AjaxFileUpload class code and change the OnPreRender method. Here is a part of this method with custom modifications:
var eventArgs = new AjaxFileUploadEventArgs(guid, AjaxFileUploadState.Success,
"Success", uploadedFile.FileName,
uploadedFile.ContentLength, uploadedFile.ContentType,
stream.ToArray());
// NEW CODE HERE
eventArgs.ContextKeys = this.Page.Request.Form["contextKeys"];
That's all changes in server code we need. Now we need to modify the Sys.Extended.UI.AjaxFileUpload client class (file AjaxFileUpload.pre.js )
Firstly let's modify _html5UploadFile method as below:
_html5UploadFile: function (fileItem) {
this._guid = Sys.Extended.UI.AjaxFileUpload.utils.generateGuid();
var uploadableFile = fileItem.get_fileInputElement();
var fd = new FormData();
fd.append("fileId", uploadableFile.id);
fd.append("Filedata", uploadableFile.file);
if (this.contextKeys) {
if (typeof this.contextKeys !== "string") {
this.contextKeys = Sys.Serialization.JavaScriptSerializer.serialize(this.contextKeys);
}
fd.append("contextKeys", this.contextKeys);
}
$common.setVisible(this._progressBar, true);
this._setDisableControls(true);
this._html5SetPercent(0);
this._setStatusMessage(String.format(Sys.Extended.UI.Resources.AjaxFileUpload_UploadingHtml5File, uploadableFile.file.name, Sys.Extended.UI.AjaxFileUpload.utils.sizeToString(uploadableFile.file.size)));
var url = this._postBackUrl;
if (url.indexOf("?") != -1)
url += "&";
else
url += "?";
this._webRequest = new Sys.Net.WebRequest();
this._executor = new Sys.Net.XMLHttpExecutor();
this._webRequest.set_url(url + 'contextkey=' + this._contextKey + '&guid=' + this._guid);
this._webRequest.set_httpVerb("POST");
this._webRequest.add_completed(this.bind(this._html5OnRequestCompleted, this));
//this._executor.add_load(this.bind(this._html5OnComplete, this));
this._executor.add_progress(this.bind(this._html5OnProgress, this));
this._executor.add_uploadAbort(this.bind(this._html5OnAbort, this));
this._executor.add_error(this.bind(this._html5OnError, this));
this._webRequest.set_executor(this._executor);
this._executor.executeRequest(fd);
}
As you can see above, we adding contextKeys to form data, posted with Ajax request.
The we need to modify the _uploadInputElement method:
_uploadInputElement: function (fileItem) {
var inputElement = fileItem.get_fileInputElement();
var uploader = this;
uploader._guid = Sys.Extended.UI.AjaxFileUpload.utils.generateGuid();
setTimeout(function () {
uploader._setStatusMessage(String.format(Sys.Extended.UI.Resources.AjaxFileUpload_UploadingInputFile, Sys.Extended.UI.AjaxFileUpload.utils.getFileName(inputElement.value)));
uploader._setDisableControls(true);
uploader.setThrobber(true);
}, 0);
var url = uploader._postBackUrl;
if (url.indexOf("?") != -1)
url += "&";
else
url += "?";
uploader._createVForm();
uploader._vForm.appendChild(inputElement);
if (this.contextKeys) {
if (typeof this.contextKeys !== "string") {
this.contextKeys = Sys.Serialization.JavaScriptSerializer.serialize(this.contextKeys);
}
var contextKeysInput = document.createElement("input");
contextKeysInput.setAttribute("type", "hidden");
contextKeysInput.setAttribute("name", "contextKeys");
contextKeysInput.setAttribute("value", this.contextKeys);
uploader._vForm.appendChild(contextKeysInput);
}
uploader._vForm.action = url + 'contextkey=' + this._contextKey + '&guid=' + this._guid;
uploader._vForm.target = uploader._iframeName;
setTimeout(function () {
uploader._vForm.submit();
uploader._waitTimer = setTimeout(function () { uploader._wait() }, 100);
}, 0);
}
After all these changes you can set ContextKeys property in code-behind and get it value from AjaxFileUploadEventArgs argument of the UploadComplete event as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !AjaxFileUpload1.IsInFileUploadPostBack)
{
AjaxFileUpload1.ContextKeys = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new Dictionary<string, string> { { "1", "First" }, { "2", "Second" } });
}
protected void AjaxFileUpload1_OnUploadComplete(object sender, AjaxFileUploadEventArgs file)
{
if (!string.IsNullOrEmpty(file.ContextKeys))
{
var contextKeys = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, string>>(file.ContextKeys);
}
Also, if you'll implement OnClientUploadStarted client-side event as proposed here link, you may pass to server your contextKeys from client:
function uploadStarted(sender, args) {
sender.contextKeys = { "first": "1", "second": "2" };
}

Resources