|
|
Hi
I am trying to create a TCP Socket Listener that installes as a windows service. I have created a console applications that works file, see code. But after reading pages and pages on how to create a window service I am stuck. It is how to handle start and stop of the service that is my biggest problem. Does any one have any ideas/tips?
Regards
Tobben
public class SynchronousSocketListener
{
public static string data = null;
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("=)") > -1)
{
System.Diagnostics.Process.Start(@"C:\Windows\System32\Notepad.exe");
break;
}
if (data.IndexOf("=(") > -1)
{
System.Diagnostics.Process.Start(@"C:\Windows\System32\cmd.exe");
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
|
|
|
|
|
I'm assuming, since you posted the code that works and not the code you are having problems with, is that you are calling StartListening in the OnStart method of the service.
Here is a Walkthrough for creating a Windows Service[^]
Note what it says in the note under the OnStart method:
Quote: A service application is designed to be long running. Therefore, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system after the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.
Your code does exactly that, it loops forever (while(true) ).
So, how would you take care of that? Well you can either use the asynchronous methods instead of the synchronous ones, see Socket.BeginReceive[^] or you can create a new thread (I'd use BackgroundWorker[^]).
Remember to keep a way to stop your service, so if you use the asynchronous socket methods you will have to be able to cancel the operation, or if you use background worker you will need to have some kind of flag to exit your function.
|
|
|
|
|
Hi I am using System.Timer class in my xaml.cs class.
my MainWindow Constructor looks like as below
public MainWindow()
{
Timer timer = new Timer(3000);
InitializeComponent();
timer.Interval = 3.0;
timer.Elapsed += new System.Timers.ElapsedEventHandler(LoadObjectValue);
}
OnButton Click i am starting the Timer
private void Button_Click(object sender, RoutedEventArgs e)
{
timer.Enabled=true;
}
My LoadObjectValue method looks like below
void LoadObjectValue(object sender, ElapsedEventArgs e)
{
dataGrid.ItemsSource = DeviceObjectVM.DeviceObjectCollection; //ObservableCollection
}
But when i am executing i am getting Exception: "Calling Thread can not access the because it owns by the other thread". It looks like my dataGrid is owns by the UI Thread and my Timer is running on the other thread. Which does not have access to dataGrid. How Can i set ItemSource of datagrid using Timer.
Please Help.
|
|
|
|
|
You can use the Dispatcher to Invoke the ItemsSource binding.
|
|
|
|
|
Your timer setup code is a bit messed up. You first create a new Timer with an interval of 3 seconds, then a couple of lines later you change the interval to 3 milliseconds. I don't think that's correct as you'd be forcing the grid to rebind and probably redraw itself nearly continuously.
|
|
|
|
|
for a quick workaround use CheckForIllegalCrossThreadCalls=false on your control/form.
|
|
|
|
|
Thanks Guys for your quick help.
The problem is solved using DispatcherTimer.
Below is the code: of MainWindow.xaml.cs class
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(3);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
DeviceObjectVM deviceObjectVM = new DeviceObjectVM();
dgDeviceValue3.ItemsSource = deviceObjectVM.DeviceObjectCollection;
}
}
Where DeviceObjectVM is my viewmodel class and dgDeviceValue3 is my datagrid. which is bound to the vm's observablecollection.
Using DispatcherTimer i was able to update my UI Control dgDeviceValue3.
|
|
|
|
|
Hi
I have a rather large table in sql server 2012 which I am pulling into a C# winform app datagridview. I am having problem with getting the navigator to work.
Background
I am only using a single table
I am using the sortable example here
<a href="http://www.codeproject.com/Articles/31418/Implementing-a-Sortable-BindingList-Very-Very-Quic">Implementing a Sortable BindingList Very, Very Quickly</a>
Here is my linq
dbcontext = new LOBappsContext();
dbcontext.myTable.Load();
this.myTableBindingSource.DataSource = dbcontext.myTable.Local.ToBindingList();
//
Cursor.Current = Cursors.WaitCursor;
strSubvertical = this.cboSubverticalOnly.SelectedItem.ToString();
var theGridData = new List<LOBapp.myTable>();
theGridData = (
from g in dbcontext.myTable
where g.System_and_Projects == strSubvertical
orderby g.Project_Name
select g
).ToList();
var sortableCollection = new customSortableBindingList<myTable>(theGridData);
BindingSource bs = new BindingSource();
bs.DataSource = sortableCollection;
this.myTableBindingNavigator.BindingSource = bs;
this.myTableDataGridView1.DataSource = sortableCollection;
myTableBindingNavigator.Update();
myTableBindingNavigator.Refresh();
hideGridColumns();
Cursor.Current = Cursors.Arrow;
The problem
When I click on the left and right arrows (any arrow actually), the little triangle next to the selected row does not move to next row.
I would appreciate any help with this.
Thanks
|
|
|
|
|
Hi,
I think it's just a simple error in the wiring. Link the binding source to the datagridview and it should work correctly.
BindingSource bs = new BindingSource();
bs.DataSource = sortableCollection;
this.myTableBindingNavigator.BindingSource = bs;
this.myTableDataGridView1.DataSource = sortableCollection
this.myTableDataGridView1.DataSource = bs;
Alan.
|
|
|
|
|
|
Did you get a code signing certificate from a known certificate authority available on the web??
|
|
|
|
|
|
The only time I've ever had this happen is because the machine couldn't verify every certificate in the chain up to the root. It was because of Root Certificate Updates that were never applied to the machine.
|
|
|
|
|
what the solution I developed postscript printer driver package unsigned and I want to signed it.
what is your advice.
thanks
|
|
|
|
|
You're already signing it! I have no idea why your machine can't verify the certificate.
|
|
|
|
|
Thanks very much
I am looking for it and I will get the answer.
|
|
|
|
|
How to get the custom folder location in c3 winforms setup .
am creating setup for my project, i added a custom folder named as ABC,
default location:tempdir\UPLOAD
property:hi
so the folder(UPLOAD)is created in programfiles\companyname\manufacturer
how to get the location of that folder in c# program.
|
|
|
|
|
Member 10263519 wrote: property:hi Folder don't have a propertybag; what property are you referring to?
Member 10263519 wrote: how to get the location of that folder in c# program. By getting the "current directory"; that's the location from which your executable launches. Or ask the assembly where it's located. Your "upload" folder is a subfolder thereof.
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); You'd Path.Combine the "upload" part to that path, and then you have the complete path to that specific folder.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi,
How do I Deserialize this?
public static void SerializeToXML(MainWindow window, Canvas canvas, int dpi, string filename)
{
string mystrXAML = XamlWriter.Save(canvas);
FileStream filestream = File.Create(filename);
StreamWriter streamwriter = new StreamWriter(filestream);
streamwriter.Write(mystrXAML);
streamwriter.Close();
filestream.Close();
}
Thanks
|
|
|
|
|
Please do not cross post. You have received a response already How do I Deserialize?[^]
"Bastards encourage idiots to use Oracle Forms, Web Forms, Access and a number of other dinky web publishing tolls.", Mycroft Holmes[ ^]
|
|
|
|
|
Hi,
I have following 2 tables and displaying both Table columns on single form (c# WinForms). How can I save data in both tables at same time (retrive also) using OOPS.
Customer:
CustomerID
FirstName
MiddleName
LastName
Salutation
CustomerAddress:
CustomerID
HouseNo
Address1
Address2
City
State
Country
Pincode
Thanks
Gaurav
Gaurav Gupta
|
|
|
|
|
gaurav2325 wrote: using OOPS. What do you mean by "OOPS", and what does it have to do with saving data? If you want to save your data then it largely depends on where you are saving it. Is this to be serialised to a simple file, converted to XML, stored in a database etc?
Veni, vidi, abiit domum
|
|
|
|
|
As it stands, we can't really answer this: there are just too many options:
Text file
Custom content
Flat - line based
XML
CSV
Binary file
Database
SQL Server
MySql
SqLite
SQLCE
Access
Oracle
...
Excel
Application config file
Binary Serializer
XML Serializer
... Those are just some of the options - and each of them has many, many variants. Some are environment specific, others require external software.
You need to think about what you want to save, what you want to do with it once you have saved it, and what technologies you have available. To say nothing of what you understand and know about already!
Never underestimate the power of stupid things in large numbers
--- Serious Sam
|
|
|
|
|
You can't; databases don't speak OOPS, they speak SQL. You can "add" a record into both tables simultaneous by wrapping them in a transaction. Ditto for updates.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|