I'm trying to call my own REST API that returns JSON using a simple C# GUI application, and am looking for the simplest way to do so:
http://danielmiessler.com:44821/token/dGVxdWllcm8=
I am opening a file containing tokens and reading the contents line by line to get the final part of the URL:
StreamReader input = new StreamReader(openFileDialog1.OpenFile());
while ((line = input.ReadLine()) != null) {
This is going back into a textbox:
textBox2.Text += ("\t" + result + "\r\n");
Here is the Ruby code I'm trying to reproduce:
# Get our libraries
require 'httparty'
require 'json'
# Get our input from the command line
input = ARGV[0]
# Loop through the file
File.open("#{input}", "r").each_line do |line|
# Request the URL
response = HTTParty.get("http://danielmiessler.com:44821/token/#{line.chomp}")
# Go through the responses
case response.code
when 400
print "Improper input…\n"
# Feel free to remove this line if you want to reduce output.
when 200
json = JSON.parse(response.body)
print "Your input is #{json['type']} of the word: #{json['value']}\n"
when 404
print "There is no meaning in your token…\n"
# Feel free to remove this line if you want to reduce output.
end
end
Any ideas how to make the calls based on the tokens in the file and output to the text box?
You can use HttpClient for that.
This is a minimal example to get you started:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
Console.WriteLine(
"First 50 countries listed by The World Bank...");
foreach (var country in readTask.Result[1])
{
Console.WriteLine(" {0}, Country Code: {1}, " +
"Capital: {2}, Latitude: {3}, Longitude: {4}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
Related
I made a code to "translate" paths or texts in general to the Git Bash syntax, at the time I didn't know that I could just put them inside '', in the code I use the $ special character on a couple of strings, compile the code via csc filename.cs on cmd, it gives me the .exe and its all great, today I go make some minor changes on the code and when I run the same code to compile it gives me:
GiTranslator.cs(59,62): error CS1056: Unexpected character '$'
GiTranslator.cs(71,25): error CS1056: Unexpected character '$'
GiTranslator.cs(72,25): error CS1056: Unexpected character '$'
GiTranslator.cs(73,25): error CS1056: Unexpected character '$'
so, why? And what can I do to fix it?
note: the minor changes were literally just some spelling on comments.
edit 1: as asked, the code(it is probably terrible, sorry):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Git_Path_Translator
{
class Program
{
#region Functions
static void actuallyResetColors()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.Write(".");
Console.Clear();
}
#endregion
#region Global Variables
static string path;
static bool repetTranslation;
static bool repetAfterExcep;
#endregion
[STAThread] // don't know what it does, but its needed, classic right?
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Title = "Path Translator for Git Bash - by Tom Zamataro"; // just some credit to me, that no one is going to see, classic right?
Console.Clear();
// set up for the API loop
do
{
repetTranslation = false;
path = "";
Console.WriteLine("\n Inform the path you would like to translate to Git Bash syntax:");
Console.Write("\n "); // just for aesthetics, class... sory, no more classic joke tho, right? yes, I've a lot of shit in my head
// set up for the exception handling loop
do
{
repetAfterExcep = false;
try
{
if (path == "")
{
path = Console.ReadLine();
}
#region The Translation
string[] metaChars = new string[] { #"\", " ", "<", ">", "&", ";","*",
"?", "#", ".", "~", "|", "!", "$", "(", ")", "[", "]", "{", "}", "'", "\"" }; // the meta characters that I've to deal with
foreach (string meta in metaChars)
{
// backslash is the special case in this contex
if (meta == #"\") { path = path.Replace(meta, "/"); }
// the rest
else { path = path.Replace(meta, $#"\{meta}"); }
}
path = path.Trim(new char[] { '\'', '"' }); // jusr making sure, ..., what? I didn't say anything
/*
* the fist way I did, yes, much worse, you know alredy, right?
* path = path.Trim().Replace(#"\", "/").Replace(" ", #"\ ").Replace("(", #"\(").Replace(")", #"\)"); // taking of the spaces and putting '\' where its needed
* path = path.Replace("[", #"\[").Replace("]", #"\]").Replace("{", #"\{").Replace("}", #"}]").Trim('"'); // nor sure if
*/
#endregion
Clipboard.SetText(path); // coping it to the user's clipboard
Console.WriteLine
(
$"\n The path was translated to:" +
$"\n\n {path}" +
$"\n\n and it is alredy copied to your clipbord."
); // just a bit more of aestheticness, yeah, ..., go on continue throught the code
}
catch (ArgumentNullException)
{
Console.Clear();
Console.WriteLine("\n Please inform a non-null value so the translation is possible," +
"\n if you would like to finish the solution, press enter:");
Console.Write("\n "); // same thing as before, just for aesthetics
if ((path = Console.ReadLine()) == "")
{
// didn't want to a valid translation
actuallyResetColors(); // Console.ResetColor() isn't all that great on doing its job, so, yeah
Console.Write("\n "); // aesthetic for VS console
Environment.Exit(0);
}
else { repetAfterExcep = true; } // did want to do a valid translation
}
} while (repetAfterExcep); // exception handling loop
Console.Write
(
"\n Type anything and press enter to make another translation,\n" +
" or press enter to finish the solution: "
); // asking for the loop
if (Console.ReadLine() == "")
{
// didn't want to do another translation
actuallyResetColors(); // Console.ResetColor() isn't that great on doing its job, so, yeah
Console.Write("\n "); // aesthetics for VS console
Environment.Exit(0);
}
// did want to do another translation
repetTranslation = true;
Console.Clear();
} while (repetTranslation); // API loop
}
}
}
edit 2: maybe useful information, I can normally run the code on VS, but when I try to compile it via csc filename.exe it gives me that error.
edit 3: so,
well, I don't know what to think or say about that.
I'm working on a project, where you have to retrieve data from a server and display it in the UI. It's a newsgroups server, that contains about 250 groups in total.
The output from the server SHOULD as far as I understand, be stored in a NetworkStream object and is read from a StreamReader which saves each line into a string.
This works, but unfortunately it seems like it doesn't finish reading everything before finishing the method call.
Next time I call another command and read it from the StreamReader it then returns the rest of the output from the previous command.
I've been struggling with this for hours now, and can't see how to fix this.
This is my code:
public ObservableCollection<Newsgroup> GetNewsGroups()
{
ObservableCollection<Newsgroup> newsgroups = new ObservableCollection<Newsgroup>();
if(connectionStatus.Equals(ConnectionStatus.CONNECTED) && loginStatus.Equals(LoginStatus.LOGGED_IN))
{
byte[] sendMessage = Encoding.UTF8.GetBytes("LIST\n");
// Write to the server
ns.Write(sendMessage, 0, sendMessage.Length);
Console.WriteLine("Sent {0} bytes to server...", sendMessage.Length);
ns.Flush();
// b) Read from the server
reader = new StreamReader(ns, Encoding.UTF8);
// We want to ignore the first line, as it just contains information about the data
string test = reader.ReadLine();
Console.WriteLine(test);
string recieveMessage = "";
if (ns.CanRead)
{
while (reader.Peek() >= 0)
{
recieveMessage = reader.ReadLine();
Console.WriteLine("Got this message {0} back from the server", recieveMessage);
// This part will simply remove the annoying numbers after the newsgroup name
int firstSpaceIndex = recieveMessage.IndexOf(" ");
string refactoredGroupName = recieveMessage.Substring(0, firstSpaceIndex);
newsgroups.Add(new Newsgroup { GroupName = refactoredGroupName });
}
}
}
return newsgroups;
}
I'd be interested to see what information about the data you are throwing away on the first line (what's in "test" variable). If it tells you how many bytes are coming your way, you should use that information to retrieve the correct amount of data instead of Peek.
If the last line contains a single period, change your while loop to look like this instead:
recieveMessage = reader.ReadLine();
while (recieveMessage != ".")
{
Console.WriteLine("Got this message {0} back from the server", recieveMessage); // This part will simply remove the annoying numbers after the newsgroup name int
firstSpaceIndex = recieveMessage.IndexOf(" ");
string refactoredGroupName = recieveMessage.Substring(0, firstSpaceIndex);
newsgroups.Add(new Newsgroup { GroupName = refactoredGroupName });
recieveMessage = reader.ReadLine();
}
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!
I have a windows application for sending SMS connecting to a GSM Modem. I only use AT Commands for connecting to port and sending text.
My problem is I can't send a message more that one part (each part is 160 characters for English and 70 characters for Farsi).
Here is the part I command the port to send sms using AT commands:
ExecCommand(port, "AT", 300, "No phone connected at " + strPortName + ".");
ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
var command = "AT+CSCS=\"" + "HEX" + "\"";
ExecCommand(port, command, 300, "Failed to support unicode");
ExecCommand(port, "AT+CSMP=1,167,0,8", 300, "Failed to set message properties.");
command = "AT+CMGS=\"" + phoneNo + "\"";
ExecCommand(port, command, 300, "Failed to accept phoneNo");
message = message.ToCharArray().Select(Convert.ToInt32).Select(value => String.Format("{0:X}", value)).Aggregate("", (current, hexOutput) => current + hexOutput.PadLeft(4, '0'));
command = message + char.ConvertFromUtf32(26) + "\r";
var recievedData = ExecCommand(port, command, 3000, "Failed to send message");
And here is ExecCommand method
public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
{
try
{
// receiveNow = new AutoResetEvent();
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
//Thread.Sleep(3000); //3 seconds
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw new ApplicationException(errorMessage, ex);
}
}
General AT command handling
You are on the right track, I am pleased to see several basic things done right (terminating AT command lines with \r, waiting for "\r\n> " for AT+CMGS, and waiting for the OK final result code instead of sleeping), very good start!
You do need however to change the structure somewhat. First you need to handle all the other final result codes and not just OK. And you should treat the AT+CMGS command differently from the other commands since you should wait for two things (first the prefix and later the final result code after sending the message text) for that command compared to waiting only for one thing (e.g. the final result code) for those. Also all responses from the modem are complete lines (except the "\r\n> " prefix), so change your algorithm to process the response(s) line by line.
String input;
do {
input = ReadLine(port, responseTimeout);
} while (!isFinalResultCode(input));
None of the commands you are using in the question produces an intermediate response for consumption, but if you were to run a command like AT+CPBR you would consume those intermediate responses inside that loop (and you would have to move the final result test into the loop before attempting to consume the line as an intermediate response).
You can see the is_final_result function in atinout or corresponding functions in ST-Ericsson's U300 RIL (see link and notes in this answer).
Multipart SMS
I think this is not possible in text mode. See the link suggested by Naser Asadi for details on multipart SMS in PDU mode. Also some useful information at
http://mobiletidings.com/2009/02/18/combining-sms-messages/ and http://developer.nokia.com/community/discussion/showthread.php/109602-Concatenated-SMS-in-PDU-Mode.
I'm new at SSDP/UPNP/Sockets and all that jazz. I'm playing around with it a bit and I just want to see what a generic SSDP search on my network will bring up.
Using this SSDP Sniffer app, I get a lot of results so I'm attempting to recreate this.
I'm using the following code, which I've found various versions of, but all the tweaking I do doesn't appear to bring back any results. I pretty much at a loss here and would appreciate any guidance.
thanks!
private const string SSDP_IP = "239.255.255.250";
private const string SSDP_PORT = "1900";
private const string SSDP_QUERY = "M-SEARCH * HTTP/1.1\r\n" +
"Host: " + SSDP_IP + ":" + SSDP_PORT + "\r\n" +
"Man: ssdp:discover\r\n" +
"ST: ssdp:all\r\n";
DataGramSocket socket;
async public void SsdpQueryAsync()
{
var remoteIP = new Windows.Networking.HostName(SSDP_IP);
var reqBuff = Encoding.UTF8.GetBytes(SSDP_QUERY);
socket = new DatagramSocket();
socket.MessageReceived += (sender, args) =>
{
// This is invoked for each device that responds to the query...
Task.Run(() =>
{
// do something useful
});
};
await socket.BindEndpointAsync(null, "");
socket.JoinMulticastGroup(remoteIP);
using (var stream = await socket.GetOutputStreamAsync(remoteIP, SSDP_PORT))
{
await stream.WriteAsync(reqBuff.AsBuffer());
}
await Task.Delay(5000);
}
I'm not familiar with C# or dotnet APIs, but I can see some details wrong with the M-SEARCH message:
MAN header must be enclosed in double quotes, so MAN: "ssdp:discover"\r\n
MX header is missing (required for multicast)
USER-AGENT header is missing
missing an empty line in the end
Header names are supposedly case insensitive, but I'd use upper case just in case...
See the Device Architecture reference pdf for more details