how to integrate signalr in typescript project? - asp.net-mvc

I am using asp.net mvc 4.5 project with typescript in client side. I have installed and configured signalR in the server side. In the client side i have installed signalr.TypeScript.DefinitelyTyped with jquery,
i have referred signalr by below in my typescript file on the top,
///
and i have created interface file for my hub,
interface SignalR {
ForecastHub: {
client: {
DeleteProject(projectId: number)
};
server: {
send(name: string, message: string)
};
};
}
and my main code in ts is below,
var client = $.connection.ForecastHub;
client.client.DeleteProject = function (projectId) {
alert(projectId);
};
$.connection.hub.start().done(function () {
});
in the runtime i am getting an error 'Cannot read property 'ForecastHub' of undefined'
so how to import signalr in the typescript ts. please provide solution to integrate signalR in typescript project.

The below solution solves my problem,
How to load signalr.js in webpack inside Angular 2
Regards,
Venu Perumal

Related

How do i solve '"Reference to type 'BaseControlContext" claim.....' for AspNet.Security.OpenIdConnect.Server

I am facing weird issue.
I am reading and creating OpenID Connect server with ASOS this article ASOS - AspNet.Security.OpenIdConnect.Server.
I simply created new sample solution and added new subclass AuthorizationProvider class of OpenIdConnectServerProvider and override the virtual method i.e. ExtractAuthorizationRequest
AuthorizationProvider.cs
public class AuthorizationProvider : OpenIdConnectServerProvider
{
public override Task ExtractAuthorizationRequest(ExtractAuthorizationRequestContext context)
{
// If a request_id parameter can be found in the authorization request,
// restore the complete authorization request stored in the user session.
if (!string.IsNullOrEmpty(context.Request.RequestId))
{
var payload = context.HttpContext.Session.Get(context.Request.RequestId);
if (payload == null)
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidRequest,
description: "Invalid request: timeout expired.");
return Task.FromResult(0);
}
// Restore the authorization request parameters from the serialized payload.
using (var reader = new BsonReader(new MemoryStream(payload)))
{
foreach (var parameter in JObject.Load(reader))
{
// Avoid overriding the current request parameters.
if (context.Request.HasParameter(parameter.Key))
{
continue;
}
context.Request.SetParameter(parameter.Key, parameter.Value);
}
}
}
return Task.FromResult(0);
}
}
Issue:
As soon as i add Microsoft.AspNetCore.Identity (2.0.0) NuGet package to my project, context.Reject start giving the following error
"Reference to type 'BaseControlContext" claim it is defined in
Microsoft.AspNetCore.Authentication, but it could not be found.
But as soon as I remove Microsoft.AspNetCore.Identity NuGet dependency, the error goes away and all looks fine.
Note:
I am using VS 2017.
I am using dotnetcore 2.0 SDK.
I created solution using .Net Core 2.0.
Massive changes have been introduced in ASP.NET Core 2.0's authentication stack. The changes are so important that all the authentication middleware written for ASP.NET Core 1.x are not compatible (which includes all the aspnet-contrib projects).
You can read https://github.com/aspnet/Announcements/issues/262 for more information.
The good news is that we have an ASP.NET Core 2.0 RTM-compatible version of ASOS. You can find the 2.0.0-preview1-* bits on the aspnet-contrib MyGet feed (https://www.myget.org/F/aspnet-contrib/api/v3/index.json).

How to perform a request to a REST API in ASP.net 5.0 (MVC6)

I am writing an ASP.Net 5, MVC 6 application (also referred to as 'ASP.net vNext') with Visual Studio 2015 RC.
How do I perform a simple GET request to a REST API? In .net 4.5 I would have used HttpClient but that no longer seems to be available.
I have tried adding both the 'System.Net.Http' and 'Microsoft.Net.Http' packages as advised by Visual Studio, however I still get "The type or namespace name 'HttpClient' could not be found" which leads me to believe that HttpClient is not the right way to do this in ASP.net 5?
Can anyone advise on the correct way to make HTTP GET requests in ASP.net 5?
Update: My question is not a duplicate of 'HttpClient in ASP.NET 5.0 not found?' bercause the answer given is out of date and not applicable to the latest version of ASP.net 5.0
Here is a solution for you, I just tried it out on the ASP.Net 5 Web site project template. Add the following method to HomeController
static async Task<string> DownloadPageAsync()
{
string page = "http://en.wikipedia.org/";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result.Substring(0, 50);
}
}
Then in the HomeControllers Index method
string test = DownloadPageAsync().Result;
And in project.json I added the following reference at dependencies
"Microsoft.Net.Http": "2.2.22"
I found an answer which was in part from a post called '
HttpClient in ASP.NET 5.0 not found?', but there were some missing gaps because the technology has moved on a bit now. I have blogged the full solution here: http://blogs.msdn.com/b/martinkearn/archive/2015/06/17/using-httpclient-with-asp-net-5-0.aspx

Using Wcf Service in asp.net mvc 4

