How can I use signalR with unity for client server communication - unity3d

Can Any one tell me How can we use signalR with Unity For Client server communication.
Im getting error in my code.
The code is as below:
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using Microsoft.AspNet.SignalR.Client;
public class SignalR : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
public class Client
{
private readonly string _platform;
private readonly HubConnection _connection;
private readonly IHubProxy _proxy;
public event EventHandler<EventArgs> OnMessageReceived;
public Client(string platform)
{
_platform = platform;
_connection = new HubConnection("http://192.168.1.103");
_proxy = _connection.CreateHubProxy("Chat");
}
public void Connect()
{
_connection.Start();
_proxy.On("messageReceived", (string platform, string message) =>
{
if (OnMessageReceived != null)
OnMessageReceived(this, string.Format("{0}: {1}", platform, message));
});
Send("Connected");
}
public void Send(string message)
{
return _proxy.Invoke("Send", _platform, message);
}
}
This is my client side code.I have added ell’s in my assets for signalR.
The error details are as below:
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: Mono.CSharp.InternalErrorException: Assets/SignalR.cs(30,24): Client.Client(string) ---> System.TypeLoadException: Could not load type 'Microsoft.AspNet.SignalR.Client.Connection' from assembly 'Microsoft.AspNet.SignalR.Client, Version=2.1.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
at (wrapper managed-to-native) System.MonoType:GetMethodsByName (string,System.Reflection.BindingFlags,bool,System.Type)
at System.MonoType.GetMethods (BindingFlags bindingAttr) [0x00000] in :0
Thanks In Advance!!

Related

Server Side Blazor + Kestrel + Windows Auth = Crash

