Program not responding from SearchListResponse - c#

I am trying to gather data of YouTube videos using a Winforms app. When I call YTSearch() method as seen below, The program stops responding when it gets to
var slResponse = await slRequest.ExecuteAsync();
The request is started, but does not stop, and is neither finished, nor triggering the catch on a try catch. I have managed to get the exact same thing working using a Discord bot, using Discord.NET. In the output is
Exception thrown: 'Google.GoogleApiException' in Google.Apis.dll
Exception thrown: 'Google.GoogleApiException' in mscorlib.dll
Exception thrown: 'Google.GoogleApiException' in mscorlib.dll`
Libraries:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Diagnostics;
Method:
public async Task<List<Video>> YTSearch(string query)
{
string ytAPI = APIKEY; // Ommitted
var ytService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = ytAPI,
ApplicationName = "YouTubeDownloader"
});
var slRequest = ytService.Search.List("snipper");
slRequest.Q = query;
slRequest.MaxResults = 10;
var slResponse = await slRequest.ExecuteAsync();
List<Video> vidList = new List<Video>();
return vidList;
}
Call:
private void btnSearch_Click(object sender, EventArgs e)
{
List<Video> vidList = YTSearch(txtSearch.Text).Result;
}

I haven't tested this, but I'm fairly sure you need to use ConfigureAwait(false). So in your YTSearch method you need to use the line:
var slResponse = await slRequest.ExecuteAsync().ConfigureAwait(false);
This is required because you are blocking for the result in the button handler, by using .Result.
This MSDN article is a little old, but explains the problem.

First off you have a small typo you should fix that is unrelated to your error. The first parameter is part valid values are
contentDetails: 2
id: 0
snippet: 2
You have snipper
It isn't clear that this is the issue as the error you are getting isn't related to the API.
The issue sounds more like a problem with the dll. I would try to reimport the nuget package make sure you are using.net 4.5 in your project

Related

C# ScrapySharp 'System.Net.CookieException: 'The 'Name'='HttpOnly, NID' part of the cookie is invalid.'

So i'm facing an unexpected issue with my code. For some reason, I am unable to download & print the links out of my Google search... Help is much appreciated as I'm really not sure what is going on here... I am also using the DotNET SDK
using System;
using System.Threading.Tasks;
using ScrapySharp;
using ScrapySharp.Extensions;
using ScrapySharp.Network;
using static System.Console;
namespace Test
{
class Program
{
static async Task Main(string[] args)
{
var query = "scrapysharp";
Console.WriteLine($"Searching '{query}' on google");
var browser = new ScrapingBrowser();
browser.UseDefaultCookiesParser = false;
var resultsPage = await browser.NavigateToPageAsync(new Uri($"https://www.google.fr/search?q={query}"));
Console.WriteLine($"Results");
foreach (var link in resultsPage.Html.CssSelect("h3.r a"))
{
Console.WriteLine($"- {link.InnerText}");
}
}
}
Error:
System.Net.CookieException: 'The 'Name'='HttpOnly, NID' part of the cookie is invalid.'
I was facing the same issue, the quick workaround for me was bellow one line code.
browser.IgnoreCookies = true;
Leave everything else as is, add this line after the line where you are creating browser object and try it out.

C# tweetinvi code 408

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.

Lucene.Net Query Error

I've just installed Solr/Lucene on a Windows machine simply to test its capability. I've indexed a couple hundred files and I'm able to successfully query the indexed content through the web interface. Given that the web interface isn't too user friendly I thought I'd try to create a simple application to do a full text search over the indexed content. So far I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Lucene.Net;
namespace solrTest
{
class Program
{
static void Main(string[] args)
{
string indexFileLocation = #"C:\solr-5.3.1\server\solr\test\data\index";
Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.Open(indexFileLocation);
Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
Lucene.Net.Index.Term searchTerm = new Lucene.Net.Index.Term("ID", "1");
Lucene.Net.Search.Query query = new Lucene.Net.Search.TermQuery(searchTerm);
Lucene.Net.Search.TopDocs results = searcher.Search(query, null, 10);
foreach(Lucene.Net.Search.ScoreDoc test in results.ScoreDocs)
{
Console.WriteLine(test.ToString());
Console.ReadLine();
}
}
}
}
When running the code I receive an error stating:
An unhandled exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
Additional information: read past EOF
I know I'm missing something obvious. Your help would be greatly appreciated.
Edit: I downloaded Luke.Net and received the same error.

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

XSockets - custom controller is not registering

I've been trying to evaluate XSockets but it appears I've hit my first stumbling block pretty early. I can connect to Generic controller just fine but custom controllers do not seem to work at all - I get a custom message: "The handler name was not found in loaded plugins". A Google search shows one other person having this problem in SE, but their solution did not work for me.
I've created a console project and installed the latest XSockets 3.03 from NuGet. My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSockets.Core.Common.Socket;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.Common.Socket.Event.Interface;
namespace XSockets2
{
class Program
{
static void Main(string[] args)
{
using (var server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
Console.WriteLine("running!");
server.StartServers();
Console.ReadLine();
server.StopServers();
}
}
}
public class TestCont: XSocketController
{
public override void OnMessage(ITextArgs textArgs)
{
this.SendToAll(textArgs);
}
}
}
And my Javascript
function connect2() {
var host = "ws://localhost:4502/testcont";
var conn;
conn = new XSockets.WebSocket(host);
conn.on(XSockets.Events.open, function (clientInfo) {
message(clientInfo.ClientGuid); //appends message to textarea
console.log('Open', clientInfo);
});
conn.on('OnMessage', function (d) {
message(d);
console.log('Message', d);
});
conn.on(XSockets.Events.onError, function (err) {
message(err.CustomMessage);
console.log('Error', err);
});
conn.on(XSockets.Events.close, function () {
message('Closed');
console.log('Closed');
});
First of all the latest version is 3.0.2 (not 3.0.3) but that is not important :)
There is a well known and documented bug in the plugin framework for the latest version. The bug only affect you if you run a console application (or any other *.exe) project since xsockets by default only looks in *.dll and not *.exe.
The issue and work around is described here
But your code will not work anyway since you have an error (from what I can see).
Your controller is named "TestCont" but you connect to "testcont". The connectionstring is case sensitive.
EDIT: I also think you are missunderstanding the method OnMessage since you have added a subscription to that exact name.

Categories

Resources