SignalR Client How to Set user when start connection? - javascript

Server side:
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var user = Context.User.Identity.Name; // Context.User is NULL
return base.OnConnected();
}
Client side (in Console project):
IHubProxy _hub;
string url = #"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
When the client connect to the server, I want to know the map between userName and connectionId, But Context.User is NULL. How do I set this value in the client side?

try this with queryString in asp.netcore 2.1:
Client (javascript)
set query string after url like follow:
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:10499/chathub?username=xxxx").build();
connection.start().then(function ()
{
// do some thing here ...
}).catch(function (err)
{
console.error(err.toString());
});
.
.
.
Server
public override Task OnConnectedAsync()
{
var username = Context.GetHttpContext().Request.Query["username"];
// username = xxxx
return base.OnConnectedAsync();
}

Pass your username using query string.
Client
First set query string
string url = #"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.qs = { 'username' : 'anik' };
connection.Start().Wait();
Server
public override Task OnConnected()
{
var username= Context.QueryString['username'];
return base.OnConnected();
}

Client
var connection = new HubConnection(<YOUR_URL>);
connection.Headers.Add("username", "maria");
var myHub = connection.CreateHubProxy("MyHub");
Server
string username = Context.Headers.Get("username");
Console.WriteLine("New client connection - " + username);

If your using basic authentication create a new System.Net.NetworkCredential
string url = #"http://localhost:8080/";
var connection = new HubConnection(url);
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = "domain";
myCredentials.UserName = "username";
myCredentials.Password = "passwd";
connection.Credentials = myCredentials;
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
See: https://learn.microsoft.com/en-us/dotnet/api/system.net.networkcredential.username?view=net-6.0

try this
Client (C#)
//Enter query string
var querystringData = new Dictionary<string, string>();
querystringData.Add("username", "naveed");
IHubProxy _hub;
string url = #"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
connection.Start().Wait();
Server
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var username= Context.QueryString["username"]; //here you will receive naveed as username
return base.OnConnected();
}

Related

Azure DataLake File Download From Javascript

I was trying to download the file from azure data lake storage. it's working on c# side using Rest API. but it's not working in a java script.
My Sample c# code is
//Get Access Token
public DataLakeAccessToken ServiceAuth(string tenatId, string clientid, string clientsecret)
{
var authtokenurl = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenatId);
using (var client = new HttpClient())
{
var model = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type","client_credentials"),
new KeyValuePair<string, string>("resource","https://management.core.windows.net/"),//Bearer
new KeyValuePair<string, string>("client_id",clientid),
new KeyValuePair<string, string>("client_secret",clientsecret),
};
var content = new FormUrlEncodedContent(model);
HttpResponseMessage response = client.PostAsync(authtokenurl, content).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var accessToken = JsonConvert.DeserializeObject<DataLakeAccessToken>(response.Content.ReadAsStringAsync().Result);
return accessToken;
}
else
{
return null;
}
}
}
File Download Code is
public void DownloadFile(string srcFilePath, ref string destFilePath)
{
int i = 0;
var folderpath = Path.GetDirectoryName(destFilePath);
var filename = Path.GetFileNameWithoutExtension(destFilePath);
var extenstion = Path.GetExtension(destFilePath);
Increment:
var isfileExist = File.Exists(destFilePath);
if (isfileExist)
{
i++;
destFilePath = folderpath+filename + "_" + i + "_" + extenstion;
goto Increment;
}
string DownloadUrl = "https://{0}.azuredatalakestore.net/webhdfs/v1/{1}?op=OPEN&read=true";
var fullurl = string.Format(DownloadUrl, _datalakeAccountName, srcFilePath);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
using (var formData = new MultipartFormDataContent())
{
var response = client.GetAsync(fullurl).Result;
using (var fs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
response.Content.CopyToAsync(fs).Wait();
}
}
}
}
first i was Generate the token using client credentials and the token based download file using path example https://mydatalaksestore.azuredatalaksestore.net/myfolder/myfile i pass myfolder/myfile in source path and destFilePath file name based download the file
in javascript i was get the accesstoken from my api server and send the request for mydatalakestore it's throw error for cross orgin for localhost:8085 like this
Any one know how to download the datalake store file using Javascript from Client Side using Access Token without cross orgin error
Thanks in Advance

