Windows 8.1 ScriptNotify not working - c#

I am stumped on an issue with webview and scriptnotify
Server chap has put the following code in the web page:
javascript(alert) and javascript(confirm)
I put in a Debug Writeline to even see if the method is being called but it is not.
I can confirm that the https://webpage.com is in the Manifest as an accepted Uri.
Here is my code
XAML
<Grid>
<WebView x:Name="webView1" HorizontalAlignment="Stretch" ScriptNotify="MyWebView_ScriptNotify" VerticalAlignment="Stretch" />
</Grid>
C#
public TeamPage()
{
this.InitializeComponent();
webView1.ScriptNotify += MyWebView_ScriptNotify;
//other stuff
}
async void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
Debug.WriteLine("in here");
var jsScriptValue = e.Value;
MessageDialog msg = new MessageDialog(jsScriptValue);
var res = await msg.ShowAsync();
}
As said, the MyWebView_ScriptNotify is not even called?? There does not seem to be much examples on this issue so any help would be much appreciated. Thanks.

ScriptNotify does not fire on javascript alert or confirm.
It fires if the webpage does the following in JavaScript:
window.external.notify('some value');
Also see description and sample in MSDN
Edit: If you need to get notified about alert and confirm you could do something like this:
// do this after initialization of the webview
this.MyWebView.NavigationCompleted += MyWebView_NavigationCompleted;
...
async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// this will override the alert function with a function calling
// the window.external.notify function
// you should be able to do the same with confirm
string inject =
#"window.alert = function(arg) {
window.external.notify(arg);
};";
await MyWebView.InvokeScriptAsync("eval", new List<string>() { inject });
}

Talked with the server chap and it looks like we can not do it in my instance. Dennis' solution is the answer if someone is looking for a similar solution, but if you want to use alert and confirm, then its not possible as far as I can tell. That said, happy to be corrected and update this answer if corrected.

Related

How to detect call hang up in windows phone 10

I want to programmatically detect when call hang up in UWP app for windows phone 10.
I see Caller ID sample and see Communication blocking and filtering sample too.
But I don't find simple solution for detect when call hang up. I found CallHistoryChanged trigger and I think my complex solution is read call history when call history changed trigger and get last incoming call.
Is there any simple solution for detect call hang up?
Is my solution is correct?
Is there a better solution than my solution?
Is there any simple solution for detect call hang up?
Is my solution is correct? Is there a better solution than my solution?
As far as I know, there is no other simple solution for detect calls' hang up.
There is an event PhoneCallManager.CallStateChanged, which can also detect hang up like below:
private bool callCame = false;
PhoneCallManager.CallStateChanged += PhoneCallManager_CallStateChanged;
private async void PhoneCallManager_CallStateChanged(object sender, object e)
{
if (callCame&&(!PhoneCallManager.IsCallActive))
{
//do something
}
if (PhoneCallManager.IsCallIncoming)
{
callCame = true;
}
}
But I don't think it's better than CallHistoryChanged trigger. And it won't get you the last Hang up phone's number either.
Is my solution is correct?
So yes, your solution is correct.
Update: There is no trick here. Register the BackgroundTask:
private void btnClick_Click(object sender, RoutedEventArgs e)
{
var taskRegistered = false;
var exampleTaskName = "MyBackgroundTask";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
taskRegistered = true;
break;
}
}
if (!taskRegistered)
{
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "PhoneCallBackground.Class1";
builder.SetTrigger(new PhoneTrigger(Windows.ApplicationModel.Calls.Background.PhoneTriggerType.CallHistoryChanged, false));
builder.Register();
}
}
And don't forget to register it in the appxmanifest file:
The Run Method will be fired after you hang up, if you registered the BackgroundTask. PhoneCallManager can not be registered for BackgroundTask. You need to set it as the default PhoneCall App, if you want to use this.
Update2:
I checked the demo, you are still using PhoneTriggerType.CallOriginDataRequest to register the background task. Please change it to PhoneTriggerType.CallHistoryChanged. And also make sure the registered background task is unregistered after you making any change to your codes.
Here is the demo that I modified: CallHistoryChangeTest.

Windows Phone ContactPicker won't await properly

Although this has been posted before on StackOverflow but i think none of those reflect my issue and none of those solutions work for me either. So i'm developing a Windows Phone app and my workflow is a bit like this:
App starts
ContactPicker opens up
User selects one or multiple contacts
Based on how many contacts he selected, that many PivotItems are added into the Pivot.
My code is as follows:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
SelectContacts();
}
private async Task SelectContacts()
{
var picker = new ContactPicker();
picker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
ContactsList = (List<Contact>)await picker.PickContactsAsync();
DisplayContacts();
}
private void DisplayContacts()
{
if (ContactsList != null)
{
foreach (var item in ContactsList)
{
PivotItem pivotItem = new PivotItem();
pivotItem.Header = item.FirstName.ToString();
ContentRoot.Items.Add(pivotItem);
}
}
}
According to me, in SelectContacts() method, the app should wait at the await call and once it gets back the list of contacts, than it should execute the DisplayContacts() method but its not working. I've tried multiple other variations of this code and they aren't working either.
await the SelectContacts() method and add the DisplayContacts() method beneath it. Remove the DisplayContacts() method from SelectContacts()
await SelectContacts();
DisplayContacts();
I don't know the complete reason why but i figured it out that since i was making the PickContactsAsync() call in the OnNavigatedTo() event, that is why it wasn't working as expected. Once i moved the PickContactsAsync() call into the PageLoaded() event handler, it started working as usual.

Delay in event in code behind file

