Cannot access Hubconnection() from vs 2010? - c#

I'm working on cross domain implementation of SignalR in asp .net web application using VS 2010 .
My problems it that I'am unable to access HubConnection() from my application . I have installed SignalR version 0.5.3 . I have searched for namespace of HubConnection() but couldn't find any. Can anyone tell me the namespace of HubConnection() or the reason why I'm not able to access.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SignalR;
namespace SignalRVersion5
{
public partial class TestServerEvent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var connection = new HubConnection("http://localhost:58416/");
var chat = connection.CreateProxy("chat");
chat.On<string>("addMessage", Console.WriteLine);
try
{
connection.Start().Wait();
string msg = null;
while ((msg = Console.ReadLine()) != null)
{
chat.Invoke("send", msg).Wait();
}
}
catch (Exception ex)
{
using (var error = ex.GetError()) // NEW ERROR HANDLING FEATURES
{
Console.WriteLine(error.StatusCode);
}
}
}
}
}

You need to use the SignalR Client package available on NuGet: http://nuget.org/packages/Microsoft.AspNet.SignalR.Client
You should be using the 1.0.0 RC2 version of SignalR. 0.5.3 is out of date.
Once you install the correct client package, you should us the Microsoft.AspNet.SignalR.Client.Hubs namespace.
The documentation at https://github.com/SignalR/SignalR/wiki is continuously kept up to date with the latest versions of SignalR. The following documentation pertains to using the .NET client library with hubs: https://github.com/SignalR/SignalR/wiki/SignalR-Client-Hubs

Here is an example, using SignalR.Client 0.5.1.1. If you are creating a new project I would definitely recommend having a look at SignalR 1.0 first.
using SignalR.Client.Hubs;
var hubConnection = new HubConnection(HUB_URL);
var hub = hubConnection.CreateProxy(HUB_NAME);
Console.WriteLine("Starting connection");
await hubConnection.Start();
Console.WriteLine("Connected");
var start = DateTime.Now;
var question = new Question
{
Text = "text message",
Time = start.ToString("d")
}
};
await hub.Invoke("Ask", question);
hubConnection.Stop();

Related

MAUI Blazor App Microsoft.CognitiveServices.Speech keyword recognition opening custom table error

I was trying to create simple service that listens for keyword from speech. I was using Microsoft.CognitiveServices.Speech ver 1.24.1 and proceeding with official documentation but got error while trying to read KeywordRecognitionodel from file, file is accessible from that path. Also tried relative and absolute path.
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace HandyCook.Services
{
internal class KeyWordRecognizerService
{
public KeyWordRecognizerService()
{
StartRecognizing();
}
private async void StartRecognizing()
{
var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
var recognizer = new KeywordRecognizer(audioConfig);
recognizer.Recognized += (s, e) =>
{
Console.WriteLine($"{e.Result.Text} DETECTED");
};
var stream = await FileSystem.Current.OpenAppPackageFileAsync("XXX.table"); //accessible
//Exception with an error code: 0x8 (SPXERR_FILE_OPEN_FAILED)
var keywordModel = KeywordRecognitionModel.FromFile(Path.Combine(FileSystem.Current.AppDataDirectory, "XXX.table"));
var result = recognizer.RecognizeOnceAsync(keywordModel);
result.Wait();
}
}
}
To reproduce the error just simply create new MAUI Blazor App, add nuget package 'Microsoft.CognitiveServices.Speech 1.24.1', add service as singleton in MauiProgram then inject in Index.razor. I'm pasting also table file and solution explorer view.
table file: https://sendanywhe.re/18U3PXF8

Title: Problem connecting to LDAP server with Xamarin.Forms project c#

I have a problem with connecting to our LDAP server, using the NuGet package “Novell.Directory.Ldap.NETStandard2_0”.
My application is a Xamarin.Forms, with the Andoid & UWP part, based on NetStandard 2.0, using Visual Studio 2019, updated.
I could not find any built-in functionality in Netcore2.0 for using LDAP,
That is why I used the Nuget Package (Novell.Directory.Ldap.NETStandard2_0 by Novell, dsbenghe, mkostreba).
I have also used an LDAP query tool for Windows to test the connection, and that works.
But when I try to establish a connection in my app, I get an error with error code 91.
I have tried it with the full hostname, and with the direct ip address of the domain server, but I get the same error result. I have tried this with debugging UWP, not android.
I haven't started on making a correct credentials query yet, because the connection itself should first be ok.
This is my code: (under a simple button clicked)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Novell.Directory.Ldap;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;
namespace App1.view
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
}
private void button2_Clicked(object sender, EventArgs e)
{
try
{
LdapConnection conn = new LdapConnection();
conn.Connect("ldapserverhostname", 389);
conn.Bind("username query", "some password");
DisplayAlert("Error", "succesvol", "ok");
conn.Disconnect();
}
catch (LdapException f)
{
DisplayAlert("Error", f.ResultCode.ToString(), "ok");
return;
}
catch (Exception f)
{
DisplayAlert("Error", f.Message, "ok");
return;
}
}
}
}
Who could help me with this?
update 16 apr 2020:
I have established a connection + successful bind with our LDAP server using WPF NetCore console application, and also with a WPF NetCore desktop application, using the same serverinfo and user query info.
But I cannot get this working under Xamarin.Forms UWP or with a dedicated UWP app. Firewall of the computer is out of the question (I believe), because I am able to communicate with the LDAP server in multiple ways.
I have tried it with sideloading my Xamarin.Forms UWP app, but no result. >> Jumps to the first catch, every time.
Besides using the Novell Ldap Nuget, I have also tried the Windows Compatibility Pack for NetCore app in my UWP and Xamarin.Forms UWP app, but that will result in an "not supported platform" error.
here is my working code from the WPF NetCore desktop app:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Novell.Directory.Ldap;
using Novell.Directory;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string ldapHost = "fullyhostname.com";
String loginDN = "CN=MyUserName,OU=HK,something=Users,DC=ourdomainname,DC=com";
String password = "mypassword";
LdapConnection conn = new LdapConnection();
try
{
conn.Connect(ldapHost, 389);
if (conn.Connected)
{
MessageBoxResult r = MessageBox.Show("connection succeeded");
}
conn.Bind(loginDN, password);
MessageBoxResult t = MessageBox.Show("bind succeeded");
}
catch (LdapException f)
{
Console.WriteLine("Error1:" + "code= " + f.ResultCode.ToString());
Console.WriteLine("Error1:" + "code= " + f.LdapErrorMessage);
return;
}
catch (Exception f)
{
Console.WriteLine("Error:" + f.Message);
return;
}
conn.Disconnect();
}
}
}

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

