problem with lock in thread &managment lock - thread-safety

i have problem in this code in the comment area "hang the form"
my program will hang there!!!! what is problem??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication28
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
BackgroundWorker backgw = new BackgroundWorker();
private void button1_Click(object sender, EventArgs e)
{
backgw.DoWork += new DoWorkEventHandler(k_DoWork);
ParameterizedThreadStart start = new ParameterizedThreadStart(startthread);
System.Threading.Thread u;
int i = 0;
while (i < 100)
{
//u = new System.Threading.Thread(start);
//u.Start(i); //1.with thread way
backgw.RunWorkerAsync(i); //2.with backgw way
Thread.Sleep(1000);
lock (y)
{
Thread.Sleep(1000);
}
lock(h)
i++;
}
}
delegate void j(int h);
j b;
object h = new object();
object y = new object();
void startthread(object m)
{
Monitor.Enter(h);
Monitor.Enter(y);
p1((int)m);
Monitor.Exit(h);
}
void p1(int h)
{
b = delegate(int q)
{
label1.Text = string.Format("Step is :{0}", h.ToString());
};
Monitor.Exit(y);
label1.Invoke(b); //hang the form????
}
void k_DoWork(object sender, DoWorkEventArgs e)
{
Monitor.Enter(h);
Monitor.Enter(y);
p1((int)e.Argument);
Monitor.Exit(h);
}
}
}

Invoke waits for the function to return. The UI thread will be running the loop for a few minutes, the worker thread will be waiting for the UI thread to invoke and return.
Use BeginInvoke to put the task on the UI thread without blocking.

Related

While navigating to Register Player details screen, throws object reference error in Xamarin.Forms

