Using TLSharp How to get UserProfilePhoto's photo? - c#

I'm using TLSharp for dealing with really complicated Telegram API.
it's hard to understand how xxxAbswww types can be converted to xxxwww types which contains the real usable information!
I have the code below:
TLUser user = client.MakeAuthAsync("<user_number>", hash, code).Result;
how can I get the photo of authenticated user?

Agha Hamed,
Users' photo is accessible using 'userProfilePhoto' Telegram method and TLSharp didn't implemented this method.
But TLSharp provided some fascilities to implement other Telegram API methods. They says:
You can call any method with help of SendRequestAsync function. For
example, send user typing method:
//Create request
var req = new TLRequestSetTyping()
{
action = new TLSendMessageTypingAction(),
peer = peer
};
//run request, and deserialize response to Boolean
return await SendRequestAsync<Boolean>(req);
Unfortunately I don't know how to use SendRequestAsync function to do this.

try this:
var photo = ((TLUserProfilePhoto)user.Photo);
var photoLocation = (TLFileLocation)photo.PhotoBig;
TLFile file = await client.GetFile(new TLInputFileLocation()
{
LocalId = photoLocation.LocalId,
Secret = photoLocation.Secret,
VolumeId = photoLocation.VolumeId
}, 1024 * 256);
//address to save pic
string fileName = "D:\\Project\\user_profile.jpg";
using (var m = new MemoryStream(file.Bytes))
{
var img = Image.FromStream(m);
//pictureBox1.Image = img; //make a preview
img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}

I dotn know why there is no example for TLSharp!
i am a newbe like you if you found the solution please post it here
i just discovered that TLUser has a method named "photo"

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.

How to call google.apis.dialogflow.v2 in C#