I have a wcfservice that is coded in vb.net. I want to use it in a c# mvc 4 client application. But when I added this service with right click on references and Add Service References, I can not use this. How can I do this?
Your service codes contain contracts and the implementation. However, The service code should be used in only the service, not in the client programs. You should generate proxy classes to be used by client programs like your Asp.NET applications.
There are 2 typical ways:
1. You run the service, then create a Service Reference to the service instance, so VS IDE will generate proxy classes under folder Service References.
2. Generate proxy classes using svcutil.exe against the service assembly that contain contracts, and build a client API assembly.
The 2nd is the most tidy and efficient way. Please check this article for more details at http://www.codeproject.com/Articles/627240/WCF-for-the-Real-World-Not-Hello-World
This is a pretty basic question but generally speaking you can add a web service reference and endpoint info in the main Web.Config file but I suspect you are having trouble with calling the WCF service URL, if so I posted an example of a generic class/wrapper for calling WCF web services in an MVC application.
Add the Web Reference to Visual Studio 2012 (or similar):
Right click the project in the Solution Explorer
Choose Add–> Service Reference –> Then click the Advanced Button... –>
Then click the "Add Web Reference…" button –> then type the address of your Web Service into the URL box. Then click the green arrow and Visual Studio will discover your Web Services and display them.
You may have known the above already and might just need a generic wrapper class which makes calling the WCF Web Service easy in MVC. I've found that using the generic class works well. I can't take credit for it; found it on the internet and there was no attribution. There is a complete example with downloadable source code at http://www.displacedguy.com/tech/powerbuilder-125-wcf-web-services-asp-net-p3 that calls a WCF Web service that was made using PowerBuilder 12.5.Net, but the process of calling the WCF Web service in MVC is the same no matter if it was created in Visual Studio or PowerBuilder.
Generic wrapper class for calling WCF Web Services in ASP.NET MVC
Of course don't model your error handling after my incomplete example...
using System;
using System.ServiceModel;
namespace LinkDBMvc.Controllers
{
public class WebService<T>
{
public static void Use(Action<T> action)
{
ChannelFactory<T> factory = new ChannelFactory<T>("*");
T client = factory.CreateChannel();
bool success = false;
try
{
action(client);
((IClientChannel)client).Close();
factory.Close();
success = true;
}
catch (EndpointNotFoundException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (CommunicationException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (TimeoutException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (Exception e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
finally
{
if (!success)
{
// abort the channel
((IClientChannel)client).Abort();
factory.Abort();
}
}
}
}
}

SignalR 2.0 - 404 in IIS Virtual Directory

I'm having an issue when deploying a very basic MVC5 app running SignalR 2.0.2. Everything works great in my local development environment when I'm running it with IIS Express. When I deploy to IIS, my js receives a 404 error attempting to connect to SignalR.
More specifically, I'm deploying to an application/virtual directory that is running under my Default Web Site. When I publish directly to Default Web Site, everything works successfully so IIS is not the issue.
GET http://myServer/signalr/negotiate?connectionData=%5B%5D&clientProtocol=1.3&_=1395517687175 404 (Not Found)
I'm assuming the 404 is caused by the missing application name. ie: myServer/MyApp/signalr/negotiate...
I've searched a number of posts and SignalR documentation with no luck regarding IIS and Applications/Virtual Directories and SignalR. Below is snippets of code in my app.
Thanks!
JS:
var connection = $.hubConnection();
var proxy = connection.createHubProxy('TestHub');
connection.start()
.done(function () {
console.log('Now connected, connection ID=' + connection.id + ' using transport=' + connection.transport.name);
})
.fail(function () { console.log('Could not connect'); });
Startup.cs:
app.MapSignalR();
Update
By changing the following JS code I was able to 'fix' the issue. The question is, how proper is this?
//var connection = $.hubConnection();
var connection = $.hubConnection("/MyApp/signalr", { useDefaultPath: false });
Your fix seems reasonable.
{ useDefaultPath: false } simply tells SignalR not to append "/signalr" to the url, so you could also create your connection object like this: var connection = $.hubConnection("/MyApp");
Alternatively, if you want to use JS hub proxies generated at /MyApp/signalr/hubs, you can could connect like this:
var proxy = $.connection.testHub;
// Make sure you always wire up client methods before calling start
proxy.client.myClientMethod = function () { /* ... */ };
$.connection.hub.start()
.done(function () { /* ... */ })
.fail(function () { /* ... */ });
http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#genproxy
A solution which will work in dev, and in IIS hosted as application, virtual directory or root is to configure the hub using the page url as its base. This will mean you won't need to hard code the value and negates configuration change for development and deployed scenarios.
var connection = $.hubConnection(document.location.origin + document.location.pathname);

running express.js app in Asp.net MVC

I would like to run node.js with asp.net mvc for performing socket.io operations.
i've successfully included the node.js in asp.net mvc as described in here
my problem is how to run express.js in asp.net mvc,
i've performed the url rewritting in Global.asax.cs file like
void Application_BeginRequest(object sender, EventArgs e)
{
// Get current path
string CurrentPath = Request.Path.ToLower();
if (CurrentPath.StartsWith("/node"))
{ HttpContext MyContext = HttpContext.Current;
MyContext.RewritePath("/Node/index.js/");
}
}
so in the url http:localhost:1234/node should redirect me to the index.js file in Node folder
it is all working well but,
when i start coading express.js server in index.js like
var express = require('express');
var app = express.createServer();
app.get('/node/', function (req, res) {
res.send(' welcome to express ');
});
app.listen(process.env.PORT);
I got error saying Cannot GET /Node/index.js/
where am i missing? please guide me how to write express.js coading in asp.net mvc
Iam running this application in windows 7 32 bit system with IIS 8.0 express , and installed node versions are
iisnode.js - iisnode-full-iis7-v0.2.3-x86
node.js - node-v0.8.19-x86
Thank you.
Do you have a web.config entry for iisnode handling index.js?
iisnode is not set up as a .js handler by default, since there is far more client-side javascript than server-side javascript, so you need to explicitly turn on iisnode as a handler for that file.

Resources