cannot receive HTTP messages on HoloLens server - networking

i've been trying for days to implement a simple server on HoloLens to receive HTTP packets sent from a smart object on a local network.
My code so far is the following (i report only the part of the code that actually runs on HoloLens):`
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
using UnityEngine.UI;
#if !UNITY_EDITOR
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Networking.Connectivity;
#endif
public class DolphinManager : MonoBehaviour
{
private static string holoLensIpAddr = "192.168.0.147";
private static int holoLensPort = 12345;
#if UNITY_EDITOR
private HttpListener _listener;
#endif
#if !UNITY_EDITOR
private StreamReader reader;
private StreamSocketListener listener;
#endif
void Start()
{
#if UNITY_EDITOR
Invoke("InitializeUnityServer", 4f);
#else
Invoke("InitializeUWPServer", 4f);
#endif
}
#if !UNITY_EDITOR
private async void InitializeUWPServer()
{
try
{
listener = new StreamSocketListener();
serverHost = new Windows.Networking.HostName(anyIp);
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.Control.KeepAlive = false;
await listener.BindServiceNameAsync(holoLensPort.ToString());
} catch(Exception e) { Debug.Log(e.Message); }
}
#endif
#if !UNITY_EDITOR
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.log("message received!");
}
The server starts correctly, but when i try to send a packet from my smart object, Listener_ConnectionReceived() is not triggered.
I have already set the PrivateNetworkClientServer capability on the app manifest.
What could be wrong?
Thank you in advance!

Related

How to send message from Unity to SignalR Self Hosted server using asp.net signal R and not asp.netcore

I am trying to create a chat application in a Unity game. So basically in one instance of the game if someone sends a message , all the other open instances of the game should get the message.
I successfully created a self-hosted SignalR 2 server using this tutorial
The code for the console app is as follows:
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
namespace SignalRSelfHost
{
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";//a web application of type Startup is started at the specified URL (http://localhost:8080).
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{// the class containing the configuration for the SignalR server ,which creates routes for any Hub objects in the project.
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{//the SignalR Hub class that the application will provide to clients.
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);//clients will call to broadcast a message to all other connected clients.
}
}
}
I created a dummy Unity game as of now. There are the username input field and chat input field. Next to the chat input field there is a send button. So the person enters his/her name and enters something into the chat and all running instances of the game should receive the message , but I am not able to achieve that thing
The script for this is attached to a empty GameObject SignalRManager. The code is as follows:
using System.Collections.Generic;
using UnityEngine;
using Microsoft.AspNet.SignalR.Client;
using UnityEngine.UI;
using System;
using TMPro;
public class SignalRManager : MonoBehaviour
{
string url = "http://localhost:8080";
HubConnection connection;
[SerializeField] private GameObject ChatMessage;
[SerializeField] private GameObject UserName;
// Start is called before the first frame update
void Start()
{
connection = new HubConnection(url);
connection.Start();
connection.StateChanged += connection_StateChanged;
}
private void connection_StateChanged(StateChange state)
{
if(state.NewState== ConnectionState.Connected)
{
Debug.Log("Connected to Server");
}
if(state.NewState == ConnectionState.Disconnected)
{
Debug.Log("Disconnected from Server");
}
}
public void OnClickSendChatButton()
{
string message= ChatMessage.GetComponent<TMP_InputField>().text;
string userName= UserName.GetComponent<TMP_InputField>().text;
}
private void OnDisable()
{
connection.StateChanged -= connection_StateChanged;
}
}
I am able to connect to the server as the log message appears , but dont know what to write to send message to the server. Also how do I receive the message from the server as well
I tried to use a function called connection.Send(), but it is not accepting two arguments. I tried to look into many tutorials ,but many are for asp.netcore Signal r , but I need it for asp.net signalR because thats my requirement.
<<<<--------edit------>>>
I was able to send data to the server but I am not able to receive data from the server on my Unity game. The updated code is as follows:
using System.Collections.Generic;
using UnityEngine;
using Microsoft.AspNet.SignalR.Client;
using UnityEngine.UI;
using System;
using TMPro;
public class SignalRManager : MonoBehaviour
{
string url = "http://localhost:8080";
HubConnection connection;
IHubProxy hubProxy;
[SerializeField] private GameObject ChatMessage;
[SerializeField] private GameObject UserName;
[SerializeField] private TextMeshProUGUI OutputText;
// Start is called before the first frame update
void Start()
{
connection = new HubConnection(url);//Create a connection for the SignalR server
hubProxy = connection.CreateHubProxy("MyHub");//Get a proxy object that will be used to interact with the specific hub on the server.There may be many hubs hosted on the server, so provide the type name for the hub
connection.Start();
connection.StateChanged += connection_StateChanged;
OutputText.text = "";
}
private void OnReceivedMessageFromServer(string name, string message)
{
OutputText.text = OutputText.text+name + ":" + message + "\n";
Debug.Log(OutputText.text + name + ":" + message + "\n");
}
private void connection_StateChanged(StateChange state)
{
if(state.NewState== ConnectionState.Connected)
{
Debug.Log("Connected to Server");
}
if(state.NewState == ConnectionState.Disconnected)
{
Debug.Log("Disconnected from Server");
}
}
public void OnClickSendChatButton()
{
string message= ChatMessage.GetComponent<TMP_InputField>().text;
string userName= UserName.GetComponent<TMP_InputField>().text;
hubProxy.On<string, string>("addMessage", OnReceivedMessageFromServer);//register hub events (methods invoked by the hub). The following code registers a handler method for ChatMessage event.
hubProxy.Invoke("Send", userName, message);
}
private void OnDisable()
{
connection.StateChanged -= connection_StateChanged;
}
}
The callBack OnReceivedMessageFromServer is not invoked. Can anyone help me here?

NServicebus not unable to resolve service for interface in handler

I'm trying to build my first NserviceBus application, but I cannot get it to work. The message arrives on the "backend" but the handler uses DI and NServicebus claims it cannot find the service for the interface. But the code was lifted directly from the examples. I'm missing something and I cannot figure it out.
The Error:
dbug: NServiceBus.LoadHandlersConnector[0]
Processing message type: Messages.JobStartCommand
Message headers:
NServiceBus.MessageId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.MessageIntent : Send
NServiceBus.ConversationId : bb4f276f-63fe-450b-b234-ad7400ef43cd
NServiceBus.CorrelationId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.ReplyToAddress : ClientUI
NServiceBus.OriginatingMachine : L19002992
NServiceBus.OriginatingEndpoint : ClientUI
$.diagnostics.originating.hostid : e1fecb2b72b8185e47341bb4dfb37dd7
NServiceBus.ContentType : text/xml
NServiceBus.EnclosedMessageTypes : Messages.JobStartCommand, Messages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
NServiceBus.Version : 7.5.0
NServiceBus.TimeSent : 2021-07-29 14:31:08:228497 Z
NServiceBus.Retries : 3
NServiceBus.Retries.Timestamp : 2021-07-29 14:31:40:397277 Z
Handlers to invoke:
Extractor.JobStartHandler
Extractor.JobStartHandler
info: NServiceBus.RecoverabilityExecutor[0]
Immediate Retry is going to retry message '0044f261-e3b3-4287-b6f0-ad7400ef43cb' because of an exception:
System.InvalidOperationException: Unable to resolve service for type 'IExtract' while attempting to activate 'Extractor.JobStartHandler'.
at Microsoft.Extensi
My backend program.cs
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NServiceBus;
using System.Threading.Tasks;
using Messages;
using Extractor;
namespace ExtractorOsiris
{
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var builder = Host.CreateDefaultBuilder(args);
builder.UseWindowsService();
//builder.UseMicrosoftLogFactoryLogging();
builder.ConfigureLogging((ctx, logging) =>
{
logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
//logging.AddEventLog();
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
});
#region back-end-use-nservicebus
builder.UseNServiceBus(ctx =>
{
var endpointConfiguration = new EndpointConfiguration("Sample.Extractor");
endpointConfiguration.UseTransport<LearningTransport>();
var transport = endpointConfiguration.UseTransport<LearningTransport>();
transport.Routing().RouteToEndpoint(typeof(ProcessObjectCommand), "Sample.Processor");
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
return endpointConfiguration;
});
#endregion
#region back-end-register-service
builder.ConfigureServices(services =>
{
services.AddSingleton<IExtract, ExtractOsiris>();
});
#endregion
return builder;
}
private static Task OnCriticalError(ICriticalErrorContext arg)
{
throw new NotImplementedException();
}
}
}
The Interface
using Newtonsoft.Json.Linq;
using NServiceBus;
using System;
using System.Threading.Tasks;
namespace Extractor
{
public interface IExtract
{
Task<JArray> Extract(string #object, DateTime deltaTime);
}
}
The handler
using System.Threading.Tasks;
using Messages;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace Extractor
{
#region back-end-handler
public class JobStartHandler : IHandleMessages<JobStartCommand>
{
private readonly IExtract extractor;
public JobStartHandler(IExtract extractor)
{
this.extractor = extractor;
}
public async Task Handle(JobStartCommand message, IMessageHandlerContext context)
{
Task<JArray> result = extractor.Extract("Medewerkers", message.DeltaTime);
await result;
JArray test = result.Result;
foreach (JObject x in test)
{
// send the object to be processed.
//await context.Send(new ProcessObjectCommand(x.ToString()));
}
}
}
#endregion
}
The implementation of the interface
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Extractor;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace ExtractorOsiris
{
public class ExtractOsiris : IExtract
{
private readonly ILogger logger;
public ExtractOsiris(ILogger<ExtractOsiris> logger)
{
this.logger = logger;
}
public Task<JArray> Extract(string #object, DateTime deltaTime)
{
logger.LogInformation($"getting {#object} for delta time {deltaTime}");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://xx.yy");
WebResponse response = request.GetResponse();
JObject temp = JObject.Load(new JsonTextReader(new StreamReader(response.GetResponseStream())));
return Task<JArray>.FromResult(temp["items"] as JArray);
}
}
}
I know the code ain't pretty, but it's pure quick and dirty testing code.
I cleaned out the offending interface from the code and still got the error on an interface that was not even there anymore. I removed the bin folder and build everything back up step by step. Stupid thing is, source control says I am back where I started, without changes. And it just works....
So must have bin something stupid with VS2019. Sorry to anyone who's time I wasted

Retry for three times If the File Exists in c#

My Requirement is i want to retry if the specific file exists,suppose like currently i'm doing svn installation / uninstallation so if the svn is installed then it will create RevisionNumber.txt and if the svn is uninstalled then ReveisionNumber.txt is deleted
So My Requirement is if RevisionNumber.txt exists / Svn exists i want to retry the process of svn uninstallation for 3 times.
can anyone please sort me out ? below is my code :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SVNUNINSTALL
{
class Program
{
public void Process()
{
System.Diagnostics.Process.Start("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\SvnUninstallation.exe");
bool exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");
Console.WriteLine(exists);
Console.ReadLine();
}
static void main(String[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
}
}
}
public void Process()
{
bool exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");
for(int i = 0; i < 3 && exists; i++)
{
System.Diagnostics.Process.Start("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\SvnUninstallation.exe");
Sleep(2000); // or long enough to ensure the uninstall process finishes executing
exists = File.Exists("C:\\Users\\sk185462\\Desktop\\SVNUPDATED\\RevisionNumber.txt");
}
Console.WriteLine(exists);
Console.ReadLine();
}

Consuming a live REST services in ASP.NET

Can you point me to a good and working examples of how to Consume Restful services in web ASP.net. Tutorials, walk-through or any useful material. I just join a company that require me to do that and I am new to ASP.net especially the rest service. I have used many materials and yet not clear.
Help me with the A B C of Rest usage in ASP.net pls
Here is a code that works with my Rest Servive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.IO;
using System.Runtime.Serialization.Formatters;
using System.Net;
namespace WebTestRestfullService
{
public partial class _Default : Page
{
public string JS;
public string resp;
protected void Page_Load(object sender, EventArgs e)
{
}
public void Page_Init(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
//client.BaseAddress = new Uri("http://88.208.232.99:0000");//Dont use this.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json"));
//This is wrong too
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Correct/api/"));
string query = "Correct/api/";//You must get the api refernce correct.
// HTTP GET
//HttpResponseMessage response = await client.GetAsync(". ");
string resp = "";
var task = client.GetAsync(query).ContinueWith
((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonstr = response.Content.ReadAsStringAsync();
jsonstr.Wait();
resp = jsonstr.Result;
});
task.Wait();
Response.Write(resp);
// string data = $.parseJSON(lbltest.Text);
// Session["resp"] = resp;
// new code
}
}
}
}
I have been working on a REST client library that works on all .NET based platforms.
https://bitbucket.org/MelbourneDeveloper/restclient-.net
There is a sample REST service there that calls another REST service. The service is written for ASP.NET Core so it should help you.

Utilizing a WCF channel from an IIS ASP.net IHttpModule

I have an ASP.net project which involves using a custom IHttpModule. This module will sit in the pipeline and when certain criteria match up, it should invoke a method on a WCF service hosted in a simple C# console application on the same machine.
The code for the module is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.SessionState;
using System.Web;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
using System.ServiceModel;
using SimpleFarmStateServer;
namespace SimpleFarm
{
public class SimpleFarmModuleSS : IHttpModule, IRequiresSessionState
{
protected string cache_directory = "";
// WCF
ChannelFactory<IStateServer> factory;
IStateServer channel;
public void Dispose() { }
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
setupFactory();
}
void setupFactory()
{
factory = new ChannelFactory<IStateServer>(
new NetNamedPipeBinding(),
"net.pipe://localhost/StateServer");
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
try
{
if (factory.State != CommunicationState.Opened)
setupFactory();
channel = factory.CreateChannel();
channel.LogAccess("Hello World!");
}
catch (Exception ex)
{
}
finally
{
factory.Close();
}
}
}
}
My problem is that this runs the first time, but then subsequent attempts cause this error message
The communication object,
System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication
because it is in the Faulted state.
It seems as if I am doing something wrong, and I am new to WCF in general so this is very likely.
I think the issue is surrounding the ChannelFactory being recreated, and this causes the faulted state.
The specific error probably means the factory faulted, threw an exception (which you're swallowing) and then when the finally block executes, the factory.Close() call fails because the factory is faulted (if a WCF object is faulted, you need to call Abort() on it, not Close()).

Resources