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);
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 working on a method to asynchronously read the contents of a json file ( containing an array of json objects) and insert it into a mongodb collection but I cannot figure out what the issue is. There is no error when debugging, but my collection is still empty.
public async void InsertDocumentsInCollection(string File)
{
string text = System.IO.File.ReadAllText(File);
IEnumerable<BsonDocument> doc = BsonSerializer.Deserialize<BsonArray>(text).Select(p => p.AsBsonDocument);
//Name of the collection is Cars
var collection = _database.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(doc);
}
i tried to reproduce the issue with the following, but it works just fine. maybe it's something wrong with the contents of the text file. can you post a sample of the file?
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace StackOverflow
{
public class Program
{
private static async Task Main(string[] args)
{
var content = File.ReadAllText("E:\\Downloads\\cars.txt"); //https://mongoplayground.net/p/LY0W7vjDuvp
var docs = BsonSerializer.Deserialize<BsonArray>(content).Select(p => p.AsBsonDocument);
var collection = new MongoClient("mongodb://localhost")
.GetDatabase("test")
.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(docs);
}
}
}
So I want to write a BTC converter app, I can get the value of it for £1 at https://blockchain.info/tobtc?currency=GBP&value=1
And changing the GBP to USD in the URL changed it to USD naturally, I want to use this and parse the data into a variable and then have it used as a normal. But I want the user to be able to enter their currency and have the url change and then fetch the amounnt in say one canadian dollar. How can I use the GBP as a variable and then have it change depending on user input.
I'm thinking a dropdown box of most popular currencys but I wouldn't know how to use that at all.
Be kind, I'm a noob and trying to make my first useful application
Here is a simply example how you can get the value for the different currencies:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp5
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetValueAsync("GBP").Result);
Console.WriteLine(GetValueAsync("USD").Result);
Console.WriteLine(GetValueAsync("RUB").Result);
}
public static async Task<string> GetValueAsync(string curr)
{
using (HttpClient client = new HttpClient())
{
var responseString = await client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
return responseString;
}
}
}
}
Here
client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
is sending asynchronous http get request by the provided URL and returning response as a string.
The site you want to use is returning just the value as a string that's why this is working.
As the request is asynchronous we must use await so that we get response in string.
If you want to do this in WinForm. Here is example. Let's assume that you have already TextBox for input value, Label for showing result and Button for Getting result. They can be added by just drop and down from Toolbox to your form.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_ClickAsync(object sender, EventArgs e)
{
string curr = textBox1.Text;
if (!string.IsNullOrEmpty(curr))
{
label2.Text = "waiting for response";
var res = await GetValueAsync(curr);
label2.Text = res;
}
}
public async Task<string> GetValueAsync(string curr)
{
var responseString = string.Empty;
using (HttpClient client = new HttpClient())
{
string reqString = "https://blockchain.info/tobtc?currency=" + curr + "&value=1";
responseString = await client.GetStringAsync(reqString);
}
return responseString;
}
}
}
Here is the full solution for Win Forms link
Here are useful links for you:
MSDN HttpClient GetStringAsync
WinForm with Async Methods
MSDN C# String Concatenation
MSDN WinForms Click Event
Here is a recording how to do this also:
Recording
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
}
Following this link How to obtain a list of workspaces using Rally REST .NET
I tried the example however when I try to query against sub["Workspaces"] I get the error
RuntimeBinderException was unhandled;
The best overloaded method match for 'Rally.RestApi.RallyRestApi.Query(Rally.RestApi.Request)' has some invalid arguments
I cannot find any other ways to gather a list of workspaces from the subscription using the RallyApi dll for .Net which I obtained from the link provided.
Any help will be much appreciated.
Try to modify that code as follows:
Request wRequest = new Request(sub["Workspaces"]);
QueryResult queryResult = restApi.Query(wRequest);
Here is an entire app:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace Rest_v2._0_test
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//get the current subscription
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
//query the Workspaces collection
QueryResult queryResult = restApi.Query(wRequest);
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine( workspaceName + " " + workspaceReference);
}
}
}
}