Node.js server went to both on data event and end event after java client sent https request

Code link: https://github.com/jason51806/java_client/tree/master
Client code:
public class SendClient {
public static void main(String[] args) throws Exception {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
/*
* end of the fix
*/
URL url = new URL("https://localhost:8001");
URLConnection con = url.openConnection();
//HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
JSONObject writeJsonObj = new JSONObject();
//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
//BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
writeJsonObj.put("msg","Hello server!");
System.out.println(writeJsonObj.toString());
printWriter.println(writeJsonObj);
printWriter.flush();
/*String text = writeJsonObj.toString();
writer.write(text);
writer.flush();*/
while (true) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
System.out.println("--prepare to receive message");
String line = null;
line = bufferedReader.readLine();
System.out.println("read something from server");
System.out.println(line);
JSONObject readJsonObj = new JSONObject(line);
System.out.println(readJsonObj.toString());
if (readJsonObj.has("test")) {
System.out.println("Send the second message to server");
printWriter.println(writeJsonObj);
printWriter.println();
printWriter.flush();
}
}
}
}
Server code:
var https = require('https'); //Require module
var fs = require('fs');
//varable declared
var Https_Options = null; //Https server key and certificate
var Server = null; //https server
var ServerInformation = null; //Server's address and port
var ClientNumber = 0; //current nunber of connected client
var num = 1;
Https_Options =
{
key : fs.readFileSync('./hacksparrow-key.pem'),
cert : fs.readFileSync('./hacksparrow-cert.pem'),
allowHalfOpen : true
};
Server = https.createServer(Https_Options).listen(8001, "localhost", function() {
ServerInformation = Server.address();
console.log("Https server is running at "+ServerInformation.address+":"+ServerInformation.port);
} //end of https.createServer call back function
); //end of https.createServer.listen
//Request listener, listening request event when client sending the request
//Call Back Function Description: "data", "close", "error" event
Server.on('request', function(req, res) {
console.log("clients: "+ (ClientNumber++));
//Data listener, litening is there any data sent from client
//Call Back Function Description: The handler of "data" event
req.on('data', function(chunk) {
var ServerDataObj = null; //the data received from client and also send this Obj as response to client
var testobj = {};
testobj =
{
'test' : num++
};
//ServerDataObj = JSON.parse(chunk.toString());
ServerDataObj = chunk.toString();
console.log('server receive message' + ServerDataObj);
res.write(JSON.stringify(testobj) + '\r\n'); //send back to client
delete ServerDataObj;
} //end of event "data" call back function
); //end of event "data"
req.on('end', function() {
console.log("client end.");
} //end of event "end" call back function
);
//listening close event
//Call Back Function Description: Emmit whether the client socket close
req.on('close', function() {
console.log("client close.");
--ClientNumber;
} //end of event "close" call back function
); //end of event "close"
//Error listener,
//Call Back Function Description: if error happen, catch & print
req.on('error', function(err) {
console.error("req: "+err);
} //end of event "error" call back function
); //end of event "error"
} //end of event "request" call back function
); //end of event "request"
I use PrintWiter to send request on my Java client code.
The node.js server received request data successfully but it triggered the end handler that causes server can't receive the request from client anymore.
I also try BufferedWriter and DataOutputStream to send my request to server, but they both have the same problem.
Is there any way to not trigger the end handler on server and keep the client send data continually?
Or any other ways to send message between Java client and node.js server on https?

SignalR javascript client not picking up event from hub

