creating a github issue in octokit.net - c#

I am trying to write a script that will open an issue typed in the console.
For some reason the issue variable comes back empty in the debugger.
class Program
{
public async static Task Main()
{
var client = new GitHubClient(new ProductHeaderValue("test-app"));
var user = await client.User.Get("medic17");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
var exampleIssue = new NewIssue("test body");
var issue = await client.Issue.Create("owner","name", exampleIssue);
}
}
APIKeys holds my token.
Thanks

I found a solution hope this helps someone else as well.
class Program
{
public async static Task Main()
{
// client initialization and authentication
var client = new GitHubClient(new ProductHeaderValue("<anything>"));
var user = await client.User.Get("<user>");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
// user input
Console.WriteLine("Give a title for your issue: ");
string userIssueTitle = Console.ReadLine().Trim();
Console.WriteLine("Describe your issue:", Environment.NewLine);
string userIssue = Console.ReadLine().Trim();
// input validation
while (string.IsNullOrEmpty(userIssue) || string.IsNullOrEmpty(userIssueTitle))
{
Console.WriteLine("ERROR: Both fields must contain text");
Console.ReadLine();
break;
}
var newIssue = new NewIssue(userIssueTitle) { Body = userIssue };
var issue = await client.Issue.Create(<owner>, <repo> newIssue);
var issueId = issue.Id;
Console.WriteLine($"SUCCESS: your issue id is {issueId} ");
Console.ReadLine();
}
}
Note
You need to store your keys in a separate file and write a class for it so your authentication flow might be different.
Note 2
You must replace all text with real values.

Still a little confused the app is OpenSource for transport since it deals with HIPPA data, users who want to use it need GitHub account if they want to do any error reporting. I assume I don’t share the authToken in the source of the project but the desktop Binary needs it plus the users GitHub login and password. Any pointers? I have tried just using username password that gets entered when creating issue but that fails with “not found”. It seems like any secret that gets deployed with binary app is potentially an issue.

Related

gRPC StarLink Router .Net

