Sending Windows Form through TCP - c#

I am developing an application whose main features are:
A group of friends want to have a game of remote role-playing.
The GM opens the application and starts a server. It opens a winForm.
Clients do the same and connect to the server. The list of connected players is updated on all windows (clients / server)
The GM opens a window on his screen and this is also displayed on all clients.
When he draws on it, the drawing also displays "live" on all client screens.
So far I manage to do everything described above except for the last step: drawing on a panel on the server side does not send the drawing to the clients.
To achieve displaying the opened windows on the client side, I serialized my winforms via a custom class. Here is a portion of code to serialize / deserialize :
public static String Serialise(Control c)
{
XmlTextWriter xmlSerialisedForm = new XmlTextWriter(Application.StartupPath + #"\serialise.xml", System.Text.Encoding.Default);
xmlSerialisedForm.Formatting = Formatting.Indented;
xmlSerialisedForm.WriteStartDocument();
xmlSerialisedForm.WriteStartElement("ChildForm");
// enumerate all controls on the form, and serialise them as appropriate
AddChildControls(xmlSerialisedForm, c);
xmlSerialisedForm.WriteEndElement(); // ChildForm
xmlSerialisedForm.WriteEndDocument();
xmlSerialisedForm.Flush();
xmlSerialisedForm.Close();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Application.StartupPath + #"\serialise.xml");
return xmlDoc.InnerXml;
}
public static void Deserialise(Control c, string XmlFileName) {
XmlDocument xmlSerialisedForm = new XmlDocument();
xmlSerialisedForm.LoadXml(XmlFileName);
XmlNode topLevel = xmlSerialisedForm.ChildNodes[1];
foreach (XmlNode n in topLevel.ChildNodes) {
SetControlProperties((Control)c, n);
}
}
I have read dozen of web articles here and there about NOT deserializing Windows Form BUT is there another way to achieve what I'm aiming ?
How can I send through TCP connection to the connected clients data about what i'm doing live on my screen ?
I'm actually building this app to know more about TCP connections and C# in general and my goal is to reproduce what this software, written in C with QT, is actually doing.
Rolistik site
Rolistik sources
Screenshot of a server and a client with a winform launched by the server and received by the client
Thanks for the incoming help
Leor

Related

Does anyone know where I can find a Universal Windows Private Network (Client & Server) code Example?

I am brand new to Universal Windows Apps (Win 10). I am trying to port a console application over to UWP that acts as a remote testing and administrative console for a custom Windows Service application. I can not seem to find any solid example code to demonstrate where to place a socket listener in the MainPage.xaml.cs file (or wherever it's supposed to go). I have been successful with porting the MSDN example into a method that serializes a PCL model object with Json and sends it to the server. I just can not seem to handle the listener correctly. I don't think that I am using it in the right place, especially when it comes to the async usage. I am having protocol\port usage errors because it's basically saying that it is already open (I just tossed it in the test method). I would like to deserialize the Json response that is received and use it to populate a List. Here is an example of what is working for me for sending.
private async void Pulse(string target)
{
if (target == null || target == string.Empty)
{
greetingOutput.Text = "No Ip specified";
return;
}
else
{
try
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName(target);
await socket.ConnectAsync(serverHost, serverPort);
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
HeartBeatPing heartBeatPing = new HeartBeatPing(GetLocalIp(), target);
string msg = JsonConvert.SerializeObject(heartBeatPing);
await writer.WriteLineAsync(msg);
await writer.FlushAsync();
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch (Exception xCeption)
{
greetingOutput.Text += "\n" + xCeption.ToString();
}
}
}
Some of you might notice from the greetingsOutput.text that I have started with the "C# Hello World" example from Microsoft's training site.
I would also like to add that I am not going to be using any HTTP for this because there is going to be some custom encryption and other "things" happening with the Json objects that will require separate ports.
I'm not far enough into my Universal Windows Apps with XAML and C# (Unleashed) books to have even a clue as to what I am doing. I am however well seasoned C# programmer in other platforms such as MVC, Windows Service, Console, and others. I have a solid understand of enterprise class patterns and practices based on my knowledge of "The Gang of Four".
Any help would be greatly appreciated. Thank you.
(https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DatagramSocket)
Here is a sample. There are CPP, js, and cs code in this sample, I've only tested the cs code. Wish this can help you.

How to pass data from windows application to web application?

I have a windows application and i want to open my web application from this windows application. My Windows application will generate a key and machine code after authorization and will save the key and machine code in to database among active users. Now i want to send this key to browser so that my web application can identify the user with his machine.
How can i do this?
i cannot use URL because the user will be able to copy the URL and use my web application from another machine. I must restrict it.
Is there any other way?
There are Two Ways to transfer winform data to web applications
If you want to transfer the data to IE then You can Use
1)MSHtml.dll
code
InternetExplorer TargetIE = null;
IHTMLDocument2 document = null;
//Check whether the IE is opened
foreach (InternetExplorer internetExplorer in new ShellWindows())
{
if (internetExplorer.Document is HTMLDocument)
{
TargetIE = internetExplorer;
break;
}
}
2) If you want to transfer data from winform to any web browser my personal advice to you please use selenium for this.
download the respective dll and driver for respective drivers from this site help
Code
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Chrome;
namespace WindowsFormsChrome
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// download the chrome driver
IWebDriver driver = new ChromeDriver(#"C:\Users\Downloads\chromedriver");
driver.Navigate().GoToUrl("http://www.yahoo.com");
IWebElement myField = driver.FindElement(By.Id("txtUserName"));
myField.SendKeys("UserName");
IWebElement myField = driver.FindElement(By.Id("txtPassword"));
myField.SendKeys("Password");
IWebElement myField = driver.FindElement(By.Id("btnLogin"));
myField.click()
}
}
}
this second part work for all browser yoou just replace chromeDriver class as per you want.
you can POST data using c#
http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx
see also this post in stackoverflow
How to post data to a website
You can write an ashx handler and pass your data (or some reference to your data) from your windows application. Here is an example how this can be done :
how to call ASHX handler and getting the result back

