Watin AddDialogHandler method throwing null reference exception in FF - watin

I'm trying to add ConfirmDialogHandler to dialog handler and i get NullReferenceException.
This happens on FF 3.6 with latest watin version, the same code works on IE7 and 8.
ConfirmDialogHandler confirmDialogHandler = new ConfirmDialogHandler();
browser.AddDialogHandler(confirmDialogHandler); // --> exception here
Any ideas?

Old Solution
Found the problem.
The DialogWatcher was not initialized when FF session was created added this line to watin code:
private void CreateFireFoxInstance(string url)
{
Logger.LogAction("Creating FireFox instance");
UtilityClass.MoveMousePoinerToTopLeft(Settings.AutoMoveMousePointerToTopLeft);
var clientPort = GetClientPort();
clientPort.Connect(url);
_ffBrowser = new FFBrowser(clientPort);
StartDialogWatcher(); // <-- Added line
WaitForComplete();
}
Please Note - This is the workaround
The provided solution didn't worked
This is my workaround:
I used AutoIt dll and handled the popups by my self, code sample:
using AutoItX3Lib;
public static void RunAutomaticEnterCommand(Session session)
{
var autoIt = GetPopupHandle();
autoIt.Send("{ENTER}");
Thread.Sleep(1000);
}
/// <summary>
/// Cancel the popup
/// For FF
/// </summary>
/// <param name="session"></param>
public static void RunAutomaticCancelCommand(Session session)
{
var autoIt = GetPopupHandle();
autoIt.Send("{TAB}");
autoIt.Send("{ENTER}");
Thread.Sleep(1000);
}
/// <summary>
/// Return the autoit popup handler
/// AutoIt is a script language, we using it to handle the firefox popups
/// </summary>
/// <returns></returns>
private static AutoItX3Class GetPopupHandle()
{
var autoIt = new AutoItX3Class();
autoIt.AutoItSetOption("WinTitleMatchMode", 2);
const string partialTitle = "The page at"; //the popup in Firefox starts with this text
autoIt.WinWait(partialTitle, "", 30);
string fullTitle = autoIt.WinGetTitle(partialTitle); //Get the whole popup title
autoIt.WinActivate(fullTitle); //Get focis to the popup
if (autoIt.WinWaitActive(fullTitle, "", 20) == 0)
{
reporter.Report("Failed to get the FireFox popup handle", false);
return autoIt;
}
return autoIt;
}

Related

Getting poor quality picture in Windows UWP if taken immediately after start

