C# namedpipes server/client - named-pipes

I am trying to learn how named pipes work so i can connect two c# applications.
I wrote two basic C# applications for testing but it doesn't work.
When i start the connection the first application freezes waiting for input and after i sent input from application 2 it defreezes and button1 shows. But nothing appears in the textbox, any ideas why?
Application1:
private void button1_Click(object sender, EventArgs e)
{
button1.Hide();
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe");
pipeServer.WaitForConnection();
StreamReader s = new StreamReader(pipeServer);
textBox1.Text = s.ReadToEnd();
pipeServer.Close();
button1.Show();
}
Application 2:
private void button1_Click(object sender, EventArgs e)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream("testpipe");
if (pipeClient.IsConnected != true) pipeClient.Connect();
StreamWriter sw = new StreamWriter(pipeClient);
sw.WriteLine("%s", textBox1.Text);
pipeClient.Close();
}

You're closing the NamedPipeClientStream before the StreamWriter has flushed any data to it. Therefore when you read data from the server stream, there's no data to read before the connection is closed, so you get an empty string.
You can fix this by properly disposing of the StreamWriter, as so:
private void button1_Click(object sender, EventArgs e)
{
using (var pipeClient = new NamedPipeClientStream("testpipe"))
{
if (pipeClient.IsConnected != true) pipeClient.Connect();
using (var sw = new StreamWriter(pipeClient))
{
sw.WriteLine("%s", textBox1.Text);
}
}
}
Alternatively, you can set AutoFlush to true on the StreamWriter.

Related

JavaFX FadeTransition end other SetVisbilities stop working when I call a new method