In my application I have a button to save some information. However, I would like to have a delay in the code before the last line is executed, so that the user could read the message that shows up before he gets redirected to the new page.
I know that doing this isn't at all an optimal way, but by some reasons (time, for example) I want to do it anyway.
So is it possible and if so, how could I do it?
Thanks in advance!
protected void SaveButton_Click(object sender, EventArgs e) {
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
Response.Redirect(String.Format("~/Edit.aspx?id={0}", movie.MovieID), false);
}
You need to do this on the client side. One alternative is this:
Define a Javascript function in the page called redirect as so:
function redirect(url)
{
setTimeout(function(){window.location.href=url;} ,2000);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
ClientScript.RegisterStartupScript(this.GetType(),"somekey","redirect('"+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+"');");
}
This will be easy if you are using Javascript. Use javascript will boost performance
Button_Click
{
string js ="<script type='text/javascript'>setTimeout(function()window.location.href="+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+";} ,2000);</script>"
ScriptManager.RegisterStartupScript(Me.Page, GetType(Page), "js", js, False)
}
possible duplicate of
asp.net delay before response redirect

Firing a server-side method via PageMethod

I wrote a JavaScript function that fires when the user clicks OK in a RadConfirm dialog. This is supposed to trigger a JavaScript callback to the server to delete a record from the database. This may not be the best architecture (I can think of other ways to accomplish my goals) but I'm trying to struggle through this as a learning exercise. Below is the code I've written thus far. I think I've gotten most of it correct.
This Javascript function:
function confirmCallBackFn(arg) {
if (arg == true) {
PageMethods.RemovePackagePageMethod();
}
else {
}
}
Should invoke the following WebMethod on the server:
[WebMethod()]
public static void RemovePackagePageMethod(object sender, EventArgs e)
{
Inventory inv = new Inventory();
inv.RemovePackage();
}
Which in turn should execute the following method:
private void RemovePackage()
{
SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();
var boxes = from p in db.Packages
where p.PackageID == Convert.ToInt32(RadGrid1.SelectedValues["PackageID"].ToString())
select p;
foreach (var box in boxes)
{
db.Packages.DeleteOnSubmit(box);
}
try
{
db.SubmitChanges();
RadGrid1.Rebind();
}
catch (Exception ex)
{
RadWindowManager1.RadAlert("System error deleting package", 200, 200, "exception", null);
}
}
Everything looks good to me and seems to be consistent with the posts I've read on this site and others about using PageMethod to fire code on the server. However, it's failing to execute the deletion in the final method (which I've tested in isolation). Can someone spot where I went wrong?
You are trying to use the RadGrid1 control in the RemovePackage method, but you are calling the method from a web method, so there is no instance of the Page class, and thus there is no RadGrid1 control.
You would have to send the id of the record that you want to delete from the client code to the web method, and from there along to the RemovePackage method.
Also, you can't rebind the RadGrid1 control to make the changes appear in the page. The web method call is not a page request, so there is no page response that can contain the updated grid. You would have to update the grid in the client code.
Try making the RemovePackage method Public (Friend may work too) instead of private and then try.

Callback function?

I need to callback Javascript function in my code, but not firing. I am providing details what I am doing?.
I have input button in the page that calling javascript function. There I am loading another ProfilePic.aspx page. ProfilePic.aspx has FileUpload, OK and cancle button
<input type=button value="Change Image" onclick="javascript:SelectUserImage()" />
Javascript functions are
<script type="text/javascript">
function SelectUserImageCallback(ret) {
var imgId = 'ctl00_PlaceHolderMain_prof_imgUser';
var clearId = 'ctl00_PlaceHolderMain_prof_hidImageURL';
if (ret) {
if (ret == '__RESET__') {
document.getElementById(imgId).src = '\u002f_layouts\u002fimages\u002fno_pic.gif';
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = '';
document.getElementById(clearId).style.display = 'none';
}
else {
document.getElementById(imgId).onload = 'imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');';
document.getElementById(imgId).src = ret;
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = ret;
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 1);
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 100);
document.getElementById(clearId).style.display = '';
}
}
}
function SelectUserImage() {
var href = '\u002f_layouts\u002fProfilePic.aspx';
var features = 'resizable: yes; status: no; scroll: no; help: no; center: yes; dialogWidth: 460px; dialogHeight: 140px; width:460;height:240;menubar:no;directories:no;location:no;';
commonShowModalDialog(href, features, SelectUserImageCallback, null);
}
In the ProfilePic.aspx page once user click OK buttong. I am upload his pic with some logic then I am closing window with javascript
protected void btnOK_Click(Object sender, EventArgs e)
{
try
{
// My logic Here
Debug.WriteLine("Shared Pictures Save Ends: " + DateTime.Now);
Response.Write ("<script language =javascript>close();</script>");
Response.End();
}
catch (Exception exception)
{
LogMessage(exception.Message, EventLogEntryType.Error);
if (exception.Message.ToLower().Contains("blocked"))
errorDisplay.Text = "* This type of file has been blocked by the administrator, please try a different file.";
else
{
errorDisplay.Text = exception.Message;
}
}
}
My Question: I am able to close the window but, What ever I need to call callback function `SelectUserImageCallback' not firing. I need to call this method after OK button part execution done.
Are you closing the window before the callback executes? I've done that before. As an experiment, try commenting out the code that closes the window.
You may have to restructure your code so that the callback function closes the window when it's finished whatever it's doing.
Update: Sorry, I misunderstood the question. There was a lot of code and I didn't read it all. I thought the call back was in the dialog page, but it looks like it's in the main page. I'm not familiar with commonShowModalDialog(), but it looks like it may have something to do with SharePoint. Do you have any documentation on that method? I found this discussion that makes it look like there's a special way to return a value from the dialog box. It may be that your callback isn't being called because you're not closing the window the right way. (That's a total guess on my part.)
Good luck.

Categories