On click on the Register_OnClicked button in the Xamarin.Forms app, system throws System.NullReferenceException: Object reference not set to an instance of an object This button will allow app to navigate to Player Register details screen from where the system save data. Could someone please advise about the cause of the error? I couldn't figure out the reason for that error yet, have restarted the app, perform the clean buildoperation, but still the same.
Database library using : sqlite-net-pcl
//MainPage.xaml.cs details
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public async void NavigateButton_OnClicked(object sender, EventArgs e)
{
var tabbedPage = new TabbedPage();
tabbedPage.Children.Add(new Home("Welcome"+' '+emailEntry.Text+' '+",have a nice day!"));
tabbedPage.Children.Add(new Map());
tabbedPage.Children.Add(new Settings());
await Navigation.PushAsync(tabbedPage);
}
public async void Register_OnClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new Register());
}
}
Register.xaml.cs details where the saving of Player details:
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Linq;
namespace soccerapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Register : ContentPage
{
public SQLiteConnection conn;
public Register()
{
InitializeComponent();
conn = DependencyService.Get<Isqlite>().GetConnection();
conn.CreateTable<PlayerDetails>();
}
public void RegisterSave_OnClicked(object sender, EventArgs e)
{
PlayerDetails playerDetails = new PlayerDetails();
playerDetails.FullName = fullNameEntry.Text;
playerDetails.Mobile = mobileEntry.Text;
playerDetails.SoccerPosition = soccerpostionEntry.Text;
playerDetails.Email = emailRegister.Text;
playerDetails.Password = passwordEntry.Text;
int x = 0;
try
{
x = conn.Insert(playerDetails);
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
DisplayAlert("Registration", "Player Registered Successfully", "Cancel");
}
else
{
DisplayAlert("Registration Failled!!!", "Please try again", "ERROR");
}
}
}
}
SQlite Connection class created and return connection:
public class SQliteDroid : Isqlite
{
public SQLiteConnection GetConnection()
{
var dbase = "soccerpep";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(dbpath, dbase);
var connection = new SQLiteConnection(path);
return connection;
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nZ8GZ.png
Error details from Debug > Windows > Call Stack add below;
0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal C#
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException C#
0x20 in Android.Runtime.DynamicMethodNameCounter.43 C#
0x12 in System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw C#
0x6 in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0 C#
0xC in Android.App.SyncContext. C#
0xE in Java.Lang.Thread.RunnableImplementor.Run C#
0xA in Java.Lang.IRunnableInvoker.n_Run C#
0x11 in Android.Runtime.DynamicMethodNameCounter.43 C#
Debug through the Constructor for your Register page, and the GetConnection method of your SqliteDroid class.
I've seen hard-to-find errors like this when the Dependency Injection fails. This could be either because of an error in GetConnection, or because SqliteDroid has not been registered in your DependencyService.

Insert, Update, Delete query using LINQ in datagridview in C# Windows Programming?

Scenario: There is following controls in the form:
datagridview, textbox1, textbox2, button(save,edit,update,delete)
1.By clicking on save button, data should be updated into datagridview at run-time.
2.By selecting complete row and clicking on edit button, data should be retrieved into textboxes.
3.By clicking on Update button, that data should be updated.
4.By selecting a complete row, the row should be deleted.
This is my code.
I hope it will help you
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LINQ_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
LINQtestDataContext dc = new LINQtestDataContext();
public void show_data()
{
dataGridView1.DataSource = (from t in dc.LinqTests
select t);
}
public void insert_data()
{
try
{
LinqTest tbl = new LinqTest
{
ID=Convert.ToInt32(textBox_id.Text),
Name=textBox_name.Text
};
dc.LinqTests.InsertOnSubmit(tbl);
dc.SubmitChanges();
MessageBox.Show("Data Inserted!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void update_data()
{
try
{
LinqTest tbl = dc.LinqTests.Single(x=>x.ID==Convert.ToInt32(textBox_id.Text));
tbl.Name = textBox_new_name.Text;
dc.SubmitChanges();
MessageBox.Show("Data Updated!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void delete_data()
{
try
{
LinqTest tbl = dc.LinqTests.Single(x => x.ID == Convert.ToInt32(textBox_id.Text));
dc.LinqTests.DeleteOnSubmit(tbl);
dc.SubmitChanges();
MessageBox.Show("Data Deleted!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
show_data();
}
private void button_insert_Click(object sender, EventArgs e)
{
insert_data();
}
private void button_update_Click(object sender, EventArgs e)
{
update_data();
}
private void button_delete_Click(object sender, EventArgs e)
{
delete_data();
}
}
}

How to make back button return to the system Windows Phone

I have a small app there is 3 seconds intro page, then the content page. When I push back button I go back to the intro screen, but I think I should go back to the system. How to do it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
namespace RSS {
public partial class FeedPage : PhoneApplicationPage {
public FeedPage() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(PhonePage1_Loaded);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
clearBackStack();
base.OnNavigatedTo(e);
}
void clearBackStack() {
while (this.NavigationService.BackStack.Any()) {
this.NavigationService.RemoveBackEntry();
}
}
void PhonePage1_Loaded(object sender, RoutedEventArgs e) {
// clearBackStack();
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.carmagazine.co.uk/Shared/Handlers/RssHandler.ashx?&N=190&Ns=P_Publication_Date|1&?"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
SyndicationFeed feed;
try {
using (XmlReader reader = XmlReader.Create(e.Result)) {
feed = SyndicationFeed.Load(reader);
lista.ItemsSource = feed.Items;
}
} catch (WebException we) { MessageBox.Show("Internet connection is down.");}
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e) {
WebBrowserTask webBrowserTask = new WebBrowserTask();
String url = (String)((Button)sender).Tag;
webBrowserTask.Uri = new Uri(url);
webBrowserTask.Show();
}
}
}
You should clear the BackStack in the OnNavigateTo method of your content page
while (this.NavigationService.BackStack.Any())
{
this.NavigationService.RemoveBackEntry();
}
The following code is the best practice for the back button key press.
protected override void OnBackKeyPress(CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
base.OnBackKeyPress(e);
}
This ensures that your application will exit and return to the main screen on pressing the BackKey.

Taking screenshot of windows phone 7.5 and sending over through TCP

i am stuck on how to take a screenshot of my windows phone 7.5 and sending it over TCP. i have no experience in doing socket program and I/O and am doing what i can through tutorials over the internet. This is what i have done.
From the codes below i am stuck in how i can send the writeableBitMap over TCP encoded as a Jpeg periodically running in the WP7.5 background, whereby a program on a desktop will receive it as a jpeg image so it can be displayed creating a windows phone to desktop streaming effect.
my mainPage of my windows phone 7.5 application using a library i have created from a tutorial for taking care of the sockets connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone;
using System.Windows.Media;
using System.IO;
namespace helloworld
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
SocketLibrary.socketLib sl = new SocketLibrary.socketLib();
private string hostIP = "127.0.0.1";
public MainPage()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
bool retVal;
retVal = sl.EstablishTCPConnection(hostIP);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
var ms = new MemoryStream();
// Send the picture.
bmpCurrentScreenImage.SaveJpeg(ms, bmpCurrentScreenImage.PixelWidth, bmpCurrentScreenImage.PixelHeight, 0, 90);
ms.Seek(0, SeekOrigin.Begin);
retVal = sl.Send(ms);
sl.CloseSocket();
}
}
}
the socket library
namespace SocketLibrary
{
public class socketLib
{
Socket s = null;
static ManualResetEvent done = new ManualResetEvent(false);
private Int16 portNo = 3334;
public socketLib()
{
}
public bool EstablishTCPConnection(string host)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(host, portNo);
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
done.Reset();
s.ConnectAsync(socketEventArg);
return done.WaitOne(10000);
}
public bool Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (s != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = s.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
socketEventArg.SetBuffer(msData, 0, msData.Length);
done.Reset();
s.SendAsync(socketEventArg);
return done.WaitOne(10000);
}
return false;
}
public void CloseSocket()
{
if (s != null)
{
s.Close();
}
}
}
}
check this
http://www.charlespetzold.com/blog/2011/05/Windows-Phone-Screen-Shots.html
http://blog.galasoft.ch/archive/2010/12/28/taking-a-screenshot-from-within-a-silverlight-wp7-application.aspx

Detect Autoscrollposition value change in panel

How to detect if the Autoscrollposition value changes in the panel1?
For example,
textbox1 and textbox2.
which added in panel1. The autoscroll property is set to true.
I am only interested in detecting when the value of panel autoscrollposition changes.
The above for dynamic textboxes which are incremented.
Software in use: C#, Visual Studio 2005.
The Component required for it. is:
ListBox1
ListBox2
Panel
Button.
The Namespace for Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
Here is the Complete Solution Code:
namespace detectpanelvalue
{
public partial class Form1 : Form
{
private Point tbpoint = new Point(10, 14);
private Point tbbpoint = new Point(300, 14);
private ArrayList arylst;
private ArrayList arylst1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Paint += new PaintEventHandler(panel1_Paint);
}
void panel1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Point pnlpt;
pnlpt = panel1.AutoScrollPosition;
if (tbpoint !=null || pnlpt != null )
{
pnlpt = tbpoint;
}
arylst1 = new ArrayList();
arylst1.Add(pnlpt);
}
private void runtime()
{
foreach (Point pt in arylst)
{
listBox1.Items.Add(pt);
}
foreach (Point ptt in arylst1)
{
listBox2.Items.Add(ptt);
}
}
private void button1_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Location = tbpoint;
this.panel1.Controls.Add(tb);
tbpoint.Y += 30;
TextBox bb = new TextBox();
bb.Location = tbbpoint;
this.panel1.Controls.Add(bb);
tbbpoint.Y += 30;
arylst = new ArrayList();
arylst.Add(tbpoint);
runtime();
}
}
}
It is helpful for adjust the panel autoscrollposition.

Resources