I am trying to setup windows Auth using kesterel on blazor server side.I have the progam setup like this:
I am using version 0.6.0 of Blazor server side and latest release of VS 2017.
Using the out of the box blazor temnplate. You can see that I enabled "windows Auth" in BuildWebHost of 'Program.cs". If I comment out options.Authentication.AllowAnonymous line, everything works, of course.
Blazor.Web.server
Program.cs
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseHttpSys(
options =>
{
options.Authentication.Schemes =
AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
})
.UseConfiguration(new ConfigurationBuilder()
.AddCommandLine(args)
.Build())
.UseStartup<Startup>()
.Build();
}
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Since Blazor is running on the server, we can use an application
service
// to read the forecast data.
services.AddSingleton();
}
public void Configure(IBlazorApplicationBuilder app)
{
app.AddComponent("app");
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
BlazorWebAssemblyHost.CreateDefaultBuilder()
.UseBlazorStartup<Startup>();
}
public class HttpContextAccessor
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HttpContextAccessor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public HttpContext Context => _httpContextAccessor.HttpContext;
}
Auth.cshtml
using System.Net.Http
#Inject Blazor.Web.App.HttpContextAccessor HttpContext
#page "/two-way-data-binding"
Logged in User: #HttpContext.Context.User.Identity.Name
I get the following error when navigating to Auth.cshtml
System.ObjectDisposedException
HResult=0x80131622
Message=Safe handle has been closed
Source=System.Private.CoreLib
StackTrace:
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.Advapi32.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, Boolean nullOnInvalidParam)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.b__46_0()
at System.Security.Principal.WindowsIdentity.<>c__DisplayClass62_0.b__0(Object )
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Security.Principal.WindowsIdentity.RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
at System.Security.Principal.WindowsIdentity.RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
at System.Security.Principal.WindowsIdentity.GetName()
at System.Security.Principal.WindowsIdentity.get_Name()
at Cloud.WebUI.App.Pages.TwoWayDataBinding.BuildRenderTree(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Blazor.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.ProcessRenderQueue()
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.AddToRenderQueue(Int32 componentId, RenderFragment renderFragment)
This is also created as a "issue" # Blazor Issue # 1596
At first, there is no need for your custom class HttpContextAccessor as it does not add any value.
Be sure to add the following line to your ConfigureServices method of the server's Startup.cs
services.AddHttpContextAccessor();
Then you are fine and can use the HttpContextAccessor in your Blazor app the following way:
#inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
User: #HttpContextAccessor.HttpContext.User.Identity.Name
Set windows authentication to true in your server's project web server settings (the last area in debug settings).
I'm using Blazor 0.7.0

Clients.All, Clients.Caller and Clients.Others throwing TypeLoadException

I have a simple Typed Hub setup through an interface. I can successfully connect to the SignalR Hub.
namespace POC.WebSocket
{
public class ApiResultHub : Hub<IApiResultHubClient>
{
public async Task SendMessage(string user, string message)
{
await Clients.All.ReceiveMessage(user, message);
}
public override Task OnConnectedAsync()
{
Clients.Caller.ReceiveMessage("newUser", $"{Context.ConnectionId}");
return base.OnConnectedAsync();
}
}
}
However, when I try invoke a client side hub method it throws the following exception:
Here are my other class files:
Startup.cs
namespace POC.WebSocket
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("https://localhost:44324", "https://localhost:44326")
.AllowCredentials();
}));
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ApiResultHub>("/apiResult");
});
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
IApiResultHubClient`T.cs
namespace POC.Common
{
public interface IApiResultHubClient
{
Task ReceiveMessage(string user, string message);
Task SendApiResponse<T>(ApiResult<T> data);
}
}
Has anyone else seen this issue? I saw few similar issues with being able to connect to the hub itself. However, as mentioned I am able to successfully connect to the hub, just not able to resolve Clients.All, Clients.Caller or Clients.Others.
All libraries updated today:
.Net Core version 2.1.4
.Net SignalR Core version 1.0.3
Edits:
Found details of the exception:
Method 'SendApiResponse' in type
'Microsoft.AspNetCore.SignalR.TypedClientBuilder.IApiResultHubClientImpl'
from assembly 'Microsoft.AspNetCore.SignalR.TypedClientBuilder,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have
an implementation.

How to make EF Core migrations less verbose

I am using Entity Framework Core 1.1.0 with migrations. When I run them with
dotnet ef database update
in Package Manager Console the console is full of applied SQL. Instead of this, I would like to have printed only names of migrations that are currently being applied. How can I do this?
I assume its configuration of your project.
To disable sql print try this
var builder = new DbContextOptionsBuilder<NAMEContext>();
builder.UseMySql(connectionString);
builder.UseLoggerFactory(new MigrationLoggerFactory()); <--- this seems to be what you are looking for
return new MigrationDataContext(builder.Options);
MigrationLoggerFactory
public class MigrationLoggerFactory : ILoggerFactory
{
public void Dispose() { }
public ILogger CreateLogger(string categoryName)
{
if ("Microsoft.EntityFrameworkCore.Migrations".Equals(categoryName))
return new MigrationLogger();
return new NullLogger();
}
public void AddProvider(ILoggerProvider provider)
{
}
}
NullLogger
public class NullLogger : ILogger
{
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
throw new NotImplementedException();
}
public bool IsEnabled(LogLevel logLevel)
{
return false;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
}
Here is an article which could also be helpful

scriptcs Mixed mode assembly error

I have added an application in scriptcs and added some references to assemblies which have the version v2.0.50727. So while running the scriptcs file it returns as Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime.Setting attribute useLegacyV2RuntimeActivationPolicy="true" in app.config may resolve the issue in asp.net web application. but in scriptcs its not working. further searching reveals that above attribbute useLegacyV2RuntimeActivationPolicy="true" should be added as scriptcs.exe.config. I have an application file named FMUpgrade.csx and how can we reference this scriptcs.exe.config in the FMUpgrade.csx file.scriptcs docs doesn't say much about scriptcs.exe.config.Also added program.exe.config with app.config but still not success.
After much research I got a workaround solution to the above problem.
By make use of class ExeConfigurationFileMap we could able to get the key values from app.config, its not able to bypass the supported runtime error caused by mixed mode assembly error.
Server server = new Server(new ServerConnection(con)); server.ConnectionContext.ExecuteNonQuery(script);
The error is caused while executing the statement ExecuteNonQuery.
So before executing the statement
if( RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully )
server.ConnectionContext.ExecuteNonQuery(script);
Solution is below
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully
{ get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
} using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}

GWT Void remote services fail for seemingly no reason

I'm working on a GWT project and have several void remote services that seem to execute just fine, but on the client side, end up firing the onFailure() method. No exceptions are thrown anywhere, and the expected behavior is observed on the backend. I have no idea what could be going wrong. Here is the relevant code:
Interfaces and implementation...
#RemoteServiceRelativePath("DeleteSearchService")
public interface DeleteSearchService extends RemoteService {
/**
* Utility class for simplifying access to the instance of async service.
*/
public static class Util {
private static DeleteSearchServiceAsync instance;
public static DeleteSearchServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(DeleteSearchService.class);
}
return instance;
}
}
public void delete(SearchBean search);
}
public interface DeleteSearchServiceAsync {
public void delete(SearchBean bean, AsyncCallback<Void> callback);
}
public class DeleteSearchServiceImpl extends RemoteServiceServlet implements DeleteSearchService {
private static final long serialVersionUID = 1L;
#Override
public void delete(SearchBean search) {
try {
Connection conn = SQLAccess.getConnection();
String sql = "DELETE FROM `searches` WHERE `id`=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
sql = "DELETE FROM `searchsourcemap` WHERE `search-id` = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
return;
} catch (Exception e) {
// TODO Log error
e.printStackTrace();
}
}
}
Calling code...
private class DeleteListener implements ClickListener {
public void onClick(Widget sender) {
DeleteSearchServiceAsync dss = DeleteSearchService.Util.getInstance();
SearchBean bean = buildBeanFromGUI();
dss.delete(bean, new AsyncCallback<Void>(){
//#Override
public void onFailure(Throwable caught) {
// TODO log
SearchNotDeleted snd = new SearchNotDeleted();
snd.show();
}
//#Override
public void onSuccess(Void result) {
SearchDeleted sd = new SearchDeleted();
sd.show();
searchDef.getParent().removeFromParent();
}
});
}
}
I know I'm a jerk for posting like 500 lines of code but I've been staring at this since yesterday and can't figure out where I'm going wrong. Maybe a 2nd set of eyes would help...
Thanks,
brian
LGTM I'm afraid.
Are you using the hosted mode or a full-fledged browser? You can try switching and see if it helps.
Also, it might help listening to that //TODO and perform a GWT.log when onFailure is invoked.