Window.close not Working in page Refernce Apex method - salesforce

I have page reference method in apex controller.
I need to close the current tab .
Here is my code:
public PageReference savePostSurveyAnswer(){
String sitePathPrefix = Site.getPathPrefix();
System.debug('savePostSurveyAnswer method start');
CaseIdentifierIdValue = ApexPages.currentPage().getParameters().get('caseIdentifierId');
ShGl_PostChatSurvey__c postChatSurvey = new ShGl_PostChatSurvey__c();
postChatSurvey.ShGl_SurveyQuestion1__c = question1;
postChatSurvey.ShGl_SurveyQuestion2__c = question2;
postChatSurvey.ShGl_SurveyQuestion3__c = question3;
postChatSurvey.ShGl_SurveyQuestion4__c = question4;
postChatSurvey.ShGl_SurveyResponse1__c = questionAnsSelected1;
postChatSurvey.ShGl_SurveyResponse2__c = questionAnsSelected2;
postChatSurvey.ShGl_SurveyResponse3__c = questionAnsSelected3;
postChatSurvey.ShGl_SurveyResponse4__c = questionAnsSelected4;
postChatSurvey.ShGl_Market_Code__c = 'US'; //new data base model
postChatSurvey.ShGl_UniqueCaseIdentifier__c = CaseIdentifierIdValue;
//postChatSurvey.ShGl_LiveTranscriptChatKey__c = chatKeyIdValue;
//postChatSurvey.ShGl_CaseOfSurvey__c = (Id) LiveChatTranscriptObj.CaseId; //through trigger
Database.SaveResult postSaveResult = Database.insert(postChatSurvey);
return new PageReference('javascript:window.close();');
}
Thanks in advance.
Any help would be appreciated.

When you check the documentation for Window.close() you will find the reason:
This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.
In short: The browser won't let you. This is not specific to Salesforce or VF. Windows.close() would anyway not close a tab, but the whole browser window.
If you are looking to close a console tab, this question/answer might provide what you are looking for.

Related

C# Selenium AADSTS90100: login parameter is empty or not valid