New Info:
I thought I would paste this in full as I can not seem to find any samples on the web of a c# solution for StarLink so hopefully anyone else looking for something may find this helpful and may contribute.
My New Proto File - (partial) - I took the advise of Yuri below. Thanks for the direction here. I was able to I have been using this tool and it has brought a lot of insight but I am still stuck on the c# side of the solution. I am an old VB.Net developer though I have done a bunch in c# I am by no means savvy in it and am probably missing something so simple. Again, any insight would be awesome. I can not post the full proto here as stack has char limit on posts. this is the first bit with messages etc. I can post more if it helps but trying to keep it to the important part.
syntax = "proto3";
option csharp_namespace = "SpaceX.API.Device";
package SpaceX.API.Device;
service Device {
//rpc Handle (.SpaceX.API.Device.Request) returns (.SpaceX.API.Device.Response) {}
//rpc Stream (stream .SpaceX.API.Device.ToDevice) returns (stream .SpaceX.API.Device.FromDevice) {}
rpc Handle (Request) returns (Response);
rpc Stream (Request) returns (Response);
}
message ToDevice {
string message = 1;
}
message Request {
uint64 id = 1;
string target_id = 13;
uint64 epoch_id = 14;
oneof request {
SignedData signed_request = 15;
RebootRequest reboot = 1001;
SpeedTestRequest speed_test = 1003;
GetStatusRequest get_status = 1004;
AuthenticateRequest authenticate = 1005;
GetNextIdRequest get_next_id = 1006;
GetHistoryRequest get_history = 1007;
GetDeviceInfoRequest get_device_info = 1008;
GetPingRequest get_ping = 1009;
SetTrustedKeysRequest set_trusted_keys = 1010;
FactoryResetRequest factory_reset = 1011;
GetLogRequest get_log = 1012;
SetSkuRequest set_sku = 1013;
UpdateRequest update = 1014;
GetNetworkInterfacesRequest get_network_interfaces = 1015;
PingHostRequest ping_host = 1016;
GetLocationRequest get_location = 1017;
EnableFlowRequest enable_flow = 1018;
GetHeapDumpRequest get_heap_dump = 1019;
RestartControlRequest restart_control = 1020;
FuseRequest fuse = 1021;
GetPersistentStatsRequest get_persistent_stats = 1022;
GetConnectionsRequest get_connections = 1023;
FlushTelemRequest flush_telem = 1026;
StartSpeedtestRequest start_speedtest = 1027;
GetSpeedtestStatusRequest get_speedtest_status = 1028;
ReportClientSpeedtestRequest report_client_speedtest = 1029;
InitiateRemoteSshRequest initiate_remote_ssh = 1030;
SelfTestRequest self_test = 1031;
SetTestModeRequest set_test_mode = 1032;
DishStowRequest dish_stow = 2002;
DishGetContextRequest dish_get_context = 2003;
DishSetEmcRequest dish_set_emc = 2007;
DishGetObstructionMapRequest dish_get_obstruction_map = 2008;
DishGetEmcRequest dish_get_emc = 2009;
DishSetConfigRequest dish_set_config = 2010;
DishGetConfigRequest dish_get_config = 2011;
StartDishSelfTestRequest start_dish_self_test = 2012;
WifiSetConfigRequest wifi_set_config = 3001;
WifiGetClientsRequest wifi_get_clients = 3002;
WifiSetupRequest wifi_setup = 3003;
WifiGetPingMetricsRequest wifi_get_ping_metrics = 3007;
WifiGetDiagnosticsRequest wifi_get_diagnostics = 3008;
WifiGetConfigRequest wifi_get_config = 3009;
WifiSetMeshDeviceTrustRequest wifi_set_mesh_device_trust = 3012;
WifiSetMeshConfigRequest wifi_set_mesh_config = 3013;
WifiGetClientHistoryRequest wifi_get_client_history = 3015;
TransceiverIFLoopbackTestRequest transceiver_if_loopback_test = 4001;
TransceiverGetStatusRequest transceiver_get_status = 4003;
TransceiverGetTelemetryRequest transceiver_get_telemetry = 4004;
}
reserved 1025, 3011, 3014;
}
message SignedData {
bytes data = 1;
bytes signature = 2;
}
My New .cs
I have tried many things from Microsoft's examples to thing I can gather from other samples. I simply can not get it to work and am lost. Again, any insight would be amazing and hopefully helpful to others looking for a solution in c#. You will see my commented code of this I have been playing with. Basically I am attempting to achieve three things and have made some movement in one of them.
Goals:
1 - Use Server Reflection to discover services.
I think I got this one resolved with dot-net grpc.
2 - Simply want to check available methods under a service and potentially either check or generate a new .proto file in case things change. StaLink does not publish its proto schema so I assume it could change anytime without warning.
3 - Just run any one of the available methods. I have tried the GetDeviceInfoRequest but can not seem to construct the request message properly. I have not been able to get this accomplishe in the gRPCurl tool either. I can do it on the basic service shown by Microsoft of course but these methods seem to be more complex and I simply get all kinds of errors.
Again, any insight or assistance would be amazing. Thanks to any and all in advance.
New .cs File
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Reflection.V1Alpha;
using ServerReflectionClient = Grpc.Reflection.V1Alpha.ServerReflection.ServerReflectionClient;
using SpaceX.API.Device;
public class Program
{
static async Task Main(string[] args)
{
//SETUP CHANNEL AND CLIENT
using var channel = GrpcChannel.ForAddress("http://192.168.100.1:9200");
var client = new ServerReflectionClient(channel);
var StarLinkClient = new Device.DeviceClient(channel);
//using var call = StarLinkClient.StreamAsync(new ToDevice { Request = GetDeviceInfoRequest });
//await foreach (var response in call.ResponseStream.ReadAllAsync())
//var request = Device.GetDeviceInfoRequest;
//var reply = await StarLinkClient.HandleAsync(
// new Request {'"getDeviceInfo" : {} '});
//Console.WriteLine(reply.Message);
//=============================================SERVER REFLECTION=============================================================
Console.WriteLine("Calling reflection service:");
var response = await SingleRequestAsync(client, new ServerReflectionRequest
{
ListServices = "" // Get all services
});
Console.WriteLine("Services:");
foreach (var item in response.ListServicesResponse.Service)
{
Console.WriteLine("- " + item.Name);
Console.WriteLine();
var StarLink = item.Name;
//Console.WriteLine(StarLink.getStatus());
}
//=============================================SERVER REFLECTION=============================================================
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
void setupchannel()
{
}
private static Task SingleRequestAsync(ServerReflectionClient client, Metadata metadata)
{
throw new NotImplementedException();
}
private static async Task<ServerReflectionResponse> SingleRequestAsync(ServerReflectionClient client, ServerReflectionRequest request)
{
using var call = client.ServerReflectionInfo();
await call.RequestStream.WriteAsync(request);
Debug.Assert(await call.ResponseStream.MoveNext());
var response = call.ResponseStream.Current;
await call.RequestStream.CompleteAsync();
return response;
}
}
Again, thanks in advance to anyone willing to assist here. Hopefully this helps others as well.

Usage of GetApiKeys in Amazon SDK

I am trying to get the total count of api keys in my API gateway via SDK.
However I am unsure on the proper implementation of the parameters that the GetApiKeysRequest takes in. My main objective is to get the count of all API keys that are already existing for my account.
The code I have so far looks like this :
class Program
{
public static void Main(string[] args)
{
var awsUserAccessKey = "xxxxx";
var awsUserSecretKey = "yyyyyyyyyyy";
var regionEndpoint = "us-west-2";
var keysInRepository = new GetApiKeysRequest
{
CustomerId = "",
IncludeValues = true||false,
Limit=0,
NameQuery = "",
Position = ""
};
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys =client.GetApiKeys(keysInRepository);
Console.Read();
}
}
This code throws an error saying that The security token included in the request is invalid (Amazon.APIGateway exception).I am unsure on how to set the parameters for this request.
Because the AmazonAPIGatewayClient you are using as described here takes three string arguments and the last one is awsSessionToken i think you are confusing with this one which takes as third argument RegionEndpoint
Do something like that instead :
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, RegionEndpoint.USWest2);
For someone looking for a solution to similar problems, this worked :
var awsUserAccessKey = "xxxx";
var awsUserSecretKey = "yyyyy";
var regionEndpointName = "us-west-2";
var regionEndpoint = RegionEndpoint.GetBySystemName(regionEndpointName);
var keysInRepository = new GetApiKeysRequest
{
Limit = 500
};
//define the key and its fields
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys = client.GetApiKeys(keysInRepository);
Console.WriteLine("Current number of api keys:{0}", apiKeys.Items.Count);