Getting poor quality picture in Windows UWP if taken immediately after starting preview. TakePhotoAsync() is called in StartPreviewAsync() task then part. Consistently getting poor quality pictures. How to get good quality picture immediately after starting preview?. Code is based on CameraStarterKit.
/// <summary>
/// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
/// </summary>
/// <returns></returns>
task<void> MainPage::InitializeCameraAsync()
{
DBOUT(__func__);
WriteLine("InitializeCameraAsync");
// Get available devices for capturing pictures
return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Back)
.then([this](DeviceInformation^ camera)
{
if (camera == nullptr)
{
WriteLine("No camera device found!");
return;
}
// Figure out where the camera is located
if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
{
// No information on the location of the camera, assume it's an external camera, not integrated on the device
_externalCamera = true;
}
else
{
// Camera is fixed on the device
_externalCamera = false;
// Only mirror the preview if the camera is on the front panel
_mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
}
_mediaCapture = ref new Capture::MediaCapture();
// Register for a notification when video recording has reached the maximum time and when something goes wrong
_recordLimitationExceededEventToken =
_mediaCapture->RecordLimitationExceeded += ref new Capture::RecordLimitationExceededEventHandler(this, &MainPage::MediaCapture_RecordLimitationExceeded);
_mediaCaptureFailedEventToken =
_mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
auto settings = ref new Capture::MediaCaptureInitializationSettings();
settings->VideoDeviceId = camera->Id;
settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
// Initialize media capture and start the preview
create_task(_mediaCapture->InitializeAsync(settings))
.then([this]()
{
_isInitialized = true;
return StartPreviewAsync()
.then([this]()
{
UpdateCaptureControls();
});
}).then([this](task<void> previousTask)
{
try
{
previousTask.get();
}
catch (AccessDeniedException^)
{
WriteLine("The app was denied access to the camera");
}
});
});
}
/// <summary>
/// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
/// </summary>
/// <returns></returns>
task<void> MainPage::StartPreviewAsync()
{
DBOUT(__func__);
// Prevent the device from sleeping while the preview is running
_displayRequest->RequestActive();
// Set the preview source in the UI and mirror it if necessary
PreviewControl->Source = _mediaCapture.Get();
PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
// Start the preview
return create_task(_mediaCapture->StartPreviewAsync())
.then([this](task<void> previousTask)
{
_isPreviewing = true;
FN_TRACE("CameraStreamState::Streaming %d\n", _mediaCapture->CameraStreamState);
TakePhotoAsync();
// Only need to update the orientation if the camera is mounted on the device
if (!_externalCamera)
{
return SetPreviewRotationAsync();
}
// Not external, just return the previous task
return previousTask;
});
}
/// <summary>
/// Takes a photo to a StorageFile and adds rotation metadata to it
/// </summary>
/// <returns></returns>
task<void> MainPage::TakePhotoAsync()
{
DBOUT(__func__);
// While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
VideoButton->IsEnabled = _mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported;
// Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
VideoButton->Opacity = VideoButton->IsEnabled ? 1 : 0;
auto inputStream = ref new Streams::InMemoryRandomAccessStream();
// Take the picture
WriteLine("Taking photo...");
return create_task(_mediaCapture->CapturePhotoToStreamAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg(), inputStream))
.then([this, inputStream]()
{
return create_task(_captureFolder->CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption::GenerateUniqueName));
}).then([this, inputStream](StorageFile^ file)
{
WriteLine("Photo taken! Saving to " + file->Path);
// Done taking a photo, so re-enable the button
VideoButton->IsEnabled = true;
VideoButton->Opacity = 1;
auto photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
return ReencodeAndSavePhotoAsync(inputStream, file, photoOrientation);
}).then([this](task<void> previousTask)
{
try
{
previousTask.get();
}
catch (Exception^ ex)
{
// File I/O errors are reported as exceptions
WriteException(ex);
}
});
}

GoBack() to previous page UWP

