Parsing JSON string from Python to .NET C# WPF - c#

I'm pretty new to this so any help would be greatly appreciated. I have two pieces of code and there is a missing link which I'm hoping someone can fill in. I'm new to both platforms and I don't have much experience with back-end nor with web architecture.
So below is the first bit of code, it's an adapted python server and it shows me a formatted JSON string when I enter http://localhost:8000 into the browser. This is great. It's what I want to see.
#!/usr/bin/python
"""
Save this file as server.py
>>> python server.py 0.0.0.0 8001
serving on 0.0.0.0:8001
or simply
>>> python server.py
Serving on localhost:8000
You can use this to test GET and POST methods.
"""
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import sys
import json
import simplejson
import time
if len(sys.argv) > 2:
PORT = int(sys.argv[2])
I = sys.argv[1]
elif len(sys.argv) > 1:
PORT = int(sys.argv[1])
I = ""
else:
PORT = 8000
I = ""
current_milli_time = lambda: int(round(time.time() * 1000))
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.warning("======= GET STARTED =======")
logging.warning(self.headers)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
logging.warning("======= POST STARTED =======")
logging.warning(self.headers)
data_string = self.rfile.read(int(self.headers['Content-Length']))
#print "data_string: "
#print data_string
data = simplejson.loads(data_string)
#print "json data: "
#print data
response = {}
response = {"time": current_milli_time()}
# Send a repsonse
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data))
Handler = ServerHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "#rochacbruno Python http server version 0.1 (for testing purposes only)"
print "Serving at: http://%(interface)s:%(port)s" % dict(interface=I or "localhost", port=PORT)
httpd.serve_forever()
I have a WPF/C# Application which contains a background worker and I have previously used this to get JSON string from a REST service.
public void getData(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
var url = "http://localhost:xxxx/";
var syncClient = new WebClient();
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(100);
var content = syncClient.DownloadString(url);
Console.WriteLine(content);
}
}
}
So I pretty much need some direction on how to proceed, how do I get the JSON string into my WPF/C# Application? I hope this is clear enough, let me know if you need more info.
Edit: I have a feeling I need to get the current python server to post to another server which is RESTful which I can then HTTP GET the JSON string.
Cheers!

Related

Two-way communication between C# WPF application and python script

I'm trying to get a tow-way communication between a c# application and a python script that c# will call.
I have some input channels in c# that changes constantly at high frequency (5000-1000 data/s) for let's say a minute. On every change of those inputs,results are calculated and assigned to output variables. What i'm trying to do is to move the logic to a python script. For instance:
Inputs: double x,y
Output: double z
So the pyhton script should be capable of read the inputs, perform the logic and write the results at a symilar frequency.
Any recomendations? Has anyone did anything similar before?
First I tried to call the script on every change and read the console output. But the code in the script is not as simple as z=x*y and variables that store values are required in the pyhon script. For example, the script mught want to save the maximum value of x and y reached.
I had a look to ZeroMQ library for the communication, not sure how to use it though.
Here is a solution:
Simple C# program: client which sends data and receive
using System;
using ZeroMQ;
namespace ZeroMQ_Client
{
class Program
{
static void Main(string[] args)
{
using (var requester = new ZSocket(ZSocketType.REQ))
{
// Connect
requester.Connect("tcp://127.0.0.1:5555");
for (int n = 0; n < 10; ++n)
{
string requestText = "Hello";
Console.Write("Sending {0}...", requestText);
// Send
requester.Send(new ZFrame(requestText));
// Receive
using (ZFrame reply = requester.ReceiveFrame())
{
Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());
}
}
}
}
}
}
python program, you have to install pyzmq:
#
# Hello World server in Python
# Binds REP socket to tcp://*:5555
# Expects b"Hello" from client, replies with b"World"
#
import time
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: %s" % message)
# Do some 'work'
time.sleep(1)
# Send reply back to client
socket.send(b"World")

AWS - Amazon Polly Text To Speech