I want to make a FadeTransition within a pane in my application. Also, with this FadeTransition I set the visibitilitys of some JavaFX inside the pane to false, to make them disappear. It's working fine but, when I call another method that I named waitForResponse(event) after the FadeTransition it just stops working. I don't know why.
If I comment the waitForResponse(event) the FadeTransitions start working again.
I've thought that maybe it's a problem with the Socket and the InputStreamReader inside the waitForResponse(event), but I tested taking it out and making another basic thing inside this method still not work.
I've made other tests and dicovered that FadeTransition and other visibility changes doesn't work if I put any bufferedReader, other loops ou decision structures after it.
I just want to make a loading screen that prevent user to click anywhere until it's finished.
This is the code:
public class LoadingScreenController implements Initializable {
// Socket que vai ser utilizado nos vários métodos para conversar com o servidor
private Socket cliente;
// PrintWriter que vai ser utilizado pelos vários métodos e vai passar o
// argumento para o switch case
private PrintWriter pr;
private InputStreamReader in;
private BufferedReader bf;
private String option;
private String response;
#FXML
private Button refreshButton;
#FXML
private ImageView loadingGif;
#FXML
private Label txtLabel;
#FXML
private AnchorPane rootPane;
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void makeFadeInTransition() {
FadeTransition fadeTransition = new FadeTransition(Duration.seconds(1), loadingGif);
fadeTransition.setFromValue(0.0);
fadeTransition.setToValue(1.0);
fadeTransition.play();
}
#FXML
private void onRefreshButtonAction(ActionEvent event) {
if (option == null) {
throw new IllegalStateException("Entity was null");
}
refreshButton.setVisible(false);
refreshButton.setDisable(true);
txtLabel.setVisible(false);
makeFadeInTransition();
sendOptionToServer(event);
}
#FXML
private void sendOptionToServer(ActionEvent event) {
try {
cliente = new Socket("localhost", 3322);
pr = new PrintWriter(cliente.getOutputStream());
in = new InputStreamReader(cliente.getInputStream());
bf = new BufferedReader(in);
pr.println(option);
pr.flush();
waitForReponse(event, bf);
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForReponse(ActionEvent event, BufferedReader bf) throws IOException {
response = bf.readLine();
switch (response) {
case "a":
Utils.currentStage(event).close();
break;
}
}
}
Your sendOptionToServer(...) method, and in particular your waitForResponse(...) method, contains blocking calls that block execution until they are complete (i.e. until you receive a response from the server). Since you're running these on the FX Application Thread, you prevent that thread from doing its normal work until those calls complete. This means it won't update the UI or process any user events until you have received and processed the response from the server.
You should place the calls to blocking methods in a background thread to allow the FX Application Thread to proceed in the meantime. The javafx.concurrent API makes this reasonably easy to do; here a Task should suffice.
Here's a version that uses a Task. I also used a "try with resources" to ensure everything that needs to be closed is correctly closed.
#FXML
private void sendOptionToServer(ActionEvent event) {
Task<String> serverCommunicationTask = new Task<>() {
#Override
protected String call() throws Exception {
try (
Socket cliente = new Socket("localhost", 3322);
PrintWriter pr = new PrintWriter(cliente.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
) {
pr.println(option);
pr.flush();
return bf.readLine();
}
}
};
serverCommunicationTask.setOnSucceeded(event -> {
if ("a".equals(serverCommunicationTask.getValue())) {
rootPane.getScene().getWindow().hide();
}
});
serverCommunicationTask.setOnFailed(event -> {
event.getException().printStackTrace();
// handle exception...
});
Thread thread = new Thread(serverCommunicationTask);
thread.setDaemon(true);
thread.start();
}

UWP Sockets: client socket StoreAsync operation not interrupted on socket close

With UWP sockets on Windows 10, I'm seeing an annoying behavior with pending asynchronous write operations not being interrupted when CancelIOAsync or Dispose is called on the socket. Below is some sample code that demonstrates the issue.
Basically, the while loop loops for 2 iterations until the send socket buffer is full (the server side connection doesn't read the data on purpose to demonstrate the problem). The next await socket.StoreAsync() operation ends up waiting indefinitely, it's not interrupted by the closing of the socket.
Any ideas on how to interrupt the pending StoreAsync?
Thanks
Benoit.
public sealed partial class MainPage : Page
{
private StreamSocket socket;
private StreamSocket serverSocket;
public MainPage()
{
this.InitializeComponent();
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
listener.Control.KeepAlive = false;
listener.BindServiceNameAsync("12345").GetResults();
}
async private void Connect_Click(object sender, RoutedEventArgs e)
{
socket = new StreamSocket();
socket.Control.KeepAlive = false;
await socket.ConnectAsync(new HostName("localhost"), "12345");
DataWriter writer = new DataWriter(socket.OutputStream);
try
{
while(true)
{
writer.WriteBytes(new byte[1000000]);
await writer.StoreAsync();
Debug.WriteLine("sent bytes");
}
}
catch(Exception ex)
{
Debug.WriteLine("sent failed : " + ex.ToString());
}
}
async private void Close_Click(object sender, RoutedEventArgs e)
{
//
// Closing the client connection with a pending write doesn't cancel the pending write.
//
Debug.WriteLine("Closing Client Connection");
await socket.CancelIOAsync();
socket.Dispose();
}
private void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
System.Diagnostics.Debug.WriteLine("Received connection");
serverSocket = args.Socket;
}
}

Review of Connection handling and Data access layer using C#, sql server compact 3.5

I am developing a stand alone application, using sql server compact 3.5 sp2 which runs in process. No Database writes involved. Its purely a reporting application. Read many articles about reusing open db connections in case of sql compact(connection pooling) due to its different behavior from sql server.
Quoting the comments from a quiz opened by Erik Ejlskov Jensen Link, where its discussed an open early close late strategy for sql server compact databases. Based on this, with my limited experience I have implemented a not so complex Connection handling+Data access layer. Basically I am unsure if i am writing it in a recommended way. Please could any one point me in the right direction with rooms for improvement in this connection handling approach i have written?
The DbConnection class
public class FkDbConnection
{
private static SqlCeConnection conn;
private static DataTable table;
private static SqlCeCommand cmd;
~FkDbConnection() { conn = null; }
//This will be called when the main winform loads and connection will be open as long as the main form is open
public static string ConnectToDatabase()
{
try {
conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Connstr"].ConnectionString);
if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
conn.Open();
}
return "Connected";
}
catch(SqlCeException e) { return e.Message; }
}
public static void Disconnect()
{
if (conn.State == ConnectionState.Open || conn.State == ConnectionState.Connecting || conn.State == ConnectionState.Fetching)
{
conn.Close();
conn.Dispose();
//conn = null; //does conn have to be set to null?
}
//else the connection might be already closed due to failure in opening it
else if (conn.State == ConnectionState.Closed) {
conn.Dispose();
//conn = null; //does conn have to be set to null?
}
}
/// <summary>
/// Generic Select DataAccess
/// </summary>
/// <param name="sql"> the sql query which needs to be executed by command object </param>
public static DataTable ExecuteSelectCommand(SqlCeCommand comm)
{
if (conn != null && conn.State == ConnectionState.Open)
{
#region block using datareader
using (table = new DataTable())
{
//using statement needed for reader? Its closed below
using (SqlCeDataReader reader = comm.ExecuteReader())
{
table.Load(reader);
reader.Close(); //is it needed?
}
}
#endregion
# region block using dataadpater
//I read DataReader is faster?
//using (SqlCeDataAdapter sda = new SqlCeDataAdapter(cmd))
//{
// using (table = new DataTable())
// {
// sda.Fill(table);
// }
//}
#endregion
//}
}
return table;
}
/// <summary>
/// Get Data
/// </summary>
/// <param name="selectedMPs"> string csv, generated from a list of selected posts(checkboxes) from the UI, which forms the field names used in SELECT </param>
public static DataTable GetDataPostsCars(string selectedMPs)
{
DataTable dt;
//i know this it not secure sql, but will be a separate question to pass column names to select as parameters
string sql = string.Format(
"SELECT " + selectedMPs + " "+
"FROM GdRateFixedPosts");
using (cmd = new SqlCeCommand(sql,conn))
{
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add("#fromDateTime",DbType.DateTime);
//cmd.Parameters.Add("#toDateTime",DbType.DateTime);
dt = ExecuteSelectCommand(cmd);
}
return dt;
}
}
The Main UI (Form) in which connection opened, for connection to be open through out. 2 other reporting forms are opened from here. Closing main form closes all, at which point connection is closed and disposed.
private void FrmMain_Load(object sender, EventArgs e)
{
string str = FkDbConnection.ConnectToDatabase();
statStDbConnection.Items[0].Text = str;
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
FkDbConnection.Disconnect();
}
Comments, improvements on this connection class much appreciated. See my questions also inline code
Thank you.
Updated classes as per Erik's suggestion. with a correction on ExecuteSelectCommand() and an additional class which will instantiate command objs in "using" and pass data to the UI. I intent to add separate GetDataForFormX() methods since the dynamic sql for each form may differ. Hope this is ok?
Correction to Erik's code:
public static DataTable ExecuteSelectCommand(SqlCeCommand comm)
{
var table = new DataTable();
if (conn != null && conn.State == ConnectionState.Open)
{
comm.Connection = conn;
using (SqlCeDataReader reader = comm.ExecuteReader())
{
table.Load(reader);
}
}
return table;
}
New FkDataAccess class for passing Data to UI
public class FkDataAccess
{
public static DataTable GetDataPostsCars(string selectedMPs)
{
var table = new DataTable();
string sql = string.Format(
"SELECT " + selectedMPs + " " +
"FROM GdRateFixedPosts");
if (FkDbConnection.conn != null && FkDbConnection.conn.State == ConnectionState.Open)
{
using (SqlCeCommand cmd = new SqlCeCommand(sql, FkDbConnection.conn))
{
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add("#fromDateTime",DbType.DateTime);
table = FkDbConnection.ExecuteSelectCommand(cmd);
}
}
return table;
}
//public static DataTable GetDataXY(string selectedvals)
// and so on
}
Too much code in your data access class, makes it unreadable and hard to maintain
The SqlCeonnection object will be disposed when you close it (and when the app closes)
You cannot dispose the DataTable if you want to use it elsewhere, and it is an completely managed object anyway.
It is a good pattern to limit your classes to a single responsibility
public class FkDbConnection
{
private static SqlCeConnection conn;
~FkDbConnection() { conn = null; }
//This will be called when the main winform loads and connection will be open as long as the main form is open
public static void ConnectToDatabase()
{
// Handle failure to open in the caller
conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Connstr"].ConnectionString);
conn.Open();
}
public static void Disconnect()
{
if (conn != null)
{
conn.Close();
}
}
public static DataTable ExecuteSelectCommand(SqlCeCommand comm)
{
var table = new DataTable();
if (conn != null && conn.State == ConnectionState.Open)
{
comm.Connection = conn;
using (SqlCeDataReader reader = comm.ExecuteReader())
{
table.Load(reader);
}
}
return table;
}
private void FrmMain_Load(object sender, EventArgs e)
{
try
{
FkDbConnection.ConnectToDatabase();
statStDbConnection.Items[0].Text = "Connected";
}
catch (Exception ex)
{
//Inform use that we canot proceed, what she can do to remedy, and exit
}
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
FkDbConnection.Disconnect();
}

Socket implementation with ObjectInputStream - can't read object

For a Java class I am taking, I need to use sockets to pass data back and forth between client and server. While I can get examples to work passing string data, I need to be able to pass custom class objects (i.e. a product) and lists of these objects back and forth. I cannot get the server piece to successfully read the input. I tried to create a simple example of my code to see if anyone can pinpoint the issue. I do understand that I don't have the code complete, but I cannot even get the server to read the object the the class is writing to the stream (in this case, I am writing a string just in an attempt to get it to work, but need to read/write objects). Here is my code. I have spent hours and hours trying this and researching other people's questions and answere, but still can't get this to work.
Here the sample code:
simple server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class simpleServer {
public static final int PORT_NO = 8888;
static ObjectInputStream serverReader = null;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = new ServerSocket(PORT_NO);
System.out.println("... server is accepting request");
Object myObject = null;
while (true) {
Socket socket = serverSocket.accept();
System.out.println("creating reader");
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
serverReader = new ObjectInputStream(socket.getInputStream());
System.out.println("created reader");
try {
System.out.println("try to read");
myObject = serverReader.readObject();
System.out.println("read it");
System.out.println(myObject);
if (myObject != null) objOut.writeUTF("Got something");
else objOut.writeUTF("got nothing");
if ("quit".equals(myObject.toString())) serverSocket.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("cath for readobject");
}
catch (Exception e) {
System.out.println("other error");
System.out.println(e.getMessage());
}
}
}
}
simple client:
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket("localhost", ProductDBServer.PORT_NO);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeUTF("loadProductsFromDisk");
objOut.flush();
String myString = objIn.toString();
//System.out.println(myString);
if (!"quit".equals(objIn.toString().trim())) {
//System.out.println("reading line 1");
String line;
try {
line = (String)objIn.readObject();
//System.out.println("line is " + line);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
objIn.close();
//System.out.println("result: " + line);
}
System.out.println("closing socket");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Unknownhostexception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("ioexception");
e.printStackTrace();
}
}
The code appears to run to the point on the server side where it trys to read the object I sent, and then dies. Can someone see what I am doing wrong? This seems to be such a simple thing to do, and yet I can't seem to get it to work. Thanks for any help!
To write objects to an ObjectOutputStream you need to call writeObject().
Not writeUTF().
To read objects from an ObjectInputStream you need to call readObject().
Not toString().
See in your code:
// Simple Client
objOut.writeUTF("loadProductsFromDisk"); // Line 8
You are sending the String "loadProductsFromDisk" in the UTF-8 format towards the server side.
So in order to receive it and read it over the server side, you will need something like this:
String clientReq = serverReader.readUTF();
Where, serverReader is your ObjectInputStream object.
Otherwise, if you wish to send and receive objects you must use the
writeObject() & readObject() methods respectively.

Listen to msmq queue

Following the is the code I have for listening to messages from Windows form.
I have noticed that when I click on send it sends a message to MyQueue but at that time I was hoping the event mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) should get called but it is not, in other words I am trying to subscribe to MyQueue from Windows form. Just wondering if I am missing something in the code:
public class Form1 : System.Windows.Forms.Form
{
public System.Messaging.MessageQueue mq;
public static Int32 j=0;
public Form1()
{
// Required for Windows Form Designer support
InitializeComponent();
// Queue Creation
if(MessageQueue.Exists(#".\Private$\MyQueue"))
mq = new System.Messaging.MessageQueue(#".\Private$\MyQueue");
else
mq = MessageQueue.Create(#".\Private$\MyQueue");
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
mq.BeginReceive();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnMsg_Click(object sender, System.EventArgs e)
{
// SendMessage(Handle, 1, 0, IntPtr.Zero);
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = txtMsg.Text;
mm.Label = "Msg" + j.ToString();
j++;
mq.Send(mm);
}
void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void btnRcv_Click(object sender, System.EventArgs e)
{
System.Messaging.Message mes;
string m;
try
{
mes = mq.Receive(new TimeSpan(0, 0, 3));
mes.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});
m = mes.Body.ToString();
}
catch
{
m = "No Message";
}
MsgBox.Items.Add(m.ToString());
}
}
See MSDN's example on how to use the ReceiveCompletedEventHandler .
They have a console app where the Main() does the same as your Form1(), but your handler doesn't have any code. You've said it doesn't call back into your event delegate, but perhaps check your queue name is correct on the constructor.
Consider using MSDN's sample code in a new console app to test your environment first, then go back to your WinForms code with any lessons learned.
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message: " + (string)m.Body);
mq.BeginReceive();
return;
}
If you want to inspect the queue and get a message on the click of a button, you can simply move the statement mq.BeginReceive(); to the btnRcv_Click() in place of .Receive();