I am trying to use the TLsharp library to send a telegram via a simple C# console app. My program runs but i receive not messages. I have gone through the process of creating an app on the Telegram website and received the necessary hash id and code.Please assist
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeleSharp.TL;
using TLSharp;
using TLSharp.Core;
namespace TLsharpTest
{
class Program
{
const int apiId = 55xxx;
const int groupId = -167xxxxx;
const string apiHash = "220xxxxxxxx";
const string number = "27xxxxxxx";
static void Main(string[] args)
{
var client = new TelegramClient(apiId, apiHash);
client.ConnectAsync();
var hash = client.SendCodeRequestAsync(number);
var code = "55xxx"; // you can change code in debugger
var user = client.MakeAuthAsync(number, apiHash, code);
client.SendMessageAsync(new TLInputPeerUser() { user_id = groupId }, "TEST");
Console.ReadKey();
}
}
}
You should have the users's access_hash to send messages. It should look like this:
_client.SendMessageAsync(
new TLInputPeerUser()
{
user_id = channelUser.Id,
access_hash = channelUser.AccessHash
}
Related
When I upload the image for getting ocr by using the Azure Vision Cognitive services.
But it will show an exception while performing in azure vision ocr.
like this,
System.AggregateException : ComputerVisionErrorResponseException: Operation returned an invalid status code 'Forbidden'
using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Linq;
namespace ComputerVisionQuickstart
{
class Program
{
// Add your Computer Vision subscription key and endpoint
static string subscriptionKey = "PASTE_YOUR_COMPUTER_VISION_SUBSCRIPTION_KEY_HERE";
static string endpoint = "PASTE_YOUR_COMPUTER_VISION_ENDPOINT_HERE";
private const string READ_TEXT_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
static void Main(string[] args)
{
Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
Console.WriteLine();
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read API
ReadFileUrl(client, READ_TEXT_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("READ FILE FROM URL");
Console.WriteLine();
// Read text from URL
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
Console.WriteLine();
}
}
}
Anyone can provide solution for this issue.
I am trying to change and edit the code but it returns with exceptions errors in regards authentication errors. The username cannot be null as well as the category is not able to load the code. Another exception that is running on it is the Twilio.Exceptions.ApiExecution that requires a phone number.
The documentation is here: https://www.twilio.com/docs/sms/tutorials/server-notifications-csharp-mvc?code-sample=code-csv-list-of-phone-numbers-to-notify&code-language=csv&code-sdk-version=default
The video to build the code for integrating Twilio in an ASP.net MVC project is here: https://www.youtube.com/watch?v=ndxQXnoDIj8
The code excerpt is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Twilio.TwiML;
using Twilio.AspNet.Mvc;
namespace SendandReceiveSms.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS
public ActionResult SendSms()
{
var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
TwilioClient.Init("ACa4XXXXXXXXXX","77XXXXXXXXXX");
var to = new PhoneNumber(ConfigurationManager.AppSettings["+65XXXXXXXX"]);
var from = new PhoneNumber("+12053016835");
var message = MessageResource.Create(
to: to,
from: from,
body: "Conserve with us and save the Wolrd ");
return Content(message.Sid);
}
public ActionResult ReceiveSms()
{
var response = new MessagingResponse();
response.Message(" We turn waste into environmental assets");
return TwiML(response);
}
}
}
You can try this also.
using DocGen.Notifications.Contract;
using DocGen.Notifications.Models;
using System;
using System.Configuration;
using System.Linq;
using System.Text;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace DocGen.Notifications.Providers
{
public class SmsNotificationProvider : INotificationProtocolContract
{
NotificationResponseModel notificationResponseModel = new NotificationResponseModel();
public NotificationResponseModel SendNotification(NotificationRequestModel notificationRequestModel)
{
if (notificationRequestModel.SmsTo == null || notificationRequestModel.SmsTo.Count() == 0)
throw new ArgumentNullException(nameof(notificationRequestModel.SmsTo));
TwilioClient.Init(ConfigurationManager.AppSettings["accountSid"], ConfigurationManager.AppSettings["authToken"]);
foreach (var Sms_to in notificationRequestModel.SmsTo)
{
var to = new PhoneNumber(Sms_to);
var message = MessageResource.Create(
to,
from: new PhoneNumber(ConfigurationManager.AppSettings["senderNumber"]),//"+12563054795"
body: Encoding.UTF8.GetString(notificationRequestModel.Message));
notificationResponseModel.ResponseMessage = message.Status.ToString();
}
//notificationResponseModel.ResponseMessage = "Message Successfully sent.";
return notificationResponseModel;
}
}
}
I have a situation where I need to send JSON data (a JSON file, not convert to JSON) to Time Series Insights via Event Hubs. But I am not able to send the data due to my lack of experience in C#.
I am able to send other sample messages but not JSON. How can I do that?
Any help or insight would be appreciated.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;
using Microsoft.ServiceBus.Messaging;
namespace ConsoleApp5
{
class Program
{
static string _connectionString = "Endpoint..;
static async Task MainAsync(string[] args)
{
var client = EventHubClient.CreateFromConnectionString(_connectionString, "eventhub");
var json = File.ReadAllText(#"C:\Users\Shyam\Downloads\personal.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await EventHubClient.SendAsync(eventData);
}
}
}
It throws an error in the async method though.
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'EventHubClient.SendAsync(EventData)' ConsoleApp5 C:\Users\Shyam\source\repos\ConsoleApp5\ConsoleApp5\Program.cs 21 Active
UPDATE:
namespace jsonData
{
using System;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
public class Program
{
private static EventHubClient eventHubClient;
private const string EhConnectionString = "Endpoint=sb://";
private const string EhEntityPath = "hub";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
// Typically, the connection string should have the entity path in it, but this simple scenario
// uses the connection string from the namespace.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
{
EntityPath = EhEntityPath
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
var json = File.ReadAllText(#"D:\Sample.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);
await eventHubClient.CloseAsync();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
}
}
Wrap your events into a JSON array:
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms))
{
// Wrap events into JSON array:
sw.Write("[");
for (int i = 0; i < events.Count; ++i)
{
if (i > 0)
{
sw.Write(',');
}
sw.Write(events[i]);
}
sw.Write("]");
sw.Flush();
ms.Position = 0;
// Send JSON to event hub.
EventData eventData = new EventData(ms);
eventHubClient.Send(eventData);
}
Reference: learn.microsoft.com/time-series-insights-send-events
I'm sure you have figured this out by now but you're problem is not with JSON, it's with how you're using the event hub client.
Instead of this line:
await EventHubClient.SendAsync(eventData);
it should be this:
await client.SendAsync(eventData);
JSON is just a string for Event Hubs, so as simple as
var json = File.ReadAllText("myfile.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);
I have a small problem. I just recently started using Twilio's API to generate a record of messages that was sent to my assigned SID and Auth Token. However my question is how can I generate a text file, based off of what the console writes from the source its addressed to?
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Twilio;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "X";
string AuthToken = "X";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
// Build the parameters
var options = new MessageListRequest();
options.From = "2015-07-01";
options.To = "2015-07-13";
var messages = twilio.ListMessages(options);
foreach (var message in messages.Messages)
{
Console.WriteLine(message.Body);
Console.Read();
}
}
}
}
Writing to a text file is pretty much boilerplate. The methods are shown here:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
I am trying to get details of a Dongle (GSM Modem) using LibUSBDotNet library (here it is).
Following is my attempt
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibUsbDotNet;
using LibUsbDotNet.Descriptors;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Info;
using LibUsbDotNet.LibUsb;
using LibUsbDotNet.LudnMonoLibUsb;
using LibUsbDotNet.Main;
using LibUsbDotNet.WinUsb;
namespace LibUsbDotNet_Test1
{
class Program
{
static void Main(string[] args)
{
//RetrieveUSBDevices(12d1, 140c);
}
public static void RetrieveUSBDevices(int vid, int pid)
{
var usbFinder = new UsbDeviceFinder(vid, pid);
var usbDevices = new UsbRegDeviceList();
var en = usbDevices.GetEnumerator();
while (en.MoveNext())
{
Console.WriteLine(en.ToString());
}
}
}
}
Unfortunately, it seems like I need to pass the Product ID (PID) and Vensor ID (VID) as integers. But my PID and VID contains letters! Please have a look at the below image, which is showing details about my device.
How can I pass my PID and VID in this case? Or I am doing something wrong? I need to print the device description and get the "port name" of the dongle and that's why I am doing all these to identify it.
It would seem the VendorID and ProductID are hexadecimal numbers, but the library you are using wants integer numbers.
string productID = "140c";
int pid = Convert.ToInt32(productID, 16);
// or if you don't like "base 16" and want to have self-documenting code:
pid = Int32.Parse(productID, System.Globalization.NumberStyles.HexNumber);