I am new to Google APIs. I want to know how to call Google Dialogflow API in C# to get intent form the input text. But I can't find any example to call Dialogflow using C#.
Please provide some example to call Dialogflow from C#.
If I understand your question correctly you want to call the DialogFlow API from within a C# application (rather than writing fulfillment endpoint(s) that are called from DialogFlow. If that's the case here's a sample for making that call:
using Google.Cloud.Dialogflow.V2;
...
...
var query = new QueryInput
{
Text = new TextInput
{
Text = "Something you want to ask a DF agent",
LanguageCode = "en-us"
}
};
var sessionId = "SomeUniqueId";
var agent = "MyAgentName";
var creds = GoogleCredential.FromJson("{ json google credentials file)");
var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
var dialogFlow = client.DetectIntent(
new SessionName(agent, sessionId),
query
);
channel.ShutdownAsync();
In an earlier version of the DialogFlowAPI I was running into file locking issues when trying to re-deploy a web api project which the channel.ShutDownAsync() seemed to solve. I think this has been fixed in a recent release.
This is the simplest version of a DF request I've used. There is a more complicated version that passes in an input context in this post:
Making DialogFlow v2 DetectIntent Calls w/ C# (including input context)
(Nitpicking: I assume you know DialogFlow will call your code as specified/registered in the action at DialogFlow? So your code can only respond to DialogFlow, and not call it.)
Short answer/redirect:
Don't use Google.Apis.Dialogflow.v2 (with GoogleCloudDialogflowV2WebhookRequest and GoogleCloudDialogflowV2WebhookResponse) but use Google.Cloud.Dialogflow.v2 (with WebhookRequest and WebhookResponse) - see this eTag-error. I will also mention some other alternatives underneath.
Google.Cloud.Dialogflow.v2
Using Google.Cloud.Dialogflow.v2 NuGet (Edit: FWIW: this code was written for the beta-preview):
[HttpPost]
public dynamic PostWithCloudResponse([FromBody] WebhookRequest dialogflowRequest)
{
var intentName = dialogflowRequest.QueryResult.Intent.DisplayName;
var actualQuestion = dialogflowRequest.QueryResult.QueryText;
var testAnswer = $"Dialogflow Request for intent '{intentName}' and question '{actualQuestion}'";
var dialogflowResponse = new WebhookResponse
{
FulfillmentText = testAnswer,
FulfillmentMessages =
{ new Intent.Types.Message
{ SimpleResponses = new Intent.Types.Message.Types.SimpleResponses
{ SimpleResponses_ =
{ new Intent.Types.Message.Types.SimpleResponse
{
DisplayText = testAnswer,
TextToSpeech = testAnswer,
//Ssml = $"<speak>{testAnswer}</speak>"
}
}
}
}
}
};
var jsonResponse = dialogflowResponse.ToString();
return new ContentResult { Content = jsonResponse, ContentType = "application/json" }; ;
}
Edit: It turns out that the model binding may not bind all properties from the 'ProtoBuf-json' correctly (e.g. WebhookRequest.outputContexts[N].parameters),
so one should probably use the Google.Protobuf.JsonParser (e.g. see this documentation).
This parser may trip over unknown fields, so one probably also wants to ignore that. So now I use this code (I may one day make the generic method more generic and thus useful, by making HttpContext.Request.InputStream a parameter):
public ActionResult PostWithCloudResponse()
{
var dialogflowRequest = ParseProtobufRequest<WebhookRequest>();
...
var jsonResponse = dialogflowResponse.ToString();
return new ContentResult { Content = jsonResponse, ContentType = "application/json" }; ;
}
private T ParseProtobufRequest<T>() where T : Google.Protobuf.IMessage, new()
{
// parse ProtoBuf (not 'normal' json) with unknown fields, else it may not bind ProtoBuf correctly
// https://github.com/googleapis/google-cloud-dotnet/issues/2425 "ask the Protobuf code to parse the result"
string requestBody;
using (var reader = new StreamReader(HttpContext.Request.InputStream))
{
requestBody = reader.ReadToEnd();
}
var parser = new Google.Protobuf.JsonParser(JsonParser.Settings.Default.WithIgnoreUnknownFields(true));
var typedRequest = parser.Parse<T>(requestBody);
return typedRequest;
}
BTW: This 'ProtoBuf-json' is also the reason to use WebhookResponse.ToString() which in turn uses Google.Protobuf.JsonFormatter.ToDiagnosticString.
Microsoft's BotBuilder
Microsoft's BotBuilder packages and Visual Studio template.
I havent't used it yet, but expect approximately the same code?
Hand written proprietary code
A simple example of incoming request code (called an NLU-Response by Google) is provided by Madoka Chiyoda (Chomado) at Github. The incoming call is simply parsed to her DialogFlowResponseModel:
public static async Task<HttpResponseMessage> Run([...]HttpRequestMessage req, [...]CloudBlockBlob mp3Out, TraceWriter log)
...
var data = await req.Content.ReadAsAsync<Models.DialogFlowResponseModel>();
Gactions
If you plan to work without DialogFlow later on, please note that the interface for Gactions differs significantly from the interface with DialogFlow.
The json-parameters and return-values have some overlap, but nothing gaining you any programming time (probably loosing some time by starting 'over').
However, starting with DialogFlow may gain you some quick dialog-experience (e.g. question & answer design/prototyping).
And the DialogFlow-API does have a NuGet package, where the Gactions-interface does not have a NuGet-package just yet.

Print using Google cloud printer API in C# MVC

I am trying to Print multiple file Using google cloud printer api.
I have integrate local printer to chrome://devices/
and try to implement Printer api from beloved link
https://github.com/lppkarl/GoogleCloudPrintApi
var provider = new GoogleCloudPrintOAuth2Provider(ClientId, SecreteKey);
var url = provider.BuildAuthorizationUrl(redirectUri);
var token = provider.GenerateRefreshTokenAsync(url, redirectUri);
var client = new GoogleCloudPrintClient(provider, token);
var request = new ListRequest { Proxy = proxy };
var response = client.ListPrinterAsync(request);
In this method I am not getting token or Authorization code from request url
and also try to implement print using Print to Google Cloud Print with dynamic URL
for (var i = 0; i < url.length; i++) {
var currenturl = url[i]
var gadget = new cloudprint.gadget();
gadget.setprintdocument("application/pdf", "pdf");
gadget.setprintdocument("url", "document title1", currenturl);
gadget.openprintdialog();
}
Above code is working fine for multiple files.
But it's asking for print for every files.
I want to print multiple file but it should be ask only first time and rest of queued file automatically add in queue for print.
I tried many ways, but no one give me success.
If anyone have any idea than it'll helpfull. Thank you