I launch a page on UWP thanks to PageRenderer, this page allows take picture and I want go back when user take a pciture.
My problem is when I go back with hardware button I have no problem but with function goback doesn't work.
This is my code :
var frame = Window.Current.Content as Frame;
if (frame != null && frame.CanGoBack)
{
frame.GoBack();
}
CanGoBack return false.
So you have some idea
Thanks
You need to hook into the back button pressed and then force the navigation back
public PageContainer()
{
this.InitializeComponent();
SystemNavigationManager.GetForCurrentView().BackRequested += PageContainer_BackRequested;
}
/// <summary>
/// Handles when the user presses the back button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PageContainer_BackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null){
return;
}
// Navigate back if possible, and if the event has not
// already been handled .
if (rootFrame.CanGoBack && e.Handled == false)
{
e.Handled = true;
rootFrame.GoBack();
}
}
This example is an adaptation of the example provided on the MSDN website
You have to use the BackPressed Event.
public Test()
{
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
private void Test_BackPressed(object sender, BackPressedEventArgs e)
{
if (this.Layer.CanGoBack)
{
e.Handled = true;
this.Layer.GoBack();
}
}

Bind ListBox (or Telerik RadListPicker) to Enum

I have an enum:
public enum UnitOfMeasure
{
Meters,
Kilometers,
Yards,
Miles,
Time
}
and I want to bind it to a ListBox (actually a Telerik RadListPicker, but it works the same):
<telerikInput:RadListPicker
Header="Measure work in:"
ItemsSource="{Binding WorkUnitOfMeasure}"
HeaderStyle="{StaticResource HeaderStyle}"
x:Name="workUnitsListPicker"
Margin="18">
</telerikInput:RadListPicker>
My View Model:
/// <summary>
/// The <see cref="WorkUnitOfMeasure" /> property's name.
/// </summary>
public const string WorkUnitOfMeasurePropertyName = "WorkUnitOfMeasure";
private ObservableCollection<Enum<UnitOfMeasure>> _workUnitOfMeasure;
/// <summary>
/// Gets the WorkUnitOfMeasure property.
/// Changes to that property's value raise the PropertyChanged event.
/// This property's value is broadcasted by the Messenger's default instance when it changes.
/// </summary>
public ObservableCollection<Enum<UnitOfMeasure>> WorkUnitOfMeasure
{
get
{
return _workUnitOfMeasure;
}
set
{
if (_workUnitOfMeasure == value)
{
return;
}
var oldValue = _workUnitOfMeasure;
_workUnitOfMeasure = value;
RaisePropertyChanged(WorkUnitOfMeasurePropertyName);
}
}
And in my constructor I have tried variations of something like this:
WorkUnitOfMeasure = new ObservableCollection<Enum<UnitOfMeasure>>();
I can't seem to get the listbox to bind to Enum. I know I'm missing something simple, but I can't figure it out.
I believe it should be an
ObservableCollection<UnitOfMeasure>
not
ObservableCollection<Enum<UnitOfMeasure>
If not what error are you seeing?
If you are binding the single enum items to listbox:
Following code may help you:
List<string> newList = new List<string>();
for (int i = 0; i <= (int)UnitOfMeasure.Time; i++)
newList.Add(Enum.GetName(typeof(UnitOfMeasure), i));
SampleList.ItemsSource = newList;

'Expected class, delegate, enum, interface,or struct' in XNA 4.0?

Here's my code;
I've looked it up online, but still unable to fix it.
Please show me a fixed version of the code, thank you so much! I've been staring at the screen for half 'n' hour and still can't figure this out!
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D car1Texture;
Vector2 car1Position = new Vector2(200f, 100f);
Texture2D background;
Rectangle mainFrame;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//Change the resolution to 800x600
graphics.PreferredBackBufferWidth = 1000;
graphics.PreferredBackBufferHeight = 800;
graphics.ApplyChanges();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the background content.
background = Content.Load<Texture2D>("roadscan");
// Set the rectangle parameters
mainFrame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
spriteBatch = new SpriteBatch(GraphicsDevice);
car1Texture = Content.Load<Texture2D>("car1");
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState keyboard = Keyboard.GetState();
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
if (keyboard.IsKeyDown(Keys.Left) || gamePad.DPad.Left == ButtonState.Pressed)
{
ballPosition.X -= 3f;
}
if (keyboard.IsKeyDown(Keys.Right) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.X += 3f;
}
if (keyboard.IsKeyDown(Keys.Up) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y += 3f;
}
if (keyboard.IsKeyDown(Keys.Down) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y -= 3f;
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Draw the background.
// Start building the sprite.
spriteBatch.Begin();
// Draw the background.
spriteBatch.Draw(background, mainFrame, Color.White);
// End building the sprite.
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
Remove the extra brace above the UnloadContent method
Right here:
// TODO: use this.Content to load your game content here
}<-------Delete this guy!!!
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
You've got one to many closing curly braces.
protected override void LoadContent()
{
// snip
} //close method
// TODO: use this.Content to load your game content here
} //close class
You accidentally close the class half way through, just removing the curly brace will fix things. This is common when you haven't shrunk or removed the default comment blocks as they tend to get in the way after you've learnt what all the basic methods do.

Sending an email message in WP7 on unhandled exception