I'm creating a method for logging in to MS Dynamics 365 and get the error below when RUN the test:
AADSTS90100: login parameter is empty or not valid.
Here is my code:
public void Login(SecureString login, SecureString password)
{
_driver.Url = "https://{domain}.crm4.dynamics.com/";
_driver.WaitForPageToLoad(TimeSpan.FromSeconds(10));
var userNameInput = _driver.WaitUntilAvailable(By.CssSelector("input[type = 'email']"),
TimeSpan.FromSeconds(10));
userNameInput.SendKeys(login.ToUnsecureString());
var submitButton = _driver.WaitUntilClickable(By.CssSelector("input[type = 'submit'][value =
'Next']"), TimeSpan.FromSeconds(10));
submitButton.Click();
//userNameInput.SendKeys(Keys.Enter);
// following actions
}
I also tried sending the Enter key and Submit() method but no luck.
Interesting thing - I cannot reproduce the issue manually or when DEBUG the test. The error appears only in the RUN mode of the test.
I compared URLs in RUN and DEBUG modes and there is not any difference.
I spent 3 hours in Google but didn't find a solution.
It should be mentioned, that I'm not an experienced dev. So can miss or don't understand something.
Some ideas?
I've found the root cause.
Actually, the issue occurs not after submitButton.Click(); but after another action which is not provided here, since the error message is a bit confusing.
The thing is we used EasyRepro framework in our solution and getting rid of it now since it's not been supported for more than a year now.
If we take a look at EasyRepro login logic, there is such a method:
private static void EnterPassword(IWebDriver driver, SecureString password)
{
var input =
driver.FindElement(By.XPath(Elements.Xpath[Reference.Login.LoginPassword]));
input.SendKeys(password.ToUnsecureString());
input.Submit();
}
And the error is caused by input.Submit(); line. I just copied it in my new method.
It seems like the method submits the whole form before the login has time to be written somewhere.
So, I simply changed that to this one:
private bool EnterPassword(string password)
{
var passwordInput = _driver.FindElement(By.CssSelector("input[type =
'password']"));
passwordInput.SendKeys(password);
var submitButton = _driver.WaitUntilClickable(By.CssSelector("input[type =
'submit'][value = 'Sign in']"),
_defaultWait);
submitButton.Click();
var staySignedInDialog = _driver.WaitUntilAvailable(By.XPath("//div[contains(text(), 'Stay signed
in?')]"), _defaultWait);
return staySignedInDialog != null;
}
Hope will be useful for someone in the future.

WPF native windows 10 toasts

Using .NET WPF and Windows 10, is there a way to push a local toast notification onto the action center using c#? I've only seen people making custom dialogs for that but there must be a way to do it through the os.
You can use a NotifyIcon from System.Windows.Forms namespace like this:
class Test
{
private readonly NotifyIcon _notifyIcon;
public Test()
{
_notifyIcon = new NotifyIcon();
// Extracts your app's icon and uses it as notify icon
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
// Hides the icon when the notification is closed
_notifyIcon.BalloonTipClosed += (s, e) => _notifyIcon.Visible = false;
}
public void ShowNotification()
{
_notifyIcon.Visible = true;
// Shows a notification with specified message and title
_notifyIcon.ShowBalloonTip(3000, "Title", "Message", ToolTipIcon.Info);
}
}
This should work since .NET Framework 1.1. Refer to this MSDN page for parameters of ShowBalloonTip.
As I found out, the first parameter of ShowBalloonTip (in my example that would be 3000 milliseconds) is generously ignored. Comments are appreciated ;)
I know this is an old post but I thought this might help someone that stumbles on this as I did when attempting to get Toast Notifications to work on Win 10.
This seems to be good outline to follow -
Send a local toast notification from desktop C# apps
I used that link along with this great blog post- Pop a Toast Notification in WPF using Win 10 APIs
to get my WPF app working on Win10. This is a much better solution vs the "old school" notify icon because you can add buttons to complete specific actions within your toasts even after the notification has entered the action center.
Note- the first link mentions "If you are using WiX" but it's really a requirement. You must create and install your Wix setup project before you Toasts will work. As the appUserModelId for your app needs to be registered first. The second link does not mention this unless you read my comments within it.
TIP- Once your app is installed you can verify the AppUserModelId by running this command on the run line shell:appsfolder . Make sure you are in the details view, next click View , Choose Details and ensure AppUserModeId is checked. Compare your AppUserModelId against other installed apps.
Here's a snipit of code that I used. One thing two note here, I did not install the "Notifications library" mentioned in step 7 of the first link because I prefer to use the raw XML.
private const String APP_ID = "YourCompanyName.YourAppName";
public static void CreateToast()
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("This is my title!!!!!!!!!!"));
stringElements[1].AppendChild(toastXml.CreateTextNode("This is my message!!!!!!!!!!!!"));
// Specify the absolute path to an image
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Your Path To File\Your Image Name.png";
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
imageElements[0].Attributes.GetNamedItem("src").NodeValue = filePath;
// Change default audio if desired - ref - https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-audio
XmlElement audio = toastXml.CreateElement("audio");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Reminder");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.IM");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Mail"); // sounds like default
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call7");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call2");
//audio.SetAttribute("loop", "false");
// Add the audio element
toastXml.DocumentElement.AppendChild(audio);
XmlElement actions = toastXml.CreateElement("actions");
toastXml.DocumentElement.AppendChild(actions);
// Create a simple button to display on the toast
XmlElement action = toastXml.CreateElement("action");
actions.AppendChild(action);
action.SetAttribute("content", "Show details");
action.SetAttribute("arguments", "viewdetails");
// Create the toast
ToastNotification toast = new ToastNotification(toastXml);
// Show the toast. Be sure to specify the AppUserModelId
// on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
}
UPDATE
This seems to be working fine on windows 10
https://msdn.microsoft.com/library/windows/apps/windows.ui.notifications.toastnotificationmanager.aspx
you will need to add these nugets
Install-Package WindowsAPICodePack-Core
Install-Package WindowsAPICodePack-Shell
Add reference to:
C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd
And
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
And use the following code:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
for (int i = 0; i < stringElements.Length; i++)
{
stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));
}
// Specify the absolute path to an image
string imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png");
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Toast Sample").Show(toast);
The original code can be found here: https://www.michaelcrump.net/pop-toast-notification-in-wpf/
I managed to gain access to the working API for windows 8 and 10 by referencing
Windows.winmd:
C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral
This exposes Windows.UI.Notifications.
You can have a look at this post for creating a COM server that is needed in order to have notifications persisted in the AC with Win32 apps https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/10/16/quickstart-handling-toast-activations-from-win32-apps-in-windows-10/.
A working sample can be found at https://github.com/WindowsNotifications/desktop-toasts

