C# tweetinvi code 408 - c#

i am trying to learn connecting C# to Twitter by using tweetinvi.
i have no problem while connecting with Twitter Key and Twitter Token
then i debug my code, noticed null value on User.GetAuthenticatedUser()
however, i'm already authorize the twitter apps with my own twitter account.
Why does User.GetAuthenticatedUser() return Null Value ?
i got the following picture while trying to pass the error into Message Box
how do i resolve this ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tweetinvi;
namespace Twitdesk
{
public partial class Form1 : Form
{
Cl_Tweetinvi twitinvi;
Command cmd = new Command();
public Form1()
{
InitializeComponent();
twitinvi = new Cl_Tweetinvi();
var AuthenticatedUser = User.GetAuthenticatedUser();
if(AuthenticatedUser == null)
{
var latestException = ExceptionHandler.GetLastException();
MessageBox.Show(latestException.ToString());
Application.Exit();
}
else
{
var settings = AuthenticatedUser.GetAccountSettings();
}
var tweets = Timeline.GetHomeTimeline();
this.Text = cmd.title;
MessageBox.Show("done");
}
}
}

The problem comes from the fact that you have not initialized your credentials.
You need to call Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"); before performing any operation.
When you have invoked this line any operation will be using these credentials.
Please take a quick look at the wiki for more information. Or let me know if you still encounter any problem.
Though the problem could be different as the error message seems to indicate that you have a timeout problem. Normally authentication problems return 401 exception.

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

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

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.

Testing a web service by returning a string of data in a web application form

I've got a web service but need to know how to test it in a windows application form.
here is the start of the service. Would I put the form code inside a button, or just return it in a label? Not exactly overly clued into c# or .net I've called the web service succesfully thougha nd just need to return the string to make sure encryption is working.
<%# WebService Language="C#" Class="UserEncryptionLink.EncryptUserLink" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Text;
using System.Security.Cryptography;
namespace UserEncryptionLink
{
/// <summary>
/// This Web Service is to encrypt user details and display them in the URL when they click on a link taking them to InfoExchange
/// </summary>
[WebService(Namespace = " Webspace name")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EncryptUserLink : System.Web.Services.WebService
{
[WebMethod]
public void TestCypher()
{
var key = "12345";
var vector = "12345";
var username = "YOURDOMAIN\\YOURUSERNAME";
var url = "sitename.com";
var it = GetSingleSignOnUrl(url, username, key, vector);
}
And my form
Yeah I've got my form referencing the service, it looks like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FormForEncrypt.nameofURL;
using System.Net;
namespace FormForEncrypt
{
public partial class EncryptForm : Form
{
public EncryptForm()
{
InitializeComponent();
}
// creates an instance of the web service as a member of the class, will put it down below, doesn't seem to work though declared in the using statement
private nameofURL.EncryptUserLink userform = new nameofUrl.EncryptUserLink();
[System.Web.Services.WebMethod]
private void testButton_Click_1(object sender, EventArgs e)
{
//method to send on button click, then recieve the string to show it works, it should come out as http://CLIENTNAME.info-exchange.com/yyyyMMddHHmmssDomainUsername
//create instances of the details
string[] it;
//send string
//recieve string and display, it must display the same as what was sent.
}
}
}
Not sure what you mean if you should put the form code inside a button or return it in a label?
Webservices don't have concepts of forms or label or anything. They are just services... no forms, no controls... just somewhat "raw code" waiting to be served up by invoking it and your hosting protocol (such as IIS or WAS or self hosting app) takes care of spinning it up and running the service.
interms of calling it... well, it depends where you want to call it from your application. Could be on a button click, could be on a timer, could be on a form load... depends on you and your application logic.
your current web method, TestChypher, does not return anything at the moment. you need to, I am guessing, return a bool value to indicate if the string matches or not?
again, depends on you and what you want to return. if you wanted to return a string, change the method signature to return a string - so change "void" to "string" and return back, in that method, a string you want to return back.
example - short snip:
[WebMethod]
public void SayHello()
{
return "Hello";
}

Categories

Resources