Using Sockets to transfer Data with MonoDroid

I'm trying to send some information to a server with Android using Monodroid.
The code is as follows:
public void sendSomething()
{
sock = new TcpClient();
sock.Connect(Dns.GetHostAddresses("a.domain.com"), 7777);
String d;
d = "somedata";
StreamWriter w = new StreamWriter(sock.GetStream());
// StreamReader r = new StreamReader(sock.GetStream());
w.WriteLine(d);
w.Flush();
sock.Close();
}
It works fine if I run the exact same routine in a winforms application, but when linked to a button click in monodroid (running on the android virtual device - I'm using the evaluation version) the server will see the connection but no data is received.
Does anybody have any idea why this could be?
(edited to ammend code)
It could be a server issue. E.g. let's assume that:
a) your winform app running on Windows / MS.NET (and not on Mono / Linux or OSX);
b) your server is Windows-based too and does a ReadLine to read sockets
Then the NewLine between the write (Unix \n) and the read (Windows \r\n\) could explain why the server does not report what's being read.
Can you show us how you're reading the data on the server ? (edit your question)

From Xaml-String to Wpf-Window

I keep having problems with creating a Wpf-Window from a Xaml-String.
What works:
I have a Server running which can receive Strings from remote Clients. (That is not complicated and works perfectly)
What doesn’t work:
Sometimes the Server receives a String with the content of a Xaml-File. Know I want to create a window dynamically with all the content specified in the Xaml-String.
Is there an easy way to do that?
var window = XamlReader.Parse(SomeXamlString) as Window;

WMEncoder Throws COMException (0x80004005) Unspecified Error

So I'm running this code
public static void ConvertToWma(string inFile, string outFile, string profileName)
{
// Create a WMEncoder object.
WMEncoder encoder = new WMEncoder();
ManualResetEvent stopped = new ManualResetEvent(false);
encoder.OnStateChange += delegate(WMENC_ENCODER_STATE enumState)
{
if (enumState == WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED)
stopped.Set();
};
// Retrieve the source group collection.
IWMEncSourceGroupCollection srcGrpColl = encoder.SourceGroupCollection;
// Add a source group to the collection.
IWMEncSourceGroup srcGrp = srcGrpColl.Add("SG_1");
// Add an audio source to the source group.
IWMEncSource srcAud = srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
srcAud.SetInput(inFile, "", "");
// Specify a file object in which to save encoded content.
IWMEncFile file = encoder.File;
file.LocalFileName = outFile;
// Choose a profile from the collection.
IWMEncProfileCollection proColl = encoder.ProfileCollection;
proColl.ProfileDirectory = AssemblyInformation.GetExecutingAssemblyDirectory();
proColl.Refresh();
IWMEncProfile pro;
for (int i = 0; i < proColl.Count; i++)
{
pro = proColl.Item(i);
if (pro.Name == profileName)
{
srcGrp.set_Profile(pro);
break;
}
}
// Start the encoding process.
// Wait until the encoding process stops before exiting the application.
encoder.SynchronizeOperation = false;
encoder.PrepareToEncode(true);
encoder.Start();
stopped.WaitOne();
}
And I get a COMException (0x80004005) when encoder.PrepareToEncode gets executed.
Some notes:
1) The process is spawned by an ASP.NET web service so it runs as NETWORK SERVICE
2) inFile and outFile are absolute local paths and their extensions are correct, in addition inFile definitely exists (this has been a source of problems in the past)
3) The program works when I run it as myself but doesn't work in the ASP.NET context.
This says to me its a security permission issue so in addition I've granted Full Control to the directory containing the program AND the directories containing the audio files to NETWORK SERVICE. So I really don't have any idea what more I can do on the security front. Any help?
Running WM Encoder SDK based app in windows service is not supported. It uses hidden windows for various reasons, and there isn't a desktop window in service. DRM would certainly fail with no user profile. Besides, even when you make your service talk to WME instance on a user's desktop, Microsoft only supports 4 concurrent requests per machine because the global lock in WME (I know, not pretty programming, but WME is old). For more scalable solutions, consider Windows Media Format SDK.
You may want to move your WM Encoder based app to Expression Encoder SDK as WM Encoder's support is ending.

Categories

Resources