Convert to PDF method only works once

I'm using pechkin.synchronized to convert from HTML to PDF. On the first http request it works fine, but after that it gets stuck on the convert method and doesn't doesn't do anything after that.
Here's my controller action method:
public ActionResult ToPdf(int id)
{
var order = _orderBll.GetById(id);
var viewHtml = order.Body;
byte[] pdfBuf = new SimplePechkin(new GlobalConfig()).Convert(viewHtml);
return File(pdfBuf, "application/pdf");
}
Try using SynchronizedPechkin.
See:
Why my Web App hangs on the "easy to use" code example below?
Why my Web App hangs/crashes even after I've started using SynchronizedPechkin
Unfortunately, Pechkin is a dead project and has many unresolved issues. You can avoid these by using Tuespechkin's ThreadSafeConverter, Pechkin's development is continuing there.
Example:
IConverter converter =
new ThreadSafeConverter(
new PdfToolset(
new Win32EmbeddedDeployment(
new TempFolderDeployment())));
// Keep the converter somewhere static, or as a singleton instance!
// Do NOT run the above code more than once in the application lifecycle!
byte[] result = converter.convert(document);
I had the same problem with my application too. So i download Synchronized Pechkin from Nuget manager. Your code will look like:
using Pechkin;
using Pechkin.Synchronized;
public ActionResult ToPdf(int id)
{
var order = _orderBll.GetById(id);
var viewHtml = order.Body;
byte[] pdfBuf = new SynchronizedPechkin(new GlobalConfig()).Convert(viewHtml);
return File(pdfBuf, "application/pdf");
}

Desktop app to create event through a facebook page

I have a facebook fanpage and I am trying to make a desktop application which can create events through this fanpage, however I'm having trouble understanding how the story goes with acces tokens, id, user permissions... If I am not mistaken once I have the accesstoken I can create an event using the facebookSDK from codeplex and the following function:
public string CreateEvent(string accessToken)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString());
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString());
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
Add the event logo image
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\logo.jpg"
};
logo.SetValue(File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = facebookClient.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
Do I always need an application to do this?
I have a test application and I can get an access token from it using:
public string getToken(string strURL)
{
string strURL = "https://graph.facebook.com/oauth/access_token?client_id=149585851811979&client_secret=blablablablabalalbal&grant_type=client_credentials";
Uri Uri = new Uri(strURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse HWResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(HWResponse.GetResponseStream());
string token = sr.ReadToEnd();
sr.Close();
token = token.Replace("access_token=", "");
return token;
}
I tried it like this but it obviously didn't work.
So my questions:
Do I always need an application? If yes, how do i connect it to my existing fan page?
Where do I set my user permissions? And how do I then login with the user?
I just think the documentation is a bit vague :s Sorry if my questions are stupid.
Any help/pseudocode is appreciated!
I am using BatchFB to create events in an App Engine app, it works for me, here is the code
// Some Date math that is from my App, but I am using Joda DateTime for output
// formatting.. I have found that if the start_time is malformed by FB standards it will
// to create an event, and give you an eventid, but the event never really gets created.
long hour = { your data }
DateTime start_time = new DateTime(d).plusHours((int)hour);
String stime = start_time.toString(ISODateTimeFormat.dateTime());
Batcher batcher = new FacebookBatcher(token);
Later<NewFeedItem> event = batcher.post(
"/events", NewFeedItem.class,
new Param("name", edata.getStringProperty(EventData.Schema.Name)),
new Param("start_time", stime )
);
long eventid = event.get().id;
I generate token on the client side with FBJS, and pass it to the server.
NewFeedItem is just a class defining an long variable, see batchFB's site..
With that said, I am thinking of switching to RestFB because I can't get BatchFB to support binary parameters with trying to post images. Also RestFB is documented better.. They seem to be related projects and refer to each other often.
I am not adding in Venue data yet, but I have read that for the GraphAPI to work, they need to be top level parameters. i.e. add in street, city, state at the same level as location and privacy..
When you try to read the event it will come in the venue parameter, but it needs to be top level when creating.. Also fallback to just using name and start_time, the only required parameters and add to that once it's working.
-John Gentilin

Categories