I have problem with logging operation in WP7. When I click LogInButton it doesn't gets value to prompt = e.Result in proxy. What can I do to wait until async call is ended? I though about Thread. Sleep but i suppose it isn't able to do in WP 7.
namespace WP7App
{
public partial class MainPage : PhoneApplicationPage
{
bool prompt;
// Constructor
public MainPage()
{
InitializeComponent();
}
// login operation
private void Log(string username, string passwd)
{
Service1Client proxy = new Service1Client();
proxy.LogInCompleted += new
EventHandler<LogInCompletedEventArgs>(proxy_LogInCompleted);
proxy.LogInAsync(username, passwd);
}
public void proxy_LogInCompleted(object sender, LogInCompletedEventArgs e)
{
prompt = e.Result;
}
//button action
void LogInButton_Click(object sender, RoutedEventArgs e)
{
if (LoginBox.Text == null) { MessageBox.Show("please fill login box"); }
if (PasswdBox.Password == null) { MessageBox.Show("enter your password"); }
string login = LoginBox.Text;
string passwd = PasswdBox.Password;
Log(login, passwd);
if (prompt == true)
{
NavigationService.Navigate(new Uri("/Pages/MainLogged.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("logging failed");
}
}
}
}
The only thing you should do is just provide user information, that some operation is still running.
If you really need that (the operation result is necessary for application) it can be done in a way, that blocks user from making another operations (like a fullscreen panel which should be shown just before starting async operation and closed when it's completed).
Related
I have class method and event
public class DefaultVariables
{
private DataTable SetDataFromSQL()
{
var Eventstatus = new BasicEventsHandlersArgs();
Eventstatus.Status.Task = BasicEventStatus.Busy;
Eventstatus.Status.Task_Status = "Please wait while we performing";
Eventstatus.Status.Task_CurrentProgress = "Verifying Steps...";
Eventstatus.Status.Task_TotalProgress = "Measuring Source Properties , Destinations Properties and someother(s)";
Raise_DefaultVariablesProgressUpdate(Eventstatus);
// Long running SQLs
}
public event EventHandler<BasicEventsHandlersArgs> Event_DefaultVariablesBasciProgress;
protected virtual void Raise_DefaultVariablesProgressUpdate(BasicEventsHandlersArgs e)
{
Event_DefaultVariablesBasciProgress?.Invoke(this, e);
}
}
and I call it in a Windows Forms app like this:
DefaultVariables variables = new DefaultVariables();
public EmployeeTag(string UserID)
{
InitializeComponent();
variables.Event_DefaultVariablesBasciProgress += Variables_Event_DefaultVariablesBasciProgress;
}
private void Variables_Event_DefaultVariablesBasciProgress(object sender, BasicEventsHandlersArgs e)
{
Application.DoEvents();
LabDepartmentCount.Text = e.Status.Task_Status.ToString();
labDesignationCount.Text = e.Status.Task_CurrentProgress.ToString(); ;
labEmCount.Text = e.Status.Task_TotalProgress.ToString();
// while (e.Status.Task != BasicEventStatus.Completed) { importToolStripMenuItem1.Enabled = false; }
if (e.Status.Task == BasicEventStatus.Busy)
{
importToolStripMenuItem1.Enabled = false;
}
if (e.Status.Task == BasicEventStatus.Completed)
{
importToolStripMenuItem1.Enabled = true;
}
}
private void importToolStripMenuItem1_Click(object sender, EventArgs e)
{
SetDataFromSQL();
}
The code is working and raising event as I expected, no error.
I just want to add button on GUI to pause, stop and continue between execution and want to control SetDataFromSQL, pause if there is long running code inside and continue from there.
Just like backgroundworker.cancel() method.
So how can I pause the execution from GUI button?
How can I pass pause flag to wait until I click continue?
Please help me out
I am developing a Client/server app.
In the Client app, I have a Main Form that is an MDI parent.
The Main Form has a Load event that creates a new instance of a Child Form and makes it visible.
This event also establishes Main as the MdiParent of Child.
The Child form is meant to be a sign-in screen.
From the child form, I create a reference to the parent, to be able to call methods from the parent.
However, upon executing the MdiParent.RequestConnection method, the GUI becomes stuck.
So I tried to execute the method from a Thread, but it is not accepting my declaration, even if I'm seemingly following the correct syntax.
I don't see what am I doing wrong. Please help
Main form
public partial class frmMainForm: Form
{
public frmMainForm()
{
InitializeComponent();
}
Thread runningClient;
public MyTcpClient client= new MyTcpClient ();
frmChildForm frmSignIn;
bool clientConnected;
private void frmMainForm_Load(object sender, EventArgs e)
{
clientConnected= false;
panelSidebar.Hide();
if(frmSignIn == null)
{
frmSignIn= new frmChildForm();
frmSignIn.MdiParent = this;
frmSignIn.Show();
}
}
public void TurnOnPanels()
{
panelSidebar.Visible = true;
panelSidebar.BringToFront();
}
public void RequestConnection(string username)
{
string serverRsp = client.Connect(username);
if(serverRsp.Equals("SUCCESS"))
{
MessageBox.Show("Signed In", "Welcome", MessageBoxButtons.OK, MessageBoxIcon.Information);
clientConnected = true;
frmSignIn.Close();
}
}
}
And my child form
public partial class frmChildForm : Form
{
frmMainForm frmParent;
Thread clientRunning;
public frmChildForm()
{
InitializeComponent();
frmParent= (frmMainForm)this.MdiParent;
}
private void frmSignIn_FormClosing(object sender, FormClosingEventArgs e)
{
frmParent= (frmMainForm)this.MdiParent;
frmParent.TurnOnPanels();
}
private void btnSignIn_Click(object sender, EventArgs e)
{
if (txtSignInUsername.Text.Equals(""))
{
MessageBox.Show("No empty fields.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
//This is where it fails
clientRunning= new Thread(new ParameterizedThreadStart(frmParent.RequestConnection);
//"No Overload for RequestConnection matches delegate ParameterizedThreadStart"
//If I try to include the parameter inside that call, I get a "waiting for method //name" syntax error message instead.
clientRunning.Start(txtSignInUsername.Text.ToUpper());
}
}
private void frmSignIn_Load(object sender, EventArgs e)
{
frmParent = (frmMainForm)this.MdiParent;
}
}
I also tried to do it from the main form by creating a thread inside RequestConnection, where it was supposed to execute client.Connect, but I got the same error.
Couple of things you need to fix
public void RequestConnection(object username) // changed parameter type
{
if (username == null)
throw new ArgumentNullException(nameof(username));
if (!(username is string))
throw new InvalidCastException("Expect string");// give proper message
string serverRsp = client.Connect(username.ToString());
if (serverRsp.Equals("SUCCESS"))
{
MessageBox.Show("Signed In", "Welcome", MessageBoxButtons.OK, MessageBoxIcon.Information);
clientConnected = true;
//this is require to solve cross-thread operation
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(delegate ()
{
frmSignIn.Close();
}));
else
frmSignIn.Close();
}
}
you need to get MdiParent in Form Load Event and remove from Constructor.
Your child form load event/ or use Parent changed Event
private void FrmLogin_Load(object sender, EventArgs e)
{
frmParent = (MainForm)this.MdiParent;
}
The ParametrizedThreadStart delegate actually takes an object as parameter.
So you must provide it a method that takes an object as parameter, not as string. In your method you will receive the object, check that it is a string then convert it to a string.
I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}
My application has a restricted access. I have a user/password box in a small dialog, and when logged-in, I'm loading a very big form with a tons of controls and several big grids. The whole InitializeComponent() take almost 10 secs to load without any data.
The issue is : how I could pre-run the Form constructor() while users are filling the two login fields ? If user is very slow and need >10 secs to complete authentification, it will be as quick as a wink to show application.
I think it is possible because it is two seperates top level windows, but I have no idea how to implement it. BackgroundWorker, new Thread, ... ? Any clue ?
SOLUTION :
Following Eamonn McEvoy's example, I added some fixes about my prerequesites : I wanted to show only login dialog, and if logged successful, I show the big form.
[STAThread]
static void Main()
{
Launcher context = new Launcher();
Application.Run(context);
}
public class Launcher : ApplicationContext
{
private BigForm _bigForm;
private Thread _loginThread;
private SynchronizeLogin _sharedLogin;
public class SynchronizeLogin
{
private bool _waited = false;
public bool IsInitialized
{
get // loginform should wait before closing until return true
{
lock (this)
{
return _waited;
}
}
set // must be set when bigform is initialized
{
lock (this)
{
_waited = value;
}
}
}
private DialogResult _logged = DialogResult.None;
public DialogResult loginResult
{
get // wait until loginform close
{
lock (this)
{
if (_logged != DialogResult.None)
return _logged;
else
{
Monitor.Wait(this);
return _logged;
}
}
}
set // set from loginform when closing
{
lock (this)
{
_logged = value;
Monitor.Pulse(this);
}
}
}
}
public Launcher()
{
// sync obj between forms
_sharedLogin = new SynchronizeLogin();
_loginThread = new Thread(new ThreadStart(LaunchLogin));
_loginThread.Start();
// first form
_bigForm= new BigForm(_sharedLogin);
_bigForm.Closed += new EventHandler(OnFormClosed);
// notify login thread that the main one is ready
// from now, the login form should be near closing
_sharedLogin.IsInitialized = true;
WaitLogon();
}
private void WaitLogon()
{
if (_sharedLogin.loginResult == DialogResult.OK)
{
_bigForm.LoginSuccessful(); // read and use auth session
_bigForm.Show();
}
else
{
// escape on user login form
// (other exit calls are not working in ctor)
Environment.Exit(42);
}
}
private void LaunchLogin()
{
// ask user
LoginDialog _loginForm = new LoginDialog (_sharedLogin);
_sharedLogin.loginResult = _loginForm.ShowDialog();
// userlogin form closed
// end only current thread
Application.ExitThread();
}
private void OnFormClosed(object sender, EventArgs e)
{
// big form closed
// end ApplicationContext globally
base.ExitThread();
}
}
You could create your login window in a new thread from your main windows constructor
using System.Threading;
private AuthSession _authSession;
public MainWindowConstructor()
{
Thread loginThread = new Thread(new ThreadStart(Login());
loginThread.Start();
//Continue initializing
}
private void Login()
{
LoginWindow loginWindow = new LoginWindow();
_authSession = loginWindow.GetAuthSession();
loginWindow.Close();
}
I have amended my code in App.xaml.cs
But i have an error at "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" (Placed at end of my App.xaml.cs)
The error is
"System.TimeSpan.FromMilliseconds(double) is a method but is used like a type"
System.Windows.Application.ApplicationLifetimeObjects is a property but is used like a type
Identifier expected
Invalid token '(' in a class, struct or interface member declaration
Method must have a return type
Below is the whole piece of my App.xaml.cs
namespace Alarm_Clock
{
public class GlobalData
{
public BitmapImage bitmapImage;
}
public partial class App : Application
{
public static GlobalData globalData;
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
public static string imagePath
{
//get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg"; }
get;
set;
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
//Global variables for the WriteableBitmap objects used throughout the application.
public static WriteableBitmap CapturedImage;
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
globalData = new GlobalData();
globalData.bitmapImage = new BitmapImage();
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// 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)
{
}
// 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)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
}
The pause just dont work in my code below.
This is my whole piece of code:
namespace Alarm_Clock
{
public partial class AlarmRing : PhoneApplicationPage
{
int songSelectedIndex;
public AlarmRing()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
//Get the DateTime.Now and place it into "timeTxtBlock" text block
timeTxtBlock.Text = DateTime.Now.ToShortTimeString();
//Read from Isolated storage queSetting.txt for the number of question to answer by the user
//Read from Isolated storage music.txt for the selected music to play when the alarm ring
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));
songSelectedIndex = Convert.ToInt16(readFile.ReadLine());
readFile.Close();
}
catch (Exception)
{
//If the user did not select the music to be played when the alarm ring it will play the first music by default
songSelectedIndex = 0;
}
using (var ml = new MediaLibrary())
{
//Play the music using media player from the song collection
FrameworkDispatcher.Update();
MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
MediaPlayer.Play(ml.Songs[songSelectedIndex]);
MediaPlayer.IsRepeating = true;
MediaPlayer.IsMuted = false;
MediaPlayer.IsShuffled = false;
MediaPlayer.IsVisualizationEnabled = false;
}
//Load code
loadtime();
}
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
void loadtime()
{
ringingAlarm.Begin();
//Get the DateTime.Now
String timeNow = DateTime.Now.ToShortTimeString();
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string labels in storage.GetFileNames("*"))
{
XElement _xml;
IsolatedStorageFileStream location = new IsolatedStorageFileStream(labels, System.IO.FileMode.Open, storage);
System.IO.StreamReader file = new System.IO.StreamReader(location);
_xml = XElement.Parse(file.ReadToEnd());
if (_xml.Name.LocalName != null)
{
XAttribute time = _xml.Attribute("time");
//Get the day of the week
String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");
if (timeNow == time.Value.ToString())
{
//"textBlock2" text block will display the label of the alarm
textBlock2.Text = labels;
}
}
file.Dispose();
location.Dispose();
}
}
}
string settingQues;
string settingQuesPassToGame;
string format;
string format1;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//Try get the value of number of question to be answered by the user that is pass over from setClockPage.xaml
if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))
settingQuesPassToGame = settingQues;
//Try get the format that is passed over
if (NavigationContext.QueryString.TryGetValue("format", out format))
format1 = format;
}
//Display a pop up message box with instruction
//And navigate to "Start.xaml"
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("To dismiss alarm" + System.Environment.NewLine + "- Answer selected IQ question" + System.Environment.NewLine + "- With all correct answer");
NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
public Visibility visible { get; set; }
}
}
When I place MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged); at the constructor there is an error.
The error is MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged) is a method but is use like a type.
I have changed my code but it still dosent work
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
You have to dispatch XNA Events manual in Windows Phone 7 Apps:
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
Add this to the end of your public App()
public App()
{
// Other stuff
// End
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
Complete Guide: http://msdn.microsoft.com/library/ff842408.aspx