I have doubts about the "text-to-speech" Amazon Polly service.
I've integrated this service in my chatbot, in order to describe vocally what the bot writes to the user in chat.
It works pretty well, but I don't know if it is possible to stop the voice early, before she (I chose a female voice) finishes speaking. Sometimes I need to go further in the conversation and I don't want to listen until the end of the sentence.
This is the code used for the integration:
//Html side
function textToSpeech(text) {
$.ajax({
type: 'GET',
url: '/Chat/TextToSpeech?text=' + text,
cache: false,
success: function (result) {
var audio = document.getElementById('botvoice');
$("#botvoice").attr("src", "/Audios/" + result);
audio.load();
audio.play();
}
});
}
Controller side:
public ActionResult TextToSpeech(string text)
{
string filename = "";
try
{
AWSCredentials credentials = new StoredProfileAWSCredentials("my_credential");
AmazonPollyClient client = new AmazonPollyClient(credentials, Amazon.RegionEndpoint.EUWest1);
// Create describe voices request.
DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
// Synchronously ask Amazon Polly to describe available TTS voices.
DescribeVoicesResponse describeVoicesResult = client.DescribeVoices(describeVoicesRequest);
List<Voice> voices = describeVoicesResult.Voices;
// Create speech synthesis request.
SynthesizeSpeechRequest synthesizeSpeechPresignRequest = new SynthesizeSpeechRequest();
// Text
synthesizeSpeechPresignRequest.Text = text;
// Select voice for synthesis.
synthesizeSpeechPresignRequest.VoiceId = voices[18].Id;
// Set format to MP3.
synthesizeSpeechPresignRequest.OutputFormat = OutputFormat.Mp3;
// Get the presigned URL for synthesized speech audio stream.
string current_dir = AppDomain.CurrentDomain.BaseDirectory;
filename = CalculateMD5Hash(text) + ".mp3";
var path_audio = current_dir + #"\Audios\" + filename;
var presignedSynthesizeSpeechUrl = client.SynthesizeSpeechAsync(synthesizeSpeechPresignRequest).GetAwaiter().GetResult();
FileStream wFile = new FileStream(path_audio, FileMode.Create);
presignedSynthesizeSpeechUrl.AudioStream.CopyTo(wFile);
wFile.Close();
}
catch (Exception ex)
{
filename = ex.ToString();
}
return Json(filename, JsonRequestBehavior.AllowGet);
}
An input text is present in my chat (obviously) for writing and sending (by pressing ENTER on the keyboard) the question to the bot. I tried to put the command audio.src="" in the handler, and she stops to talk but the chat still remains blocked... It seems like it waits the end of the audio stream. I have to refresh the page to see new messages and responses.
Is there any Amazon function that I can call with a particular parameter set, in order to notify the service that I want to stop and clear the audio stream?
Amazon Polly returns a .mp3 file. It is not responsible for playing the audio file.
Any difficulties you are experiencing playing/stopping the audio would be the result of the code you are using to play an MP3 audio file. It has nothing to do with the Amazon Polly service itself.
Thank you! I found the real problem: when I stopped the audio I didn't print the rest of the messages. I add the call to the function that print messages on the chat. For stopping the voice I used the command audio.src="";

CoolUtils TotalPDFPrinterX causes ASP C# site to crash