AWS Machine Learning RealTimePredictor returns UnknownoperationException in C#

Using Visual Studio, and AWS .NET V 3.0.
I'm trying to perform a real-time Predict operation, and to verify the basic setup works, I first perform a GetMLModel() which works and returns the endpoint (Somewhere in the documentation is was mentioned to use that result as the service endpoint, but it's the same that is listed in the console). Is has status "READY", so far so good.
The exception occurs below on the line below "Prediction P = RTP.Predict(Data)". Data contains a Dictionary with all the prediction values.
Error: Error making request with Error Code UnknownOperationException and Http Status Code BadRequest. No further error information was returned by the service.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate();
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
GetMLModelResponse MLMOdelResp = MLClient.GetMLModel("xxx"); // <-- WORKS
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
Console.WriteLine(MLConfig.ServiceURL);
MLConfig.Validate();
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data); // <----------------EXCEPTION HERE
}
(Obviously replace xxx with relevant values) :)
It turns out that this line:
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
cases the MLConfig.RegionEndpoint to be reset. Even though the documentation indicates the RegionEndpoint can be determined from the ServiceURL (I'm pretty sure I read that), the RegionEndpoint needs to be set again before the RTP.Predict(Data) call.
Once I figured that out, I was able to reduce the code to just this, in case anyone else needs help. I guess adding too much information to the Configuration is NOT a good thing, as the AWS. NET library seems to figure all this out on its own.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate(); // Just in case, not really needed
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data);
}

