I was watching a tutorial on how to script a bot using C# and the instructor used (to my knowledge) an old call to TwitchClient which takes credentials and references. However, it is currently not the case and I'm wondering now what might be a good way to work around it. Currently, the method takes a websocket and logger but I have suspicion that you still need to use credentials and references.
Any help will be appreciated.
Here's the video with the timestamp: https://youtu.be/5f1T9hQqJps?t=8m3s
Instead of the single line in the video, these two lines should now achieve mostly the same effect:
client = new TwitchClient();
client.Initialize(credentials, "channel");
If you want to also enable logging (like in the video), then you will need to provide an instance of ILogger to the first call like so:
client = new TwitchClient(null, myLoggingInstance);
The WebSocket parameter is used for testing (so you can generate your own traffic to test your bot), the docs advise not to set this.
its quite simple actually, even the github page shows a simple example:
ConnectionCredentials credentials = new ConnectionCredentials("twitch_username", "access_token");
var clientOptions = new ClientOptions
{
MessagesAllowedInPeriod = 750,
ThrottlingPeriod = TimeSpan.FromSeconds(30)
};
WebSocketClient customClient = new WebSocketClient(clientOptions);
client = new TwitchClient(customClient);
client.Initialize(credentials, "channel");
client.OnLog += Client_OnLog;
client.Connect();
then later declare this function:
private void Client_OnLog(object sender, OnLogArgs e)
{
Console.WriteLine($"{e.DateTime.ToString()}: {e.BotUsername} - {e.Data}");
}
Related
I know this is possible using Puppeteer in js, but I'm wondering if anyone has figured out how to proxy on a page level in PuppeteerSharp (different proxies for different tabs)?.
it seems I can catch the request, but I'm not sure how to adjust the proxy.
page.SetRequestInterceptionAsync(true).Wait();
page.Request += (s, ev) =>
{
// what to do?
}
Edit
I am aware that I can set the proxy at the browser level like so;
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false,
Args = new[] { "--proxy-server=host:port" }
});
var page = await browser.NewPageAsync();
await page.AuthenticateAsync(new Credentials() { Username = "username", Password = "password" });
But this is not what I'm trying to do. I'm trying to set the proxy for each page within a single browser instance. I want to test lots of proxies so spawning a new instance of the browser just to set the proxy is too much overhead.
You can use different browser instances for each logical instances. I mean instead of trying to set different proxy for each page/tab with different proxy just create new browser instance and set proxy via launch args.
If this solution doesn't fit your needs, check this question. There is library for NodeJS which give ability to use different proxy per each page/tab. You can check that library source code and implement same things inside your C# application.
That library is using very simple method. Instead of sending requests via puppeter's browser/page library send request via nodejs http tools. It can be done by using method page.setRequestInterception. So library intercept each request from page, after that gather data and send request via http tools. I used C# a long time ago. So maybe I am wrong, but you can try to use HttpWebRequest or something similar. After you get result you should use method request.respond and pass response results there. In this way you can put any kind of proxy inside your application. Check here code of library.
The call to GetSystemDateAndTime works.
The call to GetDeviceInformation gives a bad request.
The WSDL is : https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl
I've tried numerous things and the error message doesn't help... Another application seems to successfully access the camera, but I couldn't figure out how they do it from their source code at : https://sourceforge.net/projects/onvifdm/
But since they can do it I believe there has to be a way... Or at least a way to identify why my code fails and their works, any help is very appreciated.
The code is :
Binding binding;
HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();
httpTransportBindingElement.AuthenticationScheme = AuthenticationSchemes.Digest;
binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8), httpTransportBindingElement);
DeviceClient deviceClient = new DeviceClient(binding, new EndpointAddress("http://192.168.0.15/onvif/device_service"));
deviceClient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
deviceClient.ClientCredentials.HttpDigest.ClientCredential.UserName = "username";
deviceClient.ClientCredentials.HttpDigest.ClientCredential.Password = "password";
var x = deviceClient.GetSystemDateAndTime();
var x2 = deviceClient.GetDeviceInformation(out string model, out string firmwareversion, out string serialnumber, out string hardwareId);
I have seen this occur if the time between the client and the server are outwith a certain range, usually just a few seconds. Ensure both are using the same NTP server and it might fix the problem.
Some clients get around this by usin the timestamp from the GetSystemDataAndTime call within the requests of other messages to get around this check.
On some cameras it is also possible to turn off the strict checks
I have a Console Application project written in C# which I've added Application Insights to with the following NuGet packages.
Microsoft.ApplicationInsights
Microsoft.ApplicationInsights.Agent.Intercept
Microsoft.ApplicationInsights.DependencyCollector
Microsoft.ApplicationInsights.NLogTarget
Microsoft.ApplicationInsights.PerfCounterCollector
Microsoft.ApplicationInsights.Web
Microsoft.ApplicationInsights.WindowsServer
Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel
I've configured my InstrumentationKey in the config file and I'm firing up a TelemetryClient on startup using the with the following code:
var telemetryClient = new TelemetryClient();
telemetryClient.Context.User.Id = Environment.UserName;
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
Everything is working well except AI is not capturing any requests that get sent to Mongo, I can see requests going off to SQL server in the 'Application map' but no sign of any other external requests. Is there any way that I can see telemetry of requests made to Mongo?
EDIT - Thanks to Peter Bons I ended up with pretty much the following which works like a charm and allows me to distinguish between success and failure:
var telemetryClient = new TelemetryClient();
var connectionString = connectionStringSettings.ConnectionString;
var mongoUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
mongoClientSettings.ClusterConfigurator = clusterConfigurator =>
{
clusterConfigurator.Subscribe<CommandSucceededEvent>(e =>
{
telemetryClient.TrackDependency("MongoDB", e.CommandName, DateTime.Now.Subtract(e.Duration), e.Duration, true);
});
clusterConfigurator.Subscribe<CommandFailedEvent>(e =>
{
telemetryClient.TrackDependency("MongoDB", $"{e.CommandName} - {e.ToString()}", DateTime.Now.Subtract(e.Duration), e.Duration, false);
});
};
var mongoClient = new MongoClient(mongoClientSettings);
I am not familiar with MongoDB but as far as I can tell there is no default support for it when it comes to Application Insights. But that does not mean you cannot do this, it will just involve some more code.
Again, I am not familiar with MongoDB but according to http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/ there is built-in support for logging the generated queries. Now, we only need to hook this up to Application Insights.
Since you already know how to use the TelemetryClient we can use the custom tracking methods provided by that class. See https://learn.microsoft.com/nl-nl/azure/application-insights/app-insights-api-custom-events-metrics for the available custom tracking methods.
All you need to do is to insert some code like this:
telemetryClient.TrackDependency(
"MongoDB", // The name of the dependency
query, // Text of the query
DateTime.Now, // Time that query is executed
TimeSpan.FromSeconds(0), // Time taken to execute query
true); // Indicates success
The class telemetryClient is thread-safe so you can reuse it.
Now, according to the referenced blogpost you should be able to do something like this:
var client = new MongoClient(new MongoClientSettings()
{
Server = new MongoServerAddress("localhost"),
ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(e =>
{
telemetryClient.TrackDependency(
"MongoDB", // The name of the dependency
e.Command.ToJson() // Text of the query
DateTime.Now, // Time that query is executed
TimeSpan.FromSeconds(0), // Time taken to execute query
true); // Indicates success
});
}
});
Again, I am not familiar with MongoDB but I hope this is a starting point for your imagination on how to adapt it to your needs using your knowledge of MongoDB.
EDIT:
If there is also a CommandCompletedEvent or similar event as opposed to the CommandStartedEvent event you should probably track the dependency there because you should then be able to calculate (or simpel read) the time spent and maybe get the actual value for the success indicator.
I understand this breaking change:
Use new SendGridMessage() instead of SendGrid.GetInstance()
However, when doing the following:
var transportWeb = Web.GetInstance(credentials);
I am told that GetInstance doesn't exist?
What's going on? Am I missing something?
Sorry, missed this one in the updated docs. You also need to use the constructor for the Web type instead of the old factory method.
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
The readme is now fixed as well. Thanks.
I am trying to register my application, which is written in C#, with Gracenote for my senior seminar class. I believe I have done it correctly, but to my understanding when I call a WebClient.UploadData() method, I should have what is returned displayed in my output window. Nothing came up.
Since you are supposed to register your application with Gracenote only once per installation, I'm kind of at a standstill since I'm not sure if it registered or not. Below is my code. [#####-AAAAAA is my ClientID provided by Gracenote.]
using (var client = new WebClient())
{
var dataToPost = Encoding.Default.GetBytes("<QUERIES><QUERY CMD=\"REGISTER\"><CLIENT>########-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</CLIENT></QUERY></QUERIES>");
var result = client.UploadData("https://c########.web.cddbp.net/webapi/xml/1.0/", "POST", dataToPost);
}
Try using my C# Gracenote API wrapper here http://www.nuget.org/packages/ParkSquare.Gracenote/