Display consistently changing value on an ASP.NET web form - c#

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

Related

How to Prevent / Avoid Brute Force Attack on AJAX Call to ASPX Page

I have an asp.net web application(old aspx).
A page(1) display number and on button click, It makes AJAX request to another aspx page(2) with number displayed on 1st page and get response. if number is not valid, response would have error message as invalid number.
Now,
2 Page can be requested through any script using loop find valid number.
In 1st page number can be modified through Developer tool and send request to 2nd page.
This cause brute force attack on 2nd page.
2nd page may be accessed by our another application.
Whether Anti Forgery Token could be implemented for this case.
I could not find any example for old ASPX.
In this context, Please advice how to prevent Brute Force Attack on 2nd page using any approach.
My Ajax Request
var data = ({ No: $('#No').text(), xyz: $('#xyz').text()});
$.ajax({
url: 'x.aspx?y=z',
data: Data,
dataType: 'html',
async: false,
type: "POST",
success: function (data) {
if (data.startsWith('eRROR')) {
//Reading and assigning error message to html control
}
else {
if (data == "Success") {
return true;
}
else {
//set value to HTML control
}
return false;
}
},
error: function (jqXHR, textStatus, errorThrown) {
//alert
return false;
}
});
Use GUID instead of a simple (sequential?) number. I'm guessing the number that you display on first page, is the internal ID of the record, which is probably generated as a sequential number by your DB and is very easy to guess.
The solution is to add a GUID column in your table. If you are using SQL server for DB, then GUID is a long, random string, which is not in sequential order.
After generating the GUID, on first page you should use the GUID instead of the id and pass it to the second page. The second page has to look up the GUID to find the ID.

Nancyfx Request.Session not holding values on AJAX post

I'm quite new to Nancy so hopefully I'm just doing something silly here. I've got a nancy service which I'm posting data to like so:
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify({
searchTerm: productSearchTerm,
pageSize: pageView.PageSize(),
selectedBrands: pageView.checkedBrands(),
pageNumber: pageView.CurrentPage(),
selectedCategories: pageView.checkedCategories(),
selectedGender: pageView.checkedGender(),
SelectedColours: pageView.checkedColour(),
saleItemsOnly: pageView.saleItemsOnly(),
selectedMinimumPrice: pageView.minPrice(),
selectedMaximumPrice: pageView.maxPrice()
}),
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function (data) {
bindSearchResult(data);
})
.fail(function (a) {
console.log(a);
});
Then in the service I need to hold on to a bunch of string values for future requests from the user, which I'm doing like this:
private void AddListOfStringToIsSessionNull(string name, IEnumerable<string> data)
{
if (Session[name] == null)
{
Session[name] = data.ToList();
}
}
These seems to set the session variables and an "_nc" cookie is present when I inspect the page after it returns.
However if I then F5 the page the session items are all null again at the server.
I've ruled out are cross site posting as it's all on the same domain.
Could this be an AJAX thing? Seems unlikely as this seems a pretty standard thing to do.
Or can you not set it on a POST?
If so is there a way around this?
If someone could help I'd be forever grateful as otherwise I'm going to have to revert back to writing this in WCF which will make me hurl myself from the window :)
Thanks a lot.
Edit
Open a new incognito window in Chome I hit home page, no nancy cookie
present (which is correct)
Enter a search term which calls back over and AJAX post and grabs JSON, also pops a list of strings in the Nancy Session
Check cookie, a nancy one has appeared like so and the session value is correct on post back:
npTBnqPp99nLd5fU0%2btJbq%2fY%2bdf2UFWTaq5D28Az7Jw%3dzF8cIHNxTWX399sbmowjheho2S29ocpKs1TXD51BrbyPPNCeLfAcYqWhkRHqWdwKJNED5kuspllIjhI5rf2W6NKtf8xo68BlF5eLLgJxMtAxw2yD2ednEzUazq1XBt2Id77t5LE5tZVwkpRGDT5b9J0nQnr9zfzCOALXb2hQQGBPkMVyNNTO24pW1UC6Uda3B86LLYA02Jgy4G9DiT6KsutR3pSXO8AZFOlcmAEHbSSX9A8FAHaL ... etc.
I then search for a different search term which calls this bit of code:
--Session.DeleteAll();
The nancy session is re-populated with new data and returns back to the browser
However at this point the cookie has not been updated with the new value it is still as below:
npTBnqPp99nLd5fU0%2btJbq%2fY%2bdf2UFWTaq5D28Az7Jw%3dzF8cIHNxTWX399sbmowjheho2S29ocpKs1TXD51BrbyPPNCeLfAcYqWhkRHqWdwKJNED5kuspllIjhI5rf2W6NKtf8xo68BlF5eLLgJxMtAxw2yD2ednEzUazq1XBt2Id77t5LE5tZVwkpRGDT5b9J0nQnr9zfzCOALXb2hQQGBPkMVyNNTO24pW1UC6Uda3B86LLYA02Jgy4G9DiT6KsutR3pSXO8AZFOlcmAEHbSSX9A8FAHaL.... etc.
Is there anything else I need to do to solve this?
So my issue was me being a bit daft really, the implementation of the cookie stuff works well, however there were occasions when I was stuffing too much into the cookie and pushing it over the 4K cookie limit.
This meant that I was seeing some inconsistent behavior where sometimes the cookie worked nicely (the cookie was < 4K) where as for some search terms too much was being written into the cookie which meant either the cookie was never created or it was not overwriting the existing cookie.
So yes, my fault, but thought this answer might aid someone as silly as me trying to store the world in a cookie..
Right I'm off to write a session provider.