My company has purchased the CoolUtils TotalPDFPrinterX from https://www.coolutils.com/TotalPDFPrinterX
I make an HTTP PUT from Postman to the API and I get “Could not get any response”.
When running on my Windows machine the PDF prints fine however on the server the site crashes and in the event log I get the error "A process serving application pool '[MY_APP_POOL]' failed to respond to a ping. The process id was '[MY_PROCESS_ID]'."
Here is my C# code:
PDFPrinterX ppx = new PDFPrinterX();
ppx.Print(fileName, printerName, "-ap Default");
if (ppx.ErrorMessage != null)
{
WriteToSQL(id, false, ppx.ErrorMessage, 2);
Console.WriteLine(ppx.ErrorMessage);
}
By writing to the event log I know the site crashes on this line: PDFPrinterX ppx = new PDFPrinterX(); I have also surrounded the above code with a try catch and no exception is thrown. The site still crashes.
Things I have tried:
Uninstalling and Reinstalling the CoolUtils software
Giving EVERYONE Full control to the site folder and the CoolUtils program folder
Creating a C# desktop application using the same code. THIS WORKS FINE ON THE SERVER. It's just the ASP site that crashes.
Does anyone know what might be causing this?
The more I research this thing online the more I'm inclined to say that ActiveX which is the X in PDFPrinterX doesn't seem to work well when hosted in IIS.
I've seen a few forums where they say it works fine when they debug on localhost but when deployed to server is crashes.
...works fine when used inside localhost(Visual studio)
One of their feature pages shows that it requires Win 2000/NT/XP/2003/Vista/7
You should look into whether your server supports ActiveX components that can work in conjunction with IIS.
Looking at one of their other products support page: TotalPDFConverterX:
the following note in my opinion may also apply to TotalPDFPrinterX, given its dependency on ActiveX as well.
Note: Pay attention to some details during installation Total PDF Converter X:
Do not forget to register ActiveX in your web-server account.
Total PDF Converter X supports only Internet Explorer, Mozilla and Firefox browsers.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Thanks to #Nkosi I was able to find a workaround.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Our IIS server is 64 bit so that is what probably caused the site to hang up.
Buttt... the command line still worked in printing the PDFs on the server.
Client side code (makes the HTTP POST):
private void SendToPrinter(string fileName, string printerName, int id, decimal documentSequence)
{
// use http client to make a POST to the print api
using (var client = new HttpClient())
{
// compile the values string to transfer in POST
// should finish to look something like this:
// C:\print.pdf&PRTFTW_OFIT&ValShip-155320-1
var values = new Dictionary<string, string>
{
{ "", fileName + "&" + printerName + "&ValShip-" + id + "-" + documentSequence},
};
// URL encode the values string
var content = new FormUrlEncodedContent(values);
// make the POST
// DEBUG
var response = client.PostAsync("http://localhost:54339/api/print", content);
// retrieve the response
var responseString = response.Result.ToString();
}
}
Server side code (receives the HTTP POST):
using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace api.valbruna.print.Controllers
{
public class PrintController : ApiController
{
// POST api/print
public HttpResponseMessage Post(HttpRequestMessage request)
{
try
{
// parse the content recieved from the client
var content = request.Content.ReadAsStringAsync().Result;
// decode the content, certain characters such as
// '&' get encoded to URL lingo such as '%26'
content = HttpUtility.UrlDecode(content);
// split the string into 3 seperate parts
String[] str = content.Split('&');
// remove the equal sign from the first string
str[0] = str[0].Trim('=');
// compile the arguments command line string
// should finish to look something like this:
// "C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe" "C:\print.pdf" -p"\\PRINTERS\PRTFTW_OFIT" -ap Default -log "C:\inetpub\logs\CoolUtils\log-ValShip-155320-4.txt" -verbosity detail"
String arguments = "\"" + str[0] + "\" -p\"\\\\PRINTERS\\" + str[1] +
"\" -ap Default -log \"C:\\inetpub\\logs\\CoolUtils\\log-" + str[2] +
".txt\" -verbosity detail";
// file location for PDFPrinterX.exe
String file = #"C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe";
// start the process
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = file;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
return new HttpResponseMessage() { Content = new StringContent(content) };
}
catch (Exception e)
{
return new HttpResponseMessage() { Content = new StringContent(e.Message) };
}
}
}
}

How to Push data from C# to ZeroMQ and Pull from Node.JS or vice-versa?

