silverlight enabled wcf service retuning value - silverlight

This is my service which checks username and password
[OperationContract]
public bool LoginCheck(string username, string password)
{
RoadTransDataContext db = new RoadTransDataContext();
var _Pass = (from d in db.users where d.username == username select d.password).SingleOrDefault();
if (_Pass == password)
{
return true;
}
else
{
return false;
}
}
And this is child window
private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e)
{
_Log = e.Result;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient();
webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted);
webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password);
if (_Log == true)
{
this.DialogResult = true;
this.Close();
}
}
problem is that LoginCheckCompleted method is calling when OKButton_Click method finished. so if it input correct username, pass and press button it doing nothing if i click onece again window closing

Silverlight uses the async model of invoking web services and it takes some time to wait until the response is returned. In your example the assigment _Log = e.Result; will be called, let's assume, after 1-2 seconds, whereas the check if (_Log == true) will be called immideately and of course before the assignment.
That's why you should put all the necessary code in the callback and remove all the code after the async call. I've fixed it for you:
private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e)
{
_Log = e.Result;
if (_Log == true)
{
this.DialogResult = true;
this.Close();
}
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient();
webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted);
webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password);
}

Related

Stop further link navigating inside web browser control [WPF]

Hello is there something similar to AllowNavigation like in WinForms?
My search didn't yield any satisfying result.
Basically I'm trying to open a webpage inside new wpf window and stop user from clicking random links on that webpage and navigating further.
Saw something with
void browser1_Navigating(object sender, NavigatingCancelEventArgs e)
{
e.Cancel = true;
}
Rest of the code is :
public Popup_webpage(string ime)
{
InitializeComponent();
browser1.LoadCompleted += browser1_LoadCompleted;
browser1.Navigating += browser1_Navigating;
string uri = "www.google.com"
browser1.Navigate(new Uri(uri, UriKind.Absolute));
}
void browser1_LoadCompleted(object sender, NavigationEventArgs e)
{
browser1.Visibility = Visibility.Visible;
}
But it just makes my webpage not display ?
Thanks
Try this:
Once you have loaded your page, then you assign the browser_Navigating event handler.
public Popup_webpage(string ime)
{
InitializeComponent();
browser1.LoadCompleted += browser1_LoadCompleted;
string uri = "www.google.com"
browser1.Navigate(new Uri(uri, UriKind.Absolute));
browser1.Navigating += browser1_Navigating;
}
void browser1_LoadCompleted(object sender, NavigationEventArgs e)
{
browser1.Visibility = Visibility.Visible;
}
void browser1_Navigating(object sender, NavigatingCancelEventArgs e)
{
e.Cancel = true;
}

Cannot set the value of a global variable

Im pretty new to programming, but im very eager to get more into this stuff, and in particular, c#. I have a made some code for an autotyper (spam bot if i may), only to be used as a goal for me to create. Essentially, what i want the program to do, is as following:
When i start my Form1, the global variable "_timerValue" is set to
1000
When i hit Start button, the text from the textbox on will be sent at
the interval of "_timerValue"
When i hit the Speed button, Form2 will show.
When i hit very fast, "_timerValue" is set to 5000 (testing purposes)
Form1 code:
public partial class Form1 : Form
{
static class TimerIntervalValue
{
Form2 f2 = new Form2();
TimerIntervalValue = f2._timerValue;
}
public Form1()
{
InitializeComponent();
f2._timerValue = "1000";
}
public void timer1_Tick(object sender, EventArgs e)
{
SendKeys.Send(textBox1.Text);
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
MessageBox.Show(f2._timerValue);
timer1.Interval = Convert.ToInt32(f2._timerValue);
if (timer1.Enabled == false)
{
timer1.Enabled = true;
textBox1.Enabled = false;
button1.Text = ("Stop");
}
else if (timer1.Enabled == true)
{
timer1.Enabled = false;
textBox1.Enabled = true;
button1.Text = ("Start");
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
}
Form2 code:
public partial class Form2 : Form
{
public string TimerValue;
public string _timerValue
{
get { return TimerValue; }
set { TimerValue = value; }
}
public Form2()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2._timerValue = "5000";
}
}
I originally tried to create a Form2 instance just under "InitializeComponent();" in Form1, but that didnt seem to be accessible through the other funtions.
I just know its something very simple like im using the wrong class to create the Form2 instance or something like that ...
Anyway, thank you in advance
Just mark TimerValue and _timerValue as static. Then you don't need to use
Form2 f2 = new Form2(); or Form2 frm2 = new Form2();
anymore. In Form 1, just use Form2._timerValue instead of f2._timerValue. In Form 2, just change:
public void button1_Click(object sender, EventArgs e)
{
_timerValue = "5000";
}

this is not waiting form, but completion notification of thread is required

private void btnSend_Click(object sender, RoutedEventArgs e)
{
Button obj=(Button)sender;
obj.Content="Cancel";
SendImage send = new SendImage();
Thread t = new Thread(send.Image);
t.Start();
//run separate thread.(very long, 9 hours)
//so dont wait.
//but the button should be reset to obj.Content="Send"
//Can I do this?
}
I want the button to be reset to "Send" (after completion of thread). But form should not wait. Is this possible?
You can do this more elegantly using the BackgroundWorker class.
XAML for the Button:
<Button x:Name="btnGo" Content="Send" Click="btnGo_Click"></Button>
Code :
private BackgroundWorker _worker;
public MainWindow()
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.WorkerSupportsCancellation = true;
_worker.WorkerReportsProgress = true;
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
_worker.RunWorkerCompleted += delegate(object completedSender, RunWorkerCompletedEventArgs completedArgs)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = "Send";
}));
};
_worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = "Cancel";
}));
SendImage sendImage = args.Argument as SendImage;
if (sendImage == null) return;
var count = 0;
while (!_worker.CancellationPending)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = string.Format("Cancel {0} {1}", sendImage.Name, count);
}));
Thread.Sleep(100);
count++;
}
};
if (_worker.IsBusy)
{
_worker.CancelAsync();
}
else
{
_worker.RunWorkerAsync(new SendImage() { Name = "Test" });
}
}
Make the Button a member of your Window/UserControl class (by giving it a Name in XAML). When the thread eventually finishes, do this before returning from the thread method:
myButton.Dispatcher.BeginInvoke(
(Action)(() => myButton.Content = "Send"));

