.NET HBase REST API client library - calling from MVC5 Controller - c#

Looking at the sample code given on https://azure.microsoft.com/en-us/documentation/articles/hdinsight-hbase-tutorial-get-started/#use-the-net-hbase-rest-api-client-library,
I'm trying to connect to HBase from an MVC Controller as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace MyHBaseTest.Controllers
{
[RoutePrefix("api/myhbasetestcontroller")]
public class MyHBaseTestController : ApiController
{
HBaseReader hbase = new HBaseReader();
[HttpGet]
[Route("")]
public IHttpActionResult Index()
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername = "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
return Ok();
}
}
}
When I try to view the URL /api/myhbasetestcontroller in my browser when it is run in debug mode, it keeps loading the page forever without throwing any exception or anything in Visual Studio. I have waited for 15-20 minutes but nothing changes.
When I put try to do the same in a console application, it gets the version information in a matter of seconds though:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername= "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
}
}
}
I just don't understand how it makes a difference really.
Could you please advice?
Many thanks.

As of today, you need to run your calls on a background thread. I ran into this same exact issue. My calls are consolidated under a single function. I run that function on a background thread and everything works great.
// POST: api/Vizzini
[ResponseType(typeof(string))]
public async Task<IHttpActionResult> GetResponse(string tweet)
{
string s = await Task.Run(() =>
{
return ResponseEngine.GetBestResponse(tweet);
});
return Ok(s);
}

You are using blocking synchronous APIs, which won't work in the context of MVC/Web app (due to using wrong async context by default). You need to use async version of the methods. E.g. for GetVersion use GetVersionAsync.

Related

How to send a simple message using a twilio number with an ASP.NET MVC project?

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;
}
}
}

Google Vision API Document_Text_Detection

I am trying to develop C# Google Vision API function.
the code is supposed to compile into dll and it should run to do the following steps.
get the image from the image Path.
send the image to Google vision api
Call the document text detection function
get the return value (text string values)
Done
When I run the dll, However, it keeps giving me an throw exception error. I am assuming that the problem is on the google credential but not sure...
Could somebody help me out with this? I don't even know that the var credential = GoogleCredential.FromFile(Credential_Path); would be the right way to call the json file...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
var credential = GoogleCredential.FromFile(Credential_Path);
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
You just need to setup the environment variable GOOGLE_APPLICATION_CREDENTIALS as mentioned here
You mus have to mention you json file name in the environment variable as this.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
Your code would look like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
//var credential = GoogleCredential.FromFile(Credential_Path);
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
or you can send it through your Credential_Path variable.
for more details please visit Google Vision API Docs
You need to setup your environment in your console with code like this :
Windows Server:
$env:GOOGLE_APPLICATION_CREDENTIALS="File Path"
Linux Server :
export GOOGLE_APPLICATION_CREDENTIALS="File Path"
Hope it helps!

How do I make a command to store user input on a Discord Bot in C#?

I have a Discord Bot I made with Discord.net.
Currently I have a command that posts a string, but I wanted to make one that posted a string that was previously input by the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace SuccubusBot.Modules
{
public class Ping : ModuleBase<SocketCommandContext>
{
[Command("hold")]
public async Task PingAsync()
{
string oneL = "L";
await ReplyAsync(oneL);
}
}
}
My only experience with receiving user input is with console projects so I am unsure of what to do here.
A simple command that outputs what the user inputs could be written like this:
[Command("say")]
public async Task Say([Remainder] string echo)
{
// ReplyAsync is a method on ModuleBase
await ReplyAsync(echo);
}
Example usage would be (If your commands starts with prefix "!"):
!say Hello
The bot would output on the channels that it is allowed to type:
Hello
The key in this is the [Remainder] on the argument list. It tells the developer that the user will pass a command with a string after it.

this api script for a app for a site i made is not working

I need help with this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kbam_.API
{
class filea
{
public static string filea(string url) //this code right here
{
string contents;
var wc = new System.Net.WebClient();
contents = wc.DownloadString(url);
}
}
}
and yes I am authorized by kesbook uk to use this I'm the owner so I can use what I want http://kesbook.cf/autho
If you are querying a a RESTful API I would suggest using the Restsharp nugget package, it is much easier to use.

How to Generate Text File from API Source?

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

Categories

Resources