How to connect the socket.io with backend - c#

I am trying to implement chat in my ionic project what i have tried so far is to connect the socket.io with my backend (c#) is below.
Here is my index.html
<script src="http://192.xxx.x.xxx:8888/socket.io/socket.io.js"></script>
and here i created socketservice.js file looks like
var example = angular.module('starter.socketService',[])
example.service('SocketService',function(socketFactory){
console.log("SocketService");
return socketFactory({
ioSocket: io.connect('http://192.xxx.x.xxx:8888')
});
console.log(socketFactory);
})
finaly i created a folder called server i have a chat-server.js file in there.
var io = require('socket.io')(8888);
console.log(io);
io.on('connection', function(socket){
console.log(socket);
socket.on('send:message', function(msg){
console.log(msg);
socket.emit('message', msg);
console.log("success");
});
});
ERROR:
GET http://192.xxx.x.xxx:8888/socket.io/socket.io.js net::ERR_CONNECTION_TIMED_OUT
What i have done worng is there anything i have to do to connect with server always i am getting this error
Can some one tell me step by step explaination in c# to develop for socket.io

Related

How to make a complex file download functionality with Blazor server?

I have a Blazor server application. I want to allow the user to download files but the content of the files needs to be built dynamically.
Basically the application shows reports to the user based on filters and etc. and I want the user to have the option to download whatever he is currently seeing.
I know I can make a "link button" that points to a Razor page that returns some sort of FileContentResult in its OnGet method but I have no idea how to pass any data to that so that the correct report file can be built.
I know there is an alternative that uses JavaScript but, as far as I know, it's more cumbersome and I'm not sure if it is any better.
I thought about doing a request to some sort of REST/WebAPI (which would allow me to pass arguments and stuff) but I cannot seem to get a WebAPI and Blazor Server projects run at the same time. The only partial success I've had is adding a WebAPI project to my Blazor Server solution and starting both. But then, while debugging, for some reason, both processes stop when I download the file.
Also the application must be hosted on Azure Web app and am not sure how feasible it would be to run both projects at the same time.
So, how can I make my Blazor Server allow the user to download a file but generate the file dynamically based on what the user is seeing on his browser?
The JavaScript alternative is very straightforward.
export function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
create a bytestream of whatever content you want to create and call this function through IJSInterop. I have used it in blazor server and it works well.
Please note : I found this piece of code online but I don't remember from where. I will be happy to give credit to the original author if someone knows the source.

Simple example SignalR -1.0.0-alpha2 in ASP.NET MVC 4 VS2012 not working [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
UPDATE4: (SOLVED)
made new project;
imported sources;
updated SignalR to latest version (through NuGet Package Manager Console);
made corresponding changes (according to official doc: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server).
In the end, everything worked like a charm. Thanks SignalR team!
good job with this SignalR, can't wait to try it!
I found this tutorial - SignalR - 5 Minute Demo (http://www.youtube.com/watch?v=tEBaDo_sFfA)
BUT, I have some problems:
- i installed VS2012Ultimate, after creating a sample ASP.NET MVC4 Internet App, right click on References -> Manage NuGet Packages, search SignalR.... doesn't appear like in the video, none of those: SignalR, SignalR.Js, SignalR.Server... :(
Does anyone knows why?
UPDATE1:
I installed SignalR (http://nuget.org/packages/microsoft.aspnet.signalr) and after that, i installed that asp.net fall update (http://www.microsoft.com/en-us/download/details.aspx?id=35493).
BUT i get the error from below regarding function "writeMessage" from ChatHub.cs.
"Error1'Microsoft.AspNet.SignalR.Hubs.HubConnectionContext' does not contain a definition for 'writeMessage'
and no extension method 'writeMessage' accepting a first argument of type
'Microsoft.AspNet.SignalR.Hubs.HubConnectionContext' could be found (are you missing a using directive or an
assembly reference? ..\MvcApplication1\Hubs\ChatHub.cs"
After "resolving" this error using Clients.All. or Clients.Others. and start hub just after chat initialization and using chat.writeMessage, i get two errors when loading in GoogleChrome Console:
in Index.cshtml:
"Uncaught TypeError: Cannot set property 'writeMessage' of undefined"
in localhost:3420/signalr/hubs:
"Uncaught TypeError: Object #<Object> has no method 'createProxy'"
on this line:
// Create and store the hub proxy
hub._.proxy = hubConnection.createProxy(hub._.hubName);
After "resolving" this error using Clients.All. or Clients.Others. and start hub just at the end, and using chat.client.writeMessage (i installed Microsoft.AspNet.SignalR.Client), i get two errors when loading in GoogleChrome Console:
in Index.cshtml:
"Uncaught TypeError: Cannot read property 'client' of undefined"
Can anyone help me, please?! :(
Thanks in advance!!
File ChatHub.cs:
namespace MvcApplication1.Hubs
{
//[Microsoft.AspNet.SignalR.Hubs.HubName("chathub")]
[Microsoft.AspNet.SignalR.Hubs.HubName("chatHub")]
public class ChatHub : Microsoft.AspNet.SignalR.Hubs.Hub
{
public void BroadcastMessage(string message)
{
//rebroadcast the message to all the connected clients
Clients.writeMessage(message);//ERROR on compile
//I tried both of the followings, give no error, BUT when i press Submit doesn't appear messages anywhere
//Clients.All.writeMessage(message);
//Clients.Others.writeMessage(message);
}
}
}
File Index.cshtml:
#section scripts
{
<script type="text/javascript" src="~/Scripts/jquery.signalR-1.0.0-alpha2.js"></script>
#*not working, GET localhost:3420/SignalR 500 (Internal Server Error)*#
#*<script type="text/javascript" src="SignalR"></script>*#
#* with any of these declarations i don't get 500 error any more, but still not working *#
<script type="text/javascript" src="~/signalr/hubs"></script>
#*<script type="text/javascript" src="../signalr/hubs"></script>*#
<script type="text/javascript">
$(document).ready(function()
{
//i tried these, but in vain..
//var connection = new Microsoft.AspNet.SignalR.Connection("localhost:3420/");
//$.connection.hub.url = 'localhost:3420/signalr/';
var chat = $.connection.chatHub;
$.connection.hub.start();
//Uncaught TypeError: Cannot set property 'writeMessage' of undefined
//chat.writeMessage = function (msg)
//Uncaught TypeError: Cannot read property 'client' of undefined
chat.client.writeMessage = function (msg) {
{
$("#messages").append("<li>" + msg + "</li>");
}
$("#buttonSubmit").click(function ()
{
//chat.broadcastMessage($("#txtInput").val());
chat.server.broadcastMessage($("#txtInput").val());
});
$.connection.hub.start();//just one error at client
});
</script>
}
<h5>Chat with SignalR</h5>
<fieldset>
<legend>SignalR Demo</legend>
<label for="txtInput">Chat Message</label>
<input id="txtInput" type="text" />
<button id="buttonSubmit">Submit</button>
<fieldset>
<legend>Messages</legend>
<ul id="messages"></ul>
</fieldset>
</fieldset>
UPDATE2:
After Tim B James'advices, I:
created new ASP.NET MVC 4 project;
installed SignalR via NuGet with suggested commands;
tried the source code example with Hubs from https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs but NOT working!
Mentions:
- put the code from function Main, into my HomeController.cs -> function: public ActionResult Index();
- changed this line:
var hubConnection = new HubConnection("localhost/mysite");
with this one:
var hubConnection = new HubConnection("localhost:14079");
BUT, my page doesn't load ("Waiting for localhost...")
- if i don't put the code from Main into controller's function,
i get this error:
"Uncaught TypeError: Cannot read property 'chat' of undefined "
on this line:
var chat = $.connection.chat;
UPDATE3:
UPDATE2 with strikethrough lines
UPDATE4: (SOLVED)
Indications at the beginning.
There are some undocumented nuances with the latest version, in fact I was working through them today.
First off you will not need the Code from Main, in the link you referenced. That is for using Signalr inside of a WPF app or Windows 8 app.
The first issue that may or may not be an issue, is the use of HubNameAttribute, it may or may not be needed.
Without HubName the name of your hub should resolve to $.connection.chatHub
The next part that you have already handled is the new namespaces on each hub.
chatHub.client - These are client defined methods, that the server may invoke.
chatHub.server - These are server defined methods, that the client may invoke.
chatHub.state - This is the state that gets sent to and from the server.
Now the uncaught error is something in the JavaScript not getting output correctly, most likely the hubs definition, as the hub variable is whats null. You need to verify under the covers that the hubs are coming back properly.
<script type="text/javascript" src="~/signalr/hubs"></script>
This should return a properly formatted jQuery ready block, that defines all the hubs and server methods for those hubs. Using a tool like Fiddler will help with this.
I would also start using Chrome or Firefox w/Firebug, both have their advantages and disadvantages, but both will give you a network monitor and debugging facilities. Being able to catch unhandled exceptions has been a life saver trying to debug all things JavaScript.
Hope this helps you on your quest to solve your outstanding issues.
Firstly, the YouTube video is now out of date in relation to the version of SignalR which is now available.
Secondly, I would just delete the project that you are using and start again. This time, install the SignalR Alpha release via NuGet package manager.
Install-Package Microsoft.AspNet.SignalR -pre
Install-Package Microsoft.AspNet.SignalR.client -pre
Once you have done this, go and read over the documentation/examples at the SignalR website found here
https://github.com/SignalR/SignalR/wiki
If you follow some of the basics, then you should be sorted.

Migrating from V5 to V6 of the Facebook C# SDK

I'm trying to migrate from V5.3.2 to V6 of the SDK. I've got an ASP.NET 4.0 Canvas application. I noticed that now there's no more facebook.web.dll (which I previously used), and found this info:
>
Removal of Facebook.Web.dll and Facebook.Web.Mvc.dll
Starting from v6, we are depreciating Facebook.Web.dll and Facebook.Web.Mvc.dll and will no longer be providing it.
...
Starting from v6, you will have to use the Facebook Javascript SDK to get the access token and pass it to the server using secure https connection or use the Facebook OAuth Login Dialog.
Decoding signed request (ParseSignedRequest/TryParseSignedRequest) has been moved to FacebookClient instead.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest("app_secret", Request.Params["signed_request"]);
<<<<
(http://blog.prabir.me/post/Facebook-CSharp-SDK-Glimpse-into-the-Future.aspx)
So that's all well and good. Previously, I had this in my code behind:
protected void Page_Load(object sender, EventArgs e)
{
var auth = new CanvasAuthorizer { Permissions = new[] { "user_about_me" } };
if (auth.Authorize())
{
ShowFacebookContent();
}
}
To change it, I've now got the Javascript SDK successfully loading and logging in my user:
<div id="fb-root"></div>
<script type="text/javascript">
FB.init({ appId: 'xxxxxxx', cookie: true, status: true, oauth: true });
FB.getLoginStatus(function (response) {
if (response) {
alert(response.authResponse.accessToken);
}
});
</script>
I've tested this and it successfully logs in the user. But how do I then get it to do a postback and call the server side method that it was calling before (ShowFacebookContent)? I assume that whatever I do will have to pass the accessToken or the SignedRequest so that fb.ParseSignedRequest will work and on the server we can generate a FacebookClient.
I'm guessing that several people will be in a similar situation, trying to migrate off of facebook.web.dll, so any guidance would be really great.
Depending on your need pass either the signed_request or the access_token.
And also don't pass the access_token over http. Use secure https connection.

SignalR Hub not executing the specified javascript

I am using SignalR in an ASP.Net Web Application project and am having issues. My goal is to make any changes in the administrative side of the site cause some GridViews to refresh. I was planning on doing this by sending the signal for some javascript to be run, thereby refreshing the update panels containing the GridViews.
The issue right now is that I cannot get any of the code my hub is trying to call to execute in the client. I am receiving the following error in FireBug from the jquery.SignalR.js file, but I'm not sure how to proceed to fix it:
Firefox can't establish a connection to the server at ws://localhost:40068/signalr?data=[]&transport=webSockets&clientId=92e4f7b9-0118-4fd9-bb55-5f22338d6162.
(function(n,t){"use strict";if(typeof ...on=n.signalR=i})(window.jQuery,window)
After it throws this error it still looks like it is setting up the connection, but none of the javascript being sent through the hub is executed
I have set up the following hub in my site:
namespace testProject
{
public class statusChanges : Hub
{
public void ServerChange()
{
Clients.serverChange();
}
}
}
I have the following code in my button click event in the admin section. Debugging shows that this code is being run by the server:
var clients = Hub.GetClients<statusChanges>();
clients.serverChange();
Finally I have this code in my page trying to just launch an alert when it receieves the signal to confirm it is working.
<script type="text/javascript">
$(function () {
var statusChange = $.connection.statusChanges;
statusChange.serverChange = function () {
alert(8);
};
$.connection.hub.start();
});
</script>
Does any one have any ideas why this would not run or what the FireBug error means?
The error in firebug is expected. It's the websocket connection failing, don't worry about it as SignalR will fallback to longpolling. You have a method on the server side with the same name as a client side event. That doesn't work.
You want something like this:
public Administration : Hub {
}
Event handler:
var clients = Hub.GetClients<Administration>();
clients.serverChange();
Javascript:
<script type="text/javascript">
$(function () {
var administration= $.connection.administration;
administration.serverChange = function () {
alert(8);
};
$.connection.hub.start();
});
</script>

VS 2008 web services generating wrong url

Haven't done much web service development so this is probably an easy fix. Created both a mobile device project and web service project. When I add the service to my mobile project the soap document method attribute is wrong. All other info is correct. It generates service/method when it should actually be service?op= method. it will not work unless I manually change this url
You can try changing the URL you are using from http://whatevertoyourwebservice.asmx to http://localhost/whateverwebservice.asmx If you have the ability to use localhost this will work without having to change the url in the app.config folder. the other way is to use JavaScript to call your web service.
Here is an example is use for UTCTime webservice:
var portalUrl = window.location.href.substring(0, window.location.href.indexOf('/', 8));
var serviceUrl = portalUrl + "/your_webservice_location/";
var utcTimeOffsets = [];
function GetUtcOffsets(timezones, func) {
var proxy = new ServiceProxy(serviceUrl);
proxy.isWcf = false;
proxy.invoke("GetUTCOffsets",
{ tzName: timezones },
function(result) {
utcTimeOffsets = result;
if (func) func();
},
function(error, i, request) {
alert(error);
//setTimeout(function() { GetUTC(location) }, 1000);
},
false);
}
Other then that there is going to be no way, that I have found anyways, to make the C# webservice call dynamic. If you find a way please let me know. I know that these two options will work.

Categories