Using AJAX to run actions while user is logged in

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.

JQuery $.ajax not bringing latest data

I am using JQuery 1.7.2. I am using highchart for making live data chart.
I maked one C# page where on the page load I am writing some jSON format data which I am using in another page with the help ajax call for highcharts. I will run that ajax call inside function and in success event of ajax call I will make setTimeout after 1 minute to call again function, So I will get latest data every time. Until here everything works very good.
But I have issue lets say data I am getting data only for 4 hr at every 1 minute than I keep my browser open and come next day. That time my aspx page will start with new fresh data from zero, so my highcharts should automatically remove all points and should pushing new data but it is not doing that. When I refresh my page all will start working good. Is there anyway that it should refresh by itself
My code for ajax call is as follow
function recieveData() {
var pathArray = window.location.pathname.split( '/' );
var chart = $('#container').highcharts();
$.ajax({
url: '/' + pathArray[1] + '/HomePageChartData.aspx',
dataType: 'json',
cache: false,
success: function (data) {
chart.yAxis[0].setExtremes(data.minY, data.maxY, true, true);
chart.series[1].setData([]);
chart.series[1].name = data.lineSeriesName;
chart.series[0].setData([]);
chart.series[0].name = data.areaSeriesName;
for (var x in data.lineSeriesData) {
chart.series[1].addPoint([data.lineSeriesData[x][0], data.lineSeriesData[x][1]]);
}
for (var x in data.areaSeriesData) {
chart.series[0].addPoint([data.areaSeriesData[x][0], data.areaSeriesData[x][1]]);
}
setTimeout(recieveData, 60000);
}
});
}
##Edited with more explanation
It's look like I could not properly previously so I will do it again. My scenario is like data come between 9 AM to 12.30 PM and it remain on the database until next day 7 AM. So my highchart will get data every minute between 9 AM to 12.30 PM which is working very good without any problem. But issue when we wipe out all data at next day 7 AM and we start getting new data at 9 AM my high chart is not clearing by itself and start getting new data.
But if i refresh my browser I will get new data and it work good. So I was looking something like if we wipe all data my ajax should get alert and reload the page or clear data from highchart.
So I was looking for some event or way to do it in ajax call. Some guidance from experts.
Try using data parameter in your $.ajax call to send time, it will differentiate your each ajax call
data:{'time': new Date().getSeconds() }
You can compare actual time with next day, calculate interval, and then set timeout to reload page, code snippet:
var now = new Date(),
time = (new Date(now.getFullYear(), now.getMonth(), now.getDate()+1), 7).getTime() - now.getTime(); //calculate next day 00:07:00 in ms
setTimeout(function () {
document.location.reload(true);
}, time);

Replacing Timer text with result of DB calculation when Timer hits 00:00:00

I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});

Categories

Resources