Is there a way to send a email message with the details when an unhandled exception occurs in a WP7 app?
I've seen the WCF logging/email sending approach, but I don't have a place to publicly host a service.
Take a look at Andy Pennell's "little watson." It works pretty well.
The only other option you have is to use the EmailComposeTask. This leaves you at the mercy of the user to send the message, because it will give you their email address, but its the only way currently to send a mail message without a WCF service.
Example 1:
private void emailAddressChooserTask_Completed(object sender, EmailResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show("Selected email :" + e.Email);
//in-real world application user expect to select it from his contacts and if not found enter manually.
//EmailComposeTask emailComposeTask = new EmailComposeTask();
//emailComposeTask.To = e.Email;
//emailComposeTask.To = saveEmailAddressTask.Email;
//emailComposeTask.Body = "WP7 Emails Demo";
//emailComposeTask.Cc = "testmail2#test.com";
//emailComposeTask.Subject = "Windows Phone 7";
//emailComposeTask.Show();
}
}
Example 2:
private void composeMail_Click(object sender, RoutedEventArgs e)
{
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "chris#example.com";
emailComposeTask.To = saveEmailAddressTask.Email;
emailComposeTask.Body = "WP7 Emails Demo";
emailComposeTask.Cc = "testmail2#test.com";
emailComposeTask.Subject = "Windows Phone 7";
emailComposeTask.Show();
}
Souce: http://www.windowsphonegeek.com/articles/1-how-to-perform-email-tasks-in-a-wp7-app
I use the following in my app, it is a little convoluted but works. The following code is in App.xaml.cs:
/// <summary>
/// Indicates whether the application needs to quit due to a previous exception
/// </summary>
private static bool _appMustQuit = false;
/// <summary>
/// Exception class that will be unhandled causing application to quit
/// </summary>
private class AppQuitException : Exception {}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException( object sender,
ApplicationUnhandledExceptionEventArgs e )
{
if( ( e.ExceptionObject is AppQuitException ) == false ) {
Debug.WriteLine( "App:Application_UnhandledException - " + e.ToString() );
if( Debugger.IsAttached ) {
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
// Compose error report
StringBuilder report = new StringBuilder( 1024 );
report.AppendFormat( "{0}", LangResources.ErrorReportContent );
report.AppendFormat( "Message: {0}\n", e.ExceptionObject.Message );
if( e.ExceptionObject.InnerException != null ) {
report.AppendFormat( "Inner: {0}\n", e.ExceptionObject.InnerException.Message );
}
report.AppendFormat( "\nStackTrace: {0}\n", e.ExceptionObject.StackTrace );
if( MessageBox.Show( "Unexpected Error", "Error", MessageBoxButton.OKCancel )
== MessageBoxResult.OK ) {
e.Handled = true;
// Email the error report
Tasks.ComposeEmail( "\"Developer\" <your#emailaddress.com>", "MyApp Error Report",
report.ToString() );
_appMustQuit = true;
}
}
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated( object sender, ActivatedEventArgs e )
{
var state = PhoneApplicationService.Current.State;
if( state.ContainsKey( "AppMustQuit" ) ) {
throw new AppQuitException();
} else {
// Restore other tombstoned variables
}
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated( object sender, DeactivatedEventArgs e )
{
if( _appMustQuit ) {
state["AppMustQuit"] = true;
} else {
// Save other variables for tombstoning
}
}
Tasks is a static class with a bunch of helper functions from the Microsoft.Phone.Tasks namespace.
using Microsoft.Phone.Tasks;
namespace MyApp
{
/// <summary>
/// Utility class for performing various phone tasks
/// </summary>
public static class Tasks
{
/// <summary>
/// Composes an email using the specified arguments
/// </summary>
/// <param name="to">The recepient(s) of the email</param>
/// <param name="subject">Email subject</param>
/// <param name="body">Email contents</param>
/// <param name="cc">The recipient(s) on the cc line of the email</param>
public static void ComposeEmail( string to, string subject, string body,
string cc = "" )
{
var task = new EmailComposeTask() {
To = to,
Subject = subject,
Body = body,
Cc = cc,
};
task.Show();
}
}
}
To explain the code a little, using the EmailComposeTask causes your app to be tombstoned. Since I do not want to continue executing the app after an unhandled exception I save a boolean to the PhoneApplicationService's State dictionary so that after the user sends the email, when the app re-awakens I can look for this boolean and throw another exception that is intentionally unhandled. This second exception causes the app to quit.
If somebody is looking for Email messages in background (without loading EmailComposeTask) then MailMessage might be the best option so for, it also allows attachments which EmailComposeTask does not supports at all. it would allow you to send emails without bothering the users in background using your own gmail or anyother account.
you can get it from NuGet Install-Package MailMessage to give it a try, However I haven't used it myself so may be you need to buy it from authors site its only in $29.99 its really worth paying for it. Free version also works but it shows a popup message in application before sending an email.

Resources