I'm currently programming a messaging system for a website using C# .NET as backend.
The messaging system is very similar to Facebook's web interface, which allows you to "chat" with another person, sending the messages via AJAX.
I've created a webservice (C#) that handles the actual sending message bit. I'm using JQuery to activate that service using the following code:
// generic webservice used to retrieve count from db
function SendMessageAJAX(taskID, sendeeID, sendeeType, recipientId, recipientType, content) {
$.ajax({
type: "POST",
url: "/WS/UIServices.asmx/SendMessage",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'content': content, 'SendeeType': sendeeType, 'SendeeId': sendeeID, 'RecipientType': recipientType, 'RecipientId': recipientId, 'taskID': taskID }),
dataType: "json",
success: function (msg) {
// refresh chat area
LoadMessages(false);
},
error: function () { alert("error"); }
});
}
As you can see, I'm passing both the sendee / recipient info in my request. Obviously the code is very dangerous, as anyone can modify these values and impersonate any user.
I have the current logged-in user in a SESSION variable on my server side, but the code runs async, meaning the session variable is NOT defined when it runs.
What would the best way to safely run these actions via AJAX?
There are two options:
You can either encrypt your ajax requests like this code project article OR use SSL for website.
Implement your server code in an IHttpAsyncHandler and also implement IRequiresSessionState so you have access to the session.
http://msdn.microsoft.com/en-us/magazine/cc164128.aspx
is it possible to run async call to set a session in ASP.NET?
Using ssl is always preferred but other options are also viable if you have time to implement.
Related
I am currently writing a program in C# that constantly outputs random values between 1 and 12 and displays them in a label control on an ASP.NET web form. While the output is successfully written to the web form, it only displays one value. In other words, I want the label output to track the output (display) each value that is produced by the function as written below to produce a consistently changing value:
[WebMethod]
public static string StreamData()
{
string[] value = new string[1];
Random rnd = new Random();
Thread t = new Thread(delegate ()
{
while (true)
{
value[0] = rnd.Next(1, 13) + "";
}
});
t.Start();
return value[0];
}
I have tried using an AJAX function to pull the data from the function but I am not too sure if I am going about displaying the data in the right way:
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/streamdata',
data: '',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
//alert(msg.d);
$('#<%= lblReading.ClientID %>').html(msg.d);
}
});
});
</script>
The program is being written to test the concept of trending live data from PLCs using TIA Portal 15 with said data obtained from sensor readings across a production line. The idea behind this program is to serve as a proof of concept that real-time data can in fact be displayed and trended in an ASP.NET web environment to be accessed across a range of web-compliant devices. Despite my efforts in displaying random values in this way, my attempts have been thus far unsuccessful, although I am determined to not give up. I researched this method which uses SignalR to achieve something similar to my desired solution, though I am unsure of how to implement it in my case: How to implement real time data for a web page
Could somebody please shed some light on how the above might be achieved?
Many Thanks,
Ben.
Your requirement can be accomplished in ASP.Net web forms using SignalR.
Please take a look at this small tutorial on how to do that,
Adding SignalR to an ASP.NET WebForms Project
I am using Asp.net Identity for token based authentication in my web api application. The problem is I have to perform some operations after the token is generated and the user is authenticated and before the redirection to client side occurs.
I have a login page which uses /token token authentication . Once the token is issued i need to keep the user and token values in a session. [this session will be used to show online users.]
Client request
$('#btnLogin').click(function () {
$.ajax({
// Post username, password & the grant type to /token
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
}
});
Server side
[HttpPost]
public void Login()
{
OnlineUsers user = new OnlineUsers();
var users = (HttpContext.Current.Session["ActiveUsers"] as
List<OnlineUsers>) ?? new List<OnlineUsers>();
users.Add(user);
HttpContext.Current.Session["ActiveUsers"] = users;
}
I need to call this controller method after the token is issued and use is authenticated.
Is there any solution to this?
If you want to intercept generation of the token think you have to customize the aspnet identity behaviour
https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.usermanagerextensions.generateusertoken(v=vs.108).aspx
With Web API using session is not a good approach, to keep user's information in client side you can use browser's localstorage. Once the user authenticated via your login api controller, you can return the user's required info as json to client, then you can keep it to browsers. Web API is by default stateless so i think session is not suitable with it, additional burden on the client. Storing session state on the server violates the stateless constraint of the REST architecture. So the session state must be handled entirely by the client.
Web API
[HttpPost]
public IHttpActionResultLogin()
{
OnlineUsers user = new OnlineUsers();
user=YourUserDetailsMethod();
return Ok(user);
}
Client:
$('#btnLogin').click(function () {
$.ajax({
// Post username, password & the grant type to /token
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function(response){
window.localStorage.setItem('userInfo', response);
$('#UserName').val(window.localStorage.getItem('userInfo').UserName);
}
});
I'm testing the Azure server with pages that use Ajax(json)/Webmethod functions.
Some of those functions check HttpContext.Current.User.Identity.IsAuthenticated before they run code. Unfortunately, if a user is logged in and the page doesn't make a full postback request to the server, only those webmethods functions that check HttpContext.Current.User.Identity.IsAuthenticated stop running completely after couple of minutes without giving any error. They don't even run the else code block (see below).
I've tested those pages on a local server and everything worked fine as it should, even after a long period of inactivity. Here is an example of a webmethod
[WebMethod]
public static string serviceMenu(int IDservice)
{
StringBuilder SBphotoMenu = new StringBuilder();
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// Do stuff
}
else
{
// Do other stuff
}
return SBphotoMenu.ToString();
}
I'm calling the webmethod as follows:
function serviceMenu(IDservice) {
$.ajax({
type: "POST",
url: "/UserControls/serviceMenu",
data: "{ IDservice: " + IDservice }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// Do Stuff
}
})
}
This behavior occurs only if the user is logged in. Now if the user is not logged in then all functions work properly even on Azure.
As a matter of fact, when the webmethods stop running and I refresh the page the user is still logged in and the webmethods start running again but for couple of minutes only and then the same behavior occurs again.
What's going wrong?
The problem is caused by the session variables and not autentication. In fact the session state is not maitained for ASP.NET applications in Azure using the default "inProc" method. Azure uses other methods, of which some are costy: Table storage, SQL Azure, or Windows Azure Caching.
I'm actually working on a tracking system project in asp.net c#. I've already implemented the login section and made use of "session" to track the users. I have a map (Google Map v3) that is being displayed on the homepage which shows the user his/her current location after successful login. What i want to do now is retrieve the value of the username and display it on the map. I've tried to keep the value of the username in an html element and then try to access it with JavaScript but alas! That didn't work! Any help will be greatly appreciated.
Expose the username through a WebMethod in c# and then grab it when you generate your marker using ajax. Similar to this:
function grabUser() {
$.ajax({
type: "POST",
url: urlToMethod,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
}
[System.Web.Services.WebMethod]
public static string User() {
return userName;
}
I have an ASP.NET page, where the user is able to trigger a console app on our server, which generates a file. What I want is the user to see a message that states 'Requesting file', then as soon as the file becomes available (i.e. File.Exists for the file returns true), the Requesting file message will change to a link of the file.
Is this easy to accomplish in ASP.NET?
In you web page implement a JSON call to a certain WebMethod which checks if the file has be been generated or not.
you can add your message in the calling function and clear it in the complete event, where you can create the link to the file also
function ddlLeaveChanged(sender, e) {
if (leaveTypeId != '-1' && dateFrom != '' && leaveStatusId != '-1') {
$('#lblMessage').show();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: WebServiceUrl + 'YourMethod',
success: FunctionSuccedded,
error: FunctionFailed
});
}
function FunctionsSuccedded(result, e) {
if (result) { $('#lblMessage').hide(); }
}
This can be achieved using a combination of:
Javascript setInterval
[jquery.Ajax][2]
ASP.NET Web Method
A javascript function can be triggered every x seconds (using setInterval) to trigger a Web Method using AJAX to check whether the file exists.
Check the links I've provided above. These should be all you need to get this working.
If you want to avoid file systems all together you could key off a database field as well, i.e. when the linked is clicked an entry is made into a database table of some sort that signifies file creation pending, and then periodically check if the status has been updated. The server side code would update that same key and have a url in the datastore as well, so you could just check for the status of file created and the link the datastore. This would also result in you having a history of file creation, which you could purge as you saw fit, so from an ASP.NET perspective you would only be relying on data access code to determine if your file was created.
Not much different in ASP.NET vs any other platform. You can go about it like this:
Make AJAX call when the triggering link is clicked.
Server-side code that handles the call launches an external process to generate the file, and waits for it to complete.
After checking that the file is indeed there, reply to the AJAX call with a meaningful message (i.e. one that contains enough information to build a link to the file).