authorization error using linqtotwitter for streaming api

i'm trying to get a stream of tweets using LinqToTwitter library and the below c# code, but i get this error:
Error 401 Unauthorized
public static SingleUserAuthorizer auth;
static void Main(string[] args)
{
Task task = new Task(getStreamOfTweets);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void getStreamOfTweets()
{
auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = CUSTOMER_KEY,
ConsumerSecret = CUSTOMER_SECRET,
AccessToken = ACCESS_TOKEN,
AccessTokenSecret = ACCESS_TOKEN_SECRET
}
};
var context = new TwitterContext(auth);
int count = 0;
await (from strm in context.Streaming
where strm.Type == StreamingType.Filter
&& strm.Track == "federer"
select strm)
.StartAsync(async strm =>
{
string message =
string.IsNullOrEmpty(strm.Content) ?
"Keep-Alive" : strm.Content;
Console.WriteLine(
(count + 1).ToString() +
". " + DateTime.Now +
": " + message + "\n");
if (count++ == 5)
strm.CloseStream();
});
}
notes:
the permission in twitter app is "Read, Write and Access direct messages"
i can get tweet by REST API correctly
Please review the LINQ to Twitter FAQ, which has an extensive section on resolving 401 errors. That said, if it's working for the REST API, but not Streaming, that might narrow the options to try. Here are a couple things to try first:
Double check the keys to make sure you didn't accidentally add a space or lose a character on the ends.
Give a little time before trying again because sometimes too many accesses or failed attempts might cause them to deny your connection for a certain period of time.
Re: #2, try another stream, like Sample.
There are a lot of moving parts in play for using OAuth, so work through that list in case you might have missed something.
this issue happens because the time of windows was wrong.
If you copied & pasted from the Linq"Twitter sample code, make sure you have set properly all the keys:
ConsumerKey
ConsumerSecret
AccessToken
AccessTokenSecret
Then dont use "Application only" auth, use "user auth" instead for streaming which uses all of the above keys.
the issue was because the timing in PC was wrong

Can you use LiveSDK from Console Application?

I'm trying to make a console application which accesses my SkyDrive account, however I cannot figure out how to get the Live SDK working.
I'm running on Live SDK version 5.4 and this is the code I'm trying to run - the loginResult.Status is always "Unknown":
private static async Task<LiveConnectClient> ConnectToLive()
{
LiveAuthClient authClient = new LiveAuthClient("my live ID");
var loginResult = await authClient.IntializeAsync(new[] { "wl.basic" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
return new LiveConnectClient(loginResult.Session);
return null;
}
A few things I'm not certain about (since the SDK documentation is somewhat lackluster at best):
"My live ID" - is this just my e-mail address used for my personal Live account, or is it some sort of application specific ID that you have to create somewhere ?
Is InitializeAsync the proper method to call for authenticating ? All examples I've found mention a "LoginAsync", but that method is not available in the DLL.
Is it even possible to use the SDK outside of Windows Phone / Metro apps ?
I got the following code to work using a SkyDriveClient downloaded from http://skydriveapiclient.codeplex.com/releases/view/103081
static void Main(string[] args)
{
var client = new SkyDriveServiceClient();
client.LogOn("YourEmail#hotmail.com", "password");
WebFolderInfo wfInfo = new WebFolderInfo();
WebFolderInfo[] wfInfoArray = client.ListRootWebFolders();
wfInfo = wfInfoArray[0];
client.Timeout = 1000000000;
string fn = #"test.txt";
if (File.Exists(fn))
{
client.UploadWebFile(fn, wfInfo);
}
}

Categories