I have a method on the hub however I am not getting any messages from this. I get the connection ID's from my user to connectionid mapping dictionary and loop through these connectionid's and then invoke a method on the client side called deviceDiscovered I can also confirm that the browser does connect to the hub
Here is my hub method
public async Task DetectDevice(dynamic message)
{
//We will be searching via the userid
var connectionId = Context.ConnectionId;
//now we get the connectionID from the table.
var connectionObj = ConnectionTable[connectionId];
//we now check whether this is a pathfinder or browser client
if (connectionObj.clientType == "pathfinder")
{
/*The pathfinder initiated the request and so this means the message should be forwarded to the browser client
that requested this resource*/
//Grab the data out of the dictionary.
PathfinderDetection deviceDiscoveredNotification = JsonConvert.DeserializeObject<PathfinderDetection>(message);
var userId = deviceDiscoveredNotification.userId;
var sysInfo = deviceDiscoveredNotification.sysInfo;
var found = deviceDiscoveredNotification.data;
if (found == "FOUND")
{
var deviceId = deviceDiscoveredNotification.deviceID;
var connections = ConnectionTable.Where(val => val.Value.id == connectionObj.id).Select(key => key.Key).ToList();
foreach (string connection in connections)
{
Clients.Client(connection).deviceDiscovered(deviceId);
}
}
else
{
//call a method on client side.
Clients.Group(userId.ToString()).noDevice("NOTFOUND");
}
I can see that the deviceID variable is populated and that the connection exists, however not getting anything back from the hub when looking at the client
here is my client side code:
<script>
$(document).ready(function(){
var connection = $.hubConnection("http://localhost:59016");
var contosoChatHubProxy = connection.createHubProxy('metrics');
contosoChatHubProxy.on('taskAdded', function(data){
console.log(data);
});
contosoChatHubProxy.on('deviceDiscovered', function(data) {
console.log(data);
});
contosoChatHubProxy.on('taskUpdate', function(data){
console.log(data);
});
contosoChatHubProxy.on('noDevice', function(found) {
console.log(found);
});
});
</script>

Error on Downloading From using Asp.net web api

I'm using the code below for downloading with the web API in ASP.NET.
When I'm trying to click the download button, it calls the API.
After executing the "DownloadFile"-function, the download dialog box isn't coming .
[HttpGet]
public HttpResponseMessage DownloadFile(string DownloadFilePath)
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath(DownloadFilePath);
// check if parameter is valid
if (String.IsNullOrEmpty(DownloadFilePath))
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
// check if file exists on the server
else if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{// serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = DownloadFilePath;
}
return result;
}
I didn't get any exception from the code above, but the dialog box for downloading the file isn't coming.
Here is the code, I am using and it works great. I hope it will give you an idea
....
var fileBytes = Helper.GetFileBytes(filePath);//convert file to bytes
var stream = new MemoryStream(fileBytes);
resp.Content = new StreamContent(stream);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filerequest.FileName };
resp.Content.Headers.Add("Content-Encoding", "UTF-8");
return resp;
And, here is the code for GetFileBytes method,
public static byte[] GetFileBytes(string filePath)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
return File.ReadAllBytes(fileInfo.FullName);
}
return null;
}

Signalr persistent connection with query params.

I have a persistent connection which I would like to start with some seed info using query params. Here is the override in the connection.
protected override Task OnConnected(IRequest request, string connectionId)
{
//GET QUERY PARAMS HERE
return base.OnConnected(request, connectionId);
}
Now I have my route setup in global.asax file which looks like this.
RouteTable.Routes.MapConnection("myconnection",
"/myconnection");
And the client code looks like this
var connection = $.connection('/myconnection');
connection.start()
.done(() =>
{
});
Can someone tell me how I can pass query string params to this connecton so I can read them in the override as I seem to be hitting a brick wall on this.
Cheers hope someone can help,
Dave
HUBS
var connection = $.connection('/myconnection');
$.connection.hub.qs = "name=John"; //pass your query string
and to get it on the server
var myQS = Context.QueryString["name"];
To access your query string in javascript you could use something like
function getQueryStringValueByKey(key) {
var url = window.location.href;
var values = url.split(/[\?&]+/);
for (i = 0; i < values.length; i++) {
var value = values[i].split("=");
if (value[0] == key) {
return value[1];
}
}
}
Call it:
var name = getQueryStringValueByKey("name");
PERSISTENT CONNECTION
//pass your query string
var connection = $.connection('/myconnection', "name=John", true);
protected override Task OnConnected(IRequest request, string connectionId)
{
//get the name here
var name = request.QueryString["name"];
return base.OnConnected(request, connectionId);
}
Here is the source code where you can find out more: https://github.com/SignalR/SignalR/blob/master/src/Microsoft.AspNet.SignalR.Client.JS/jquery.signalR.core.js#L106

Categories

Resources