Running Python Script/application in Windows Phone 8

I want to run the Skeinforge slicer program written in Python inside my Windows Phone 8 C# application. I have determined that I should probably use IronPython to do this, I have already determined that I can run Skeinforge inside the ipy.exe terminal I got when I installed IronPython. My problem though is that I am struggling to figure out how to host and run a Python script with IronPython inside Windows Phone 8. I have also already managed to get a simple hello world script running inside a Desktop Windows Forms application that transfers the applications console output to the Debug console with the following code:
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 System.Diagnostics;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DebugWriter debugW = new DebugWriter();
Console.SetOut(debugW);
}
private void button1_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("Test.py");
tw.Write(scriptBox.Text);
tw.Close();
try
{
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("Test.py");
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
}
}
}
And this is the DebugWriter:
class DebugWriter : TextWriter
{
private StringBuilder content = new StringBuilder();
public DebugWriter()
{
Debug.WriteLine("Writing console to debug");
}
public override void Write(char value)
{
base.Write(value);
if (value == '\n')
{
Debug.WriteLine(content.ToString());
content = new StringBuilder();
}
else
{
content.Append(value);
}
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
I have no idea how to even add the IronPython libraries to my Windows Phone 8 application though as the standard libraries won't import. I have though tried compiling the apparently now defunct Windows Phone 7 libraries with the master source code and I can import these libraries, but I get absolutely no response on the debug terminal when I try to run my hello world script.
Do any of you have any idea how to get this woring in Windows Phone 8, if you know how to do this in Windows 8/Metro/RT then that would also probably work for WP8.
UPDATE:
I have looked at the debug output again and I seem to get this error when trying to use the WP7 libraries to run a hello world script:
A first chance exception of type 'System.NotImplementedException' occurred in Microsoft.Scripting.DLL
Error: The method or operation is not implemented.
I managed to get Skeinforge running on a modified version of IPY. You can get the source for my application here: http://skeinforgewp8.codeplex.com/

Getting location in Windows 8 desktop apps

I am a total beginner at C#, but I have used Java a lot. I am trying to use the following code in my app to get location data. I am making a Windows 8 desktop app to use the GPS sensor in my device:
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 Windows.Devices.Sensors;
using Windows.Devices.Geolocation;
using Windows.Devices.Geolocation.Geoposition;
using Windows.Foundation;
namespace Hello_Location
{
public partial class Form1 :
{
public Form1()
{
InitializeComponent();
}
async private void Form1_Load(object sender, EventArgs e)
{
Geolocator loc = new Geolocator();
try
{
loc.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await loc.GetGeopositionAsync();
var lat = pos.Coordinate.Latitude;
var lang = pos.Coordinate.Longitude;
Console.WriteLine(lat+ " " +lang);
}
catch (System.UnauthorizedAccessException)
{
// handle error
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
I get this error:
'await' requires that the type
'Windows.Foundation.IAsyncOperation'
have a suitable GetAwaiter method. Are you missing a using directive
for 'System'? C:\Users\clidy\documents\visual studio
2012\Projects\Hello-Location\Hello-Location\Form1.cs
How can I fix this?
Also it will be very useful if you can point me to some resources for C# location and the sensor API for windows desktop apps. Upon googling, I am only getting Windows RT APIs.
To fix your error you have to reference to the link that Bart gave in one of the question's comments.
You might need to add a reference to System.Runtime.WindowsRuntime.dll
as well if you are using mapped types like Windows Runtime event
handlers:
...
That assembly resides in C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework.NETCore\v4.5
I recently found a "solution" for a similar question: C# desktop application doesn't share my physical location. Maybe you might be interested by my approach: https://stackoverflow.com/a/14645837/674700.
It's more like a workaround and it's not targeting Windows 8, but it works in the end.
alex's solution works!
add that reference and geolocation api starts working like a charm! so do async methods for other sensors!
here is a function i just got working using it.
async public void UseGeoLocation()
{
Geolocator _GeoLocator = new Geolocator();
Geoposition _GeoPosition =
await _GeoLocator.GetGeopositionAsync();
Clipboard.Clear();
Clipboard.SetText("latitude," +
_GeoPosition.Coordinate.Latitude.ToString() +
"," + "longitude," + _GeoPosition.Coordinate.Longitude.ToString() +
"," + "heading," + _GeoPosition.Coordinate.Heading.ToString() +
"," + "speed," + _GeoPosition.Coordinate.Speed.ToString());
Application.Exit();
}

Categories

Resources