Scenario:
I am trying to send a data (say String type) from C# сonsole application to Node.JS server through ZeroMQ.
Information:
Using clrzmq for c# and ZeroMQ libs for C# and Node.JS respectively
I am able to perform push-pull from Node.JS, also push - pull from C#.
So, one thing is confirmed that ZeroMQ - The Intelligent Transport Layer is installed on the machine (Windows 7 64-bit)
Issue:
I am not able to push data from C# Console app to Node.JS app (even tried vice-versa), both are on the same machine and on the same address i.e tcp://127.0.0.1:2222
Node.js code:
var zmq = require('zeromq.node');
var pull_socket = zmq.socket('pull');
pull_socket.connect('tcp://127.0.0.1:2222');
pull_socket.on('message', function (data) {
console.log('received data:\n');
console.log(data);
});
C# code:
namespace DataServiceEngine
{
class Program
{
static void Main(string[] args)
{
//clsApp App = new clsApp();
//App.appId = "001";
//App.name = "Back Office";
//Console.WriteLine("appId :" + App.appId + "\n");
//Console.WriteLine("name:" + App.name + "\n");
try
{
// ZMQ Context and client socket
using (var context = new Context(1))
{
using (Socket client = context.Socket(SocketType.PUSH))
{
client.Connect("tcp://127.0.0.1:2222");
string request = "Hello";
for (int requestNum = 0; requestNum < 10; requestNum++)
{
Console.WriteLine("Sending request {0}...", requestNum);
client.Send(request, Encoding.Unicode);
string reply = client.Recv(Encoding.Unicode);
Console.WriteLine("Received reply {0}: {1}", requestNum, reply);
}
}
}
}
catch (ZMQ.Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}
Question: Can anyone tell me what may be the reason or where am I doing wrong?
I had the same issue (but I issued a communication Node.JS -> Node.JS). To solve the problem I used to do sendersocket.connect("tcp://"+host+":"+port); at the sender and receiversocket.bindSync("tcp://*:"+port); at the receiver.
Hope this fix your problem.

WebSockets in firefox

For implementing my websocket server in C# I'm using Alchemy framework. I'm stuck with this issue. In the method OnReceive when I try to deserialize json object, I get a FormatException:
"Incorrect format of the input string." (maybe it's different in english, but I'm getting a localized exception message and that's my translation :P). What is odd about this is that when I print out the context.DataFrame I get: 111872281.1341000479.1335108793.1335108793.1335108793.1; __ad which is a substring of the cookies sent by the browser: __gutp=entrystamp%3D1288455757%7Csid%3D65a51a83cbf86945d0fd994e15eb94f9%7Cstamp%3D1288456520%7Contime%3D155; __utma=111872281.1341000479.1335108793.1335108793.1335108793.1; __adtaily_ui=cupIiq90q9.
JS code:
// I'm really not doing anything more than this
var ws = new WebSocket("ws://localhost:8080");
C# code:
static void Main(string[] args) {
int port = 8080;
WebSocketServer wsServer = new WebSocketServer(port, IPAddress.Any) {
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect,
OnConnected = OnConnected,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, 5, 0)
};
wsServer.Start();
Console.WriteLine("Server started listening on port: " + port + "...");
string command = string.Empty;
while (command != "exit") {
command = Console.ReadLine();
}
Console.WriteLine("Server stopped listening on port: " + port + "...");
wsServer.Stop();
Console.WriteLine("Server exits...");
}
public static void OnReceive(UserContext context) {
string json = "";
dynamic obj;
try {
json = context.DataFrame.ToString();
Console.WriteLine(json);
obj = JsonConvert.DeserializeObject(json);
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
}
On the C# side I'm using Newtonsoft.Json, though it's not a problem with this library...
EDIT:
One more thing - I browsed through the code in here: https://github.com/Olivine-Labs/Alchemy-Websockets-Example and found nothing - I mean, I'm doing everything the same way authors did in this tutorial...
EDIT:
I was testing the above code in Firefox v 17.0.1, and it didn't work, so I tested it under google chrome, and it works. So let me rephrase the question - what changes can be made in js, so that firefox would not send aforementioned string?
I ran into the same issue - simply replacing
var ws = new WebSocket("ws://localhost:8080");
with
var ws = new WebSocket("ws://127.0.0.1:8080");
fixed the issue for me.
In C# console app I connect the client to the server using :
var aClient = new WebSocketClient(#"ws://127.0.0.1:81/beef");
Your code above is connecting using
var ws = new WebSocket("ws://localhost:8080");
There could be one of two issues -
First is to see if WebSocketClient works instead.
To make sure your url is of the format ws://ur:port/context. This threw me off for a while.

Categories

Resources