I'm currently trying to start with CoAP in C#. The library I'm using is CoAP.Net (→ https://github.com/smeshlink/CoAP.NET).
Unfortunately, I didn't even succeed with the example published in the "Quick Start"-Section on GitHub.
My Server Code:
class Program
{
static void Main(string[] args)
{
CoapServer server = new CoapServer();
server.Add(new HelloWorldRessouce());
server.Start();
}
}
and a ressource-class in the Server solution:
class HelloWorldRessouce : CoAP.Server.Resources.Resource
{
public HelloWorldRessouce() : base("hello-world")
{
Attributes.Title = "GET a friendly greeting!";
}
protected override void DoGet (CoapExchange exchange)
{
exchange.Respond("Hello World fron CoAP.NET!");
}
}
On the client-side I've got the following:
static void Main(string[] args)
{
CoapClient client = new CoapClient();
Request request = new Request(Method.GET);
//request.URI = new Uri("coap://[::1]/hello-world");
request.URI = new Uri("coap://192.168.178.48:5683/hello-world");
request.Send();
// wait for response
Response response = request.WaitForResponse();
}
Here is the Console-Output from the Server:
DEBUG - Starting CoAP server
DEBUG - BlockwiseLayer uses MaxMessageSize: 1024 and
DefaultBlockSize:512
DBEUG - Starting endpoint bound to [::ffff:0:0]:5683
Press any key...
Here is the Console-Output from the Client:
Console-Output - Client
I'm pretty sure, the problems are on the Client-side...
It would be awesome, if there's someone to help me get this example running. Or maybe, someone can give me a few Noob-Examples. The example-files don't really help me with this problem...
Thanks everybody...
Cheers, Mirco
Okay, it seems as if there was the dumbest user at work...^^
Server-side:
static void Main(string[] args)
{
CoapServer server = new CoapServer();
server.Add(new HelloWorldRessouce());
server.Start();
}
after "server.Start();" the program is finished and the server turns off.
By adding a "Console.ReadKey();" afterwards, everything is fine.
If someone has any noob-examples espacially about the configuration, they are still appreciated.
Thanks everybody ;)
Related
I al looking to capture network traffic and log responses/headers however I cannot seem to find any resources for achieving this in c#. Most if not all of the guides have been for JS or Python. I read that this functionality was not added into the c# version as of 2019 but no new news has been posted. Does anyone know how to get network logs from a ChromeDriver?
Wrong, in selenium 4 you can do that but it is still in beta
Through much effort and googling around I have created something in C# that seems to do what you want. My answer is an adaption of some C# and Java implementations found on the internet which I could not get to work on individually, but did provide some needed insight.
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
using Network = OpenQA.Selenium.DevTools.V108.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V108.DevToolsSessionDomains;
internal class Program
{
private static async Task Main(string[] args)
{
string url = "https://stackoverflow.com/questions/68582545/catching-network-traffic-with-selenium-c-sharp";
Uri uri = new Uri(url);
var driver = new ChromeDriver();
var devTools = (IDevTools)driver;
IDevToolsSession session = devTools.GetDevToolsSession();
var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
domains.Network.ResponseReceived += ResponseReceivedHandler;
Task task = domains.Network.Enable(new Network.EnableCommandSettings());
task.Wait();
driver.Navigate().GoToUrl(uri);
var name = Console.ReadLine();
Console.WriteLine("finished");
driver.Dispose();
void ResponseReceivedHandler(object sender,Network.ResponseReceivedEventArgs e)
{
Console.WriteLine("New Work Response received");
Console.WriteLine($"Response Status: {e.Response.Status}");
Console.WriteLine($"Status Text: {e.Response.StatusText}");
Console.WriteLine($"Response MimeType: {e.Response.MimeType}");
Console.WriteLine($"Response Url: {e.Response.Url}");
}
}
}
I hope this answer answers your question or at least helps someone in a similar situation.
You can use this approach in any selenium version and not wait for the Selenium 4 release.
https://www.automatetheplanet.com/webdriver-capture-modify-http-traffic/
If you want to do use a simular version like that one from Jeppe Holt, for Selenium 4+ without being version and browser specific try that one: (Works on Chrome and Edge with Selenium 4.8)
public void SetupNetworkLogging(IWebDriver driver)
{
NetworkManager manager = new NetworkManager(driver);
manager.NetworkResponseReceived += ResponseHandler;
manager.StartMonitoring();
}
private void ResponseHandler(object sender, NetworkResponseReceivedEventArgs e)
{
Console.WriteLine($"Http status: {e.ResponseStatusCode} : {e.ResponseBody} | Url: {e.ResponseUrl} ");
}
You can also experiment with a devtools session:
IDevTools devTools = driver as IDevTools;
var session = devTools.GetDevToolsSession();
var network = session.Domains.Network;
network.EnableNetwork();
network.EnableNetworkCaching();
According to the Docker for Windows FAQ, " clients can connect to the Docker Engine through a named pipe: npipe:////./pipe/docker_engine"
I have been trying to connect to the API via named pipes to no avail:
public class DockerNamedPipeTest
{
private const string PIPE_PATH = "docker_engine";
public void Test()
{
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(
".",
PIPE_PATH,
PipeDirection.InOut,
PipeOptions.WriteThrough,
TokenImpersonationLevel.Impersonation))
{
pipeClient.Connect(30);
Send(pipeClient);
Receive(pipeClient);
}
}
public void Send(NamedPipeClientStream pipeClient)
{
if (pipeClient.IsConnected)
{
byte[] buffer = Encoding.UTF8.GetBytes("GET /containers/json");
pipeClient.Write(buffer, 0, buffer.Length);
pipeClient.WaitForPipeDrain();
pipeClient.Flush();
}
}
public void Receive(NamedPipeClientStream pipeClient)
{
string result = string.Empty;
if (pipeClient.IsConnected && pipeClient.CanRead)
{
do
{
byte b = (byte)pipeClient.ReadByte(); // <-- Hangs here
result += Convert.ToChar(b).ToString();
}
while (!pipeClient.IsMessageComplete);
}
Console.WriteLine(result);
}
}
Can anyone tell me what I am doing wrong?
Microsoft's .NET client library for Docker supports named pipes, have you looked at that?
Here's an example:
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"))
.CreateClient();
It turns out that the answer can be found inside the source of the Docker.DotNet code, specifically in the DockerPipeStream.cs class in the method called CloseWrite():
(https://github.com/Microsoft/Docker.DotNet/blob/master/src/Docker.DotNet/DockerPipeStream.cs)
// The Docker daemon expects a write of zero bytes to signal the end of writes. Use native
// calls to achieve this since CoreCLR ignores a zero-byte write.
I adapted this method to my code and the code no longer hangs.
I now get a 400 Bad Request but at least now I know why the communication with the docker daemon was hanging. It would have been nice if the Docker for Windows FAQ had mentioned this nuance.
I am using Fiddler to catch updates sent to a page via LightStreamer. I am creating a FiddlerCore proxy and connecting a Selenium ChromeDriver instance to it. My automation navigates Chrome to the page, and data comes through the proxy.
Once loaded, the updates to the page (via LightStreamer) visibly appear on the page but they do not come through the AfterSessionComplete event.
If I run the Fiddler desktop application instead of launching my proxy (comment out "StartProxy()") all of the updates (via LightStreamer) come through and appear inside the application. They appear has HTTPS data, but other HTTPS data appears to come through.
I have also using tried the BeforeResponse event instead of AfterSessionCompleted.
Here's my code:
static void Main(string[] args)
{
StartProxy();
var seleniumProxy = new Proxy { HttpProxy = "localhost:8888", SslProxy = "localhost:8888" };
var chromeOptions = new ChromeOptions { Proxy = seleniumProxy };
var path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\ChromeDriver\\";
var chromeService = ChromeDriverService.CreateDefaultService(path);
var driver = new ChromeDriver(chromeService, chromeOptions);
driver.Navigate().GoToUrl("https://mywebpage.com");
// page loads and updates start flowing
Console.ReadLine();
driver.Dispose();
StopProxy();
}
private static void FiddlerApplication_AfterSessionComplete(Session session)
{
// data comes through, just not the LightStreamer Data
var respBody = session.GetResponseBodyAsString();
Console.WriteLine(respBody);
// do something with the response body.
}
static void StartProxy()
{
if (FiddlerApplication.IsStarted())
FiddlerApplication.Shutdown();
FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.DecryptSSL);
}
static void StopProxy()
{
FiddlerApplication.AfterSessionComplete -= FiddlerApplication_AfterSessionComplete;
if (FiddlerApplication.IsStarted())
FiddlerApplication.Shutdown();
}
Thanks for your help.
Update: I've also tried to use the flag: FiddlerCoreStartupFlags.Default instead of FiddlerCoreStartupFlags.DecryptSSL when starting fiddler with no luck.
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.
I try to approve non project time in a console application with the ApproveNonProjectTime method (http://msdn.microsoft.com/en-us/library/websvctimesheet.timesheet.approvenonprojecttime%28v=office.12%29.aspx).
My code is very simple :
class Program
{
const string projectServerUri = "http://morpheus-sp/pwa/";
const string resourceServicePath = "_vti_bin/psi/Timesheet.asmx";
static void Main(string[] args)
{
TimesheetWebSvc.TimeSheet timesheetSvc = new TimesheetWebSvc.TimeSheet();
timesheetSvc.Url = projectServerUri + resourceServicePath;
timesheetSvc.Credentials = CredentialCache.DefaultCredentials;
timesheetSvc.ApproveNonProjectTime(new Guid[] { new Guid("D6909043-18A7-4FF6-83BB-67EFDF17A279")}, null);
}
}
When I execute it I have this error message :
System.Web.Services.Protocols.SoapException: ProjectServerError(s) LastError=GeneralItemDoesNotExis
However I took the TS_LINE_UID directly in my DB and its status is Pending Approval.
Have you a solution ?
Thank you,
Justin