CefSharp load a page with browser login

I need to ebed a web browser in a Wpf app, I tried with the one from the toolbox but get some issues and went to CefSharp.
public MainWindow()
{
InitializeComponent();
BrowserSettings settings = new BrowserSettings();
Cef.Initialize(new CefSettings());
CefSharp.Wpf.ChromiumWebBrowser webBrowser = new CefSharp.Wpf.ChromiumWebBrowser();
licence_grid.Children.Add(webBrowser);
webBrowser.Address = "http://myurlToLoad the page";
}
The problem is when I used a normal url the page load.
But when I used the url I intend to use and whith which the user enter his user and password in a browser pop up (I mean not a pop up from the website) . I get an error with this page take yoo much time to load and nothing else.
Can someone give me some tracks to follow...
Thanks
It sounds like the popup you are referring to is in fact the site prompting for basic authentication.
In that case you need to provide an IRequestHandler.GetAuthCredentials handler.
As the question & answer is very old and i would like to give the latest update on this solution, there is slight change as per original solution suggested.
anybody consuming cefsharp need to implement the authentication dialog. and changes in method is
bool IRequestHandler.GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy,
string host, int port, string realm, string scheme, IAuthCallback callback)
{
//NOTE: If you do not wish to implement this method returning false is the default behaviour
// We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
// shyam - original implemenation.
//callback.Dispose();
//return false;
bool handled = false;
// Instantiate the dialog box
AuthDialog dlg = new AuthDialog(host); // create new dialog with username and password field.
// Open the dialog box modally
dlg.ShowDialog();
if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
{
// The user did not cancel out of the dialog. Retrieve the username and password.
callback.Continue(dlg.UserName,dlg.Password);
handled = true;
}
return handled;
}

Animated GIF in please wait from

I have a please wait form in a windows application that gets rendered before a long running task, the please wait contains an animated gif that needs to "spin" during this process but I can't get this work.
I finally got the form to display correctly using the following code:
frmChooser chooser = frmChooser.Instance;
chooser.Url = this.UrlTextBox.Text;
frmBuildNotification fb = new frmBuildNotification();
fb.Show(this);
fb.Update();
Application.DoEvents();
chooser.BuildTreeView();
fb.Close();
this.Hide();
chooser.Show(this);
The GIF is contained within a PictureBox control on frmBuildNotification
I've read somewhere that you'll need to repaint the form for the image to animate, but this seems a bit tedious?
You need to keep the DoEvents message pump going and it also helps if you throw your notification form on another thread. Try this:
bool done = false;
frmBuildNotification fb = null;
ThreadPool.QueueUserWorkItem((x) =>
{
using (fb = new frmBuildNotification())
{
fb.Show();
while (!done)
Application.DoEvents();
fb.Close();
}
});
frmChooser chooser = frmChooser.Instance;
chooser.Url = this.UrlTextBox.Text;
chooser.BuildTreeView();
done = true;
this.Hide();
chooser.Show(this);

open a PDF : WPF

I want to open a PDF file in a button click. I'll keep the PDF file within the solution/namespace of the project. Can anyone give me solution for this?
To start the standard PDF viewer you can simply start an external process:
Process proc = new Process( );
proc.StartInfo = new ProcessStartInfo( ) {
FileName = path //put your path here
};
proc.Start( );
To show the file inside your application you have to use the pdf viewer as an ActiveX-component.
My solution:
private AxAcroPDFLib.AxAcroPDF axAcroPDF1;
this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();
this.axAcroPDF1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axAcroPDF1.Enabled = true;
this.axAcroPDF1.Name = "axAcroPDF1";
this.axAcroPDF1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axAcroPDF1.OcxState")));
axAcroPDF1.LoadFile(DownloadedFullFileName);
axAcroPDF1.Visible = true;
You have many options:
User WPF WebBrowser control and open the pdf:
Link 1, Link 2
User WinformsHost to host ActiveX Stackoverflow link.

Resources