call a Async Method multiple times problem in silverlight

Hi i am calling a Async method with different parameter value multiple times giving same result in completed event.
client.ListAllLookupValuesByTypeCompleted += client_ListAllAddressFormatCompleted;
client.ListAllLookupValuesByTypeAsync("AddressFormat");
client.ListAllLookupValuesByTypeCompleted += client_ListAllPhoneFormatCompleted;
client.ListAllLookupValuesByTypeAsync("PhoneFormat");
void client_ListAllAddressFormatCompleted(object sender, ListAllLookupValuesByTypeCompletedEventArgs e)
{
cmbAddressFormat.ItemsSource = e.Result;
}
void client_ListAllPhoneFormatCompleted(object sender, ListAllLookupValuesByTypeCompletedEventArgs e)
{
cmbPhonePrintFormat.ItemsSource = e.Result;
}
please help me.
Thanks.
You can create new instance of client.
...
var client = new XyzClient();
client.ListAllLookupValuesByTypeCompleted += client_ListAllAddressFormatCompleted;
client.ListAllLookupValuesByTypeAsync("AddressFormat");
client = new XyzClient();
client.ListAllLookupValuesByTypeCompleted += client_ListAllPhoneFormatCompleted;
client.ListAllLookupValuesByTypeAsync("PhoneFormat");
...
void client_ListAllAddressFormatCompleted(object sender, ListAllLookupValuesByTypeCompletedEventArgs e)
{
cmbAddressFormat.ItemsSource = e.Result;
}
void client_ListAllPhoneFormatCompleted(object sender, ListAllLookupValuesByTypeCompletedEventArgs e)
{
cmbPhonePrintFormat.ItemsSource = e.Result;
}
Another solution would be to make the second call in the handler of the first one (probably creating new client instance anyway).

Cannot Get Threading right on wpf UI

I am building a proof of concept application before it gets rollout to the real one.
Scenario
I should be able to stop processing in the middle of it.
Toolbar 2 buttons "Start" & "Stop"
User press start and it process a long running task.
User decides out of the blue to stop the task.
I cannot seem to get threading right!! I cannot press stop as it's waiting for the long running task as if the long running task is actually running on UI thread and not as intented on background thread.
What Am I doing wrong can you spot it? Thanks for your help
public partial class TestView : UserControl
{
private readonly BackgroundWorker _worker;
public TestView
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.RunWorkerCompleted += RunWorkerCompleted;
_worker.DoWork+=DoWork;
_worker.WorkerReportsProgress = true;
_worker.ProgressChanged+=_worker_ProgressChanged;
_worker.WorkerSupportsCancellation = true;
}
static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + e.Error);
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result);
}
}
private delegate void SimpleDelegate();
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
_worker.ReportProgress(i, DateTime.Now);
// SimpleDelegate simpleDelegate = () => txtResult.AppendText("Test" + System.Environment.NewLine);
//Dispatcher.BeginInvoke(DispatcherPriority.Normal, simpleDelegate);
}
MessageBox.Show("I have done it all");
}
private void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
DateTime time = Convert.ToDateTime(e.UserState);
txtResult.AppendText(time.ToLongTimeString());
txtResult.AppendText(Environment.NewLine);
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
_worker.RunWorkerAsync();
}
private void BtnStop_Click(object sender, RoutedEventArgs e)
{
_worker.CancelAsync();
MessageBox.Show("Process has been stopped!");
}
}
You run a very tight loop inside of DoWork and continuously push Invoked ProgressUpdates to the Main Thread. That will make it sluggish.
But the real problem is that DoWork has to cooperate in Cancellation:
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
if (_worker.CancelationPending)
{
e.Cancel = true;
break; // or: return to skip the messagebox
}
_worker.ReportProgress(i, DateTime.Now);
}
MessageBox.Show("I have done it all"); // remove or make depend on Cancelled
}

Resources