Can I send data to signalr clients as a Class? - c#

I've recently made this function in my hub:
public void createFileAndWrite(string path, string content)
{
Clients.Others.createFile(
new CreateFile
{
UserName = users[Context.ConnectionId],
Path = path,
Content = content
});
}
Seems OK, but when I built my project, my website couldn't connect to SignalR Hub. This error appeared in browser console:
SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'></script>.
So I deduced, that it's blame of my CreateFile class. And it was; after removing those lines, everything works perfectly. In every other function in Hub I used strings to pass information.
The interesting fact is: it didn't work on my website client (where I used javascript to connect with server) but everything seemed to work fine on c# client (windows application).
So, do I really can't use my own classes to organize data that I want to send? I can't find anything about that on asp.net site.

Related

DinkToPDF PDF generation only works once on Azure before giving 502 errors

I've written a PDF generation API that uses dinktopdf to convert some templated HTML to a byte array. This all works fine on my local machine but when I deploy to my azure web application the API only works once. When I try it a second time I get the following message and a 502 error:
The specified CGI application encountered an error and the server terminated the process.
Here's a stripped down version of my code that still presents the same error:
static IPdfConverter pdfConverter = new SynchronizedConverter(new PdfTools());
public static byte[] BuildPdf(string html)
{
return pdfConverter.Convert(new HtmlToPdfDocument()
{
Objects =
{
new ObjectSettings
{
HtmlContent = html
}
}
});
}
I've also tried using IronPDF to do the HTML to PDF conversion and gotten the same exact issue (works perfectly on local machine but only once on Azure deployment before giving consistent 502 errors).
If you initialize converter with var converter = new SynchronizedConverter(new PdfTools());´, remove it, and just injectIConverterin your service.
I tried and this approach is working, after all, we already register the converter, we don't need to create an instance using thenew` keyword. My app is not on Azure, but I have the same problem, the converter hangs after the first call, for that reason I decide to write down this comment.
Update: Problem was solved by changing the Azure App Service Plan to Basic rather than free (PDF generation requires at minimum the Basic plan apparently).

Need help related internal network communication using an asp.net mvc solution

In a new project as frontend developer the team I joined is using ASP.NET MVC for the backend. I am running a mac, so this means I can only compile the C# sources on Windows to run the application locally.
I have a Win10 setup inside a VM using virtual box. The sources are on the host and shared to the guest via a samba share (On Z:\ in the guest) and a host-only network adapter. Goal is to reach the app then from the host using the IP of the Guest, i.e. https://192.168.56.102:44301/ (it`s a single page application written in angular)
In the guest I compile from the command line using msbuild and then I start the REST API and the "Web App" using iisexpress.exe: (because visual studio is way to slow in the guest)
commands to build & start:
msbuild Z:\TheApp.sln
:: shell #1
iisexpress.exe" /config:Z:\.vs\config\applicationhost.config /site:"AppName.Api"
:: shell #2
iisexpress.exe" /config:Z:\.vs\config\applicationhost.config /site:"AppName.Web"
In Web.config of the Solution AppName.Web I have the following option:
<add key="ApiEndpointBase" value="https://192.168.56.102:44302/" />
The REST API is listening on port 44302, the "web app" on port 44301
So when I enter https://192.168.56.102:44301/ I get the app served.
The problem:
For each page reload the web app (HomeController.cs) does an http request against the API, so this means it is internally communicating to https://192.168.56.102:44302/
// HomeController.cs
// this fails with an exception like "An error occurred while processing your request.":
private readonly HttpClient client = new HttpClient();
...
/// <returns>The index view.</returns>
public async Task<ActionResult> Index() {
var response = await clientclient.GetAsync("api/foo?someId=" + someId);
client.BaseAddress is https://192.168.56.102:44302/
So there are two apps running in the guest using iisexpress, and one of them does an http request against the other using the Address https://192.168.56.102:44302/.... - and this request times out, or fails somehow and I don't get why.
It works if:
<add key="ApiEndpointBase" value="https://localhost:44302/" />
I visit https://localhost:44301/ in a browser inside the guest
But I want to access it from a browser on the host. Would really appreciate if some asp.net devs may help me here :)
EDIT:
External requests are already working. Else I would not get the app served on the host. I also registered the URLs using netsh and windows firewall is disabled on the guest. So I think this is not a duplicate of IIS Express enable external request

Possible bug (?) xsockets.net console server

I'm trying to start development on xsockets.net service.
My server doesn't want to recognize any of CustomController implementation for a Console Application (server). Everything works fine in Web project.
I've noticed that XSocketPlugins property contains a list of plugins. My plugin is not on a list for console App and is registered for Web.
The source code is simple like in ReadMe.txt
using (var container = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
container.StartServers();
container.OnServerClientConnection+=container_OnServerClientConnection
Console.ReadLine();<br/>
}
Defining new controller
public class CustomController1 : XSocketController
{
public void OnMessage(...)
{
//do stuff
}
}
I'm able to connect to Generic controller using C# client and JS client.
Any ideas?
Env: Windows7 64-bit, VS2012, .NET 4.0
Yes, the bug is described here: known-issues and the work around is also described.
Regarding the comment, please post the code you use to connect with the Client API and maybe I can see something in there. There should not be any problems connecting from the clients API.

How can I connect to a Server Side USB (HID) Device from within an ASP.NET Application?

I'm trying to write my own controller for a USB device instead of using the SDK that comes with the product (I feel the sdk is sub-par).
The USB Device is plugged into the SAME SERVER that this application is running on.
So I decided to head over to Nuget and grab the HidLibrary
PM> Install-Package hidlibrary
and I proceeded to follow the example found on GitHub.
First I went into my control panel to verify the VendorID and the ProductID
And I dropped it into my code.
Then I set a breakpoint on the line that grabs the device, but unfortunately it always comes back null.
using HidLibrary;
public class MyController : ApiController
{
private const int VendorId = 0x0BC7;
private const int ProductId = 0x0001;
private static HidDevice _device;
// POST api/<controller>
public string Post(CommandModel command)
{
_device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();
if (_device != null)
{
// getting here means the device exists
}
else
{
// ending up here means the device doesn't exist
throw new Exception("device not connected");
}
return null;
}
I'm hoping it's something silly, and not some deal-breaking permissions issue regarding connecting to a USB device directly from an IIS worker.
Despite your hopes to be something silly, it is not. You have some deal-breaking permission issues. If you will browse Mike O'Brien's code from GitHub of the Hid Library you will see that it calls Win32 API functions located in: kernel32.dll, setupapi.dll, user32.dll, hid.dll (Native.cs).
The enumeration itself it's done through setupapi.dll functions. It browse all the installed devices and filters what it's need it.
So... I think it's a security issue to execute kernel32.dll code directly from a web-app in IIS with anonymous authentication, don't you?
If you really need to communicate with that HID (who knows maybe it's a temperature sensor, or something else) I would do a separate Windows service and the IIS hosted web app would communication through WCF with this service. This service would like a proxy.
Put the same code in a console application and run it. That will help you verify if it's your code or environment.
If it's environment, try using Process Monitor to see if there are any hidden access errors. Also try enumerating all devices, not just looking for the one device you're after, just to see if you can do it in ASP.NET.
#Chase, unless this is an experiment - it is best not to attempt connecting to a device from IIS process. [It's a Pandora's box if you start down this path].
Best way to do this is to have another (WCF) service as proxy to the device and expose just what you need out of the service, hook it up with your app. Feel free to ask for an example if you think that would help.
I +1 #garzanti.

Get original url without non-standard port (C#)

First question!
Environment
MVC, C#, AppHarbor.
Problem
I am calling an openid provider, and generating an absolute callback url based on the domain.
On my local machine, this works fine if I hit http://localhost:12345/login
Request.Url; //gives me `http://localhost:12345/callback`
However, on AppHarbor where I'm deploying, because they are using non-standard ports, even if I'm hitting it at "http://sub.example.com/login"
Request.Url; //gives me http://sub.example.com:15232/callback
And this screws up my callback, because the port number wasn't in the original source url!
I've tried
Request.Url
Request.Url.OriginalString
Request.RawUrl
All gives me "http://sub.example.com:15232/callback".
Also to clear up that this isn't a Realm issue, the error message I am getting from DotNetOpenAuth is
'http://sub.example.com:14107/accounts/openidcallback' not under realm 'http://*.example.com/'.
I don't think I've stuffed that up?
Now, I'm about to consider some hacky stuff like
preprocessor commands (#IF DEBUG THEN PUT PORT)
string replace (Request.URL.Contains("localhost"))
All of these are not 100% solutions, but I'm sick of mulling over what could be a simple property that I am missing. I have also read this but that doesn't seem to have an accepted answer (and is more about the path rather than the authority). So I'm putting it towards you guys.
Summary
So if I had http://localhost:12345/login, I need to get http://localhost:12345/callback from the Request context.
And if I had "http://sub.example.com/login", I should get "http://sub.example.com/callback", regardless of what port it is on.
Thanks! (Sleep time, will answer any questions in the morning)
This is a common problem in load balanced setups like AppHarbor's - we've provided an example workaround.
Update: A more desirable solution for many ASP.NET applications may be to set the aspnet:UseHostHeaderForRequestUrl appSetting to true. We (AppHarbor) have seen several customers experience issues using it with their WCF apps, which is why we haven't enabled it by default and stil recommend the above solution for those situations. You can configure it using AppHarbor's "Configuration Variables" to inject the appsettings when deployed. More information can be found in this article.
I recently ran into an issue where I compared a URL to the current URL, and then highlighted navigation based on that. It worked locally, but not in production.
I had http://example.com/path/to/file.aspx as my file, but when viewing that file and running Request.Url.ToString() it produced https://example.com:81/path/to/file.aspx in a load balanced production environment.
Now I am using Request.Url.AbsolutePath to just give me /path/to/file.aspx, thus ignoring the schema, hostname, and port numbers.
When I need to compare it to the URL on each navigation item I used:
New Uri(theLink.Href).AbsolutePath
My initial thoughts are get the referrer variable and check if that includes a port, if so use it otherwise don't.
If that’s not an option because a proxy might remove the referrer header variable then you might need to use some client side script to get the location and pass it back to the server.
I'm guessing that AppHarbor use port forwarding to the IIS server so even though publicly the site is on port 80 IIS has it hosted on another port so it can't know what port the client connected on.
Something like
String port = Request.ServerVariables["SERVER_PORT"] == "80" ? "" : ":" + Request.ServerVariables["SERVER_PORT"];
String virtualRoot = Url.Content("~/");
destinationUrl = String.Format("http://{0}{1}{2}", Request.ServerVariables["SERVER_NAME"], port + virtualRoot, "/callback");
If you use the UrlBuilder class in the framework you can easly get around this. On the builder class if you set the port to -1 then the port number will be removed:
new UriBuilder("http://sub.example.com:15232/callback"){ Port = -1}
returns : http://sub.example.com/callback
To keep the port number on a local machine just check Request.IsLocal and don't apply -1 to the port.
I would wrap this into a extension method to keep it clean.
I see that this is an old thread. I had this issue running MVC5, on IIS 7.5, with an Apache proxy in front. Outside of the server, I would get "Empty Response", since the asp.net app gets the Url from apache with the custom port.
In order to have the app redirect to a subpath without including the "custom" port, forget the Response/Request objects, and use the Transfer method. For instance, if I want that users are automatically redirected to the login page in case they are not logged already:
if (!User.Identity.IsAuthenticated)
Server.TransferRequest("Account/Login");

Categories

Resources