Get data from server side variables in a JS variable? - c#

I want to store data in a client side variable from a server side one, is it a good practice?
I have an app which uses a web service and I dont want to expose the ip on the source code, so it would be good if I can set a client side variable with that ip.
Now someone told me that for example getting values from the Session and storing them in a JS variable could be known as a "bad thing", as it represents an XSS Hole and I dont want my website to be marked as a "unsafe" one.
The reason I want to store the value on a client side variable is so that I can use JQUERY - AJAX so that the client does not have to re load the page for every request.
Can you help me out?

There's nothing inherently wrong with saving server side data on the client side.
Here's an easy way, for PHP:
<script>var someValue = "<?php echo $some_value; ?>";</script>
This saves a PHP value in the someValue JavaScript variable.
For more complicated data structures, here's a nice way to convert between the two languages:
<script>var someValue = JSON.decode("<?php echo json_encode($some_value); ?>");</script>
This only becomes a bad idea when the data you want to save client side is sensitive. There's no way to tell what your intentions are, so you have to use your best judgment.

Code Generating in JS
<script >
<%= SomeMethodFromCodeBehind() %> //JS goes here.
</script >
Pros: You get access to everything you want on the server.
Cons: You are writing JS using C# and C# string methods aren't exactly templating engine.
You will think you have access to Session, but only at code gen time!
If you mix user input into the results, then this is "JavaScript Injection", which get's lumped in with XSS.
Code Generating Just the Data
<script >
var myNumber = parseInt(<%= Convert.ToInt32(Session["TheNumber"]) %>,10);
var id = '<% TextBox.ClientID %>';
</script >
The above just generates the data, not all the code, so it's easier to see what is potential user input (maybe the Session part) and then force it to a suitable datatype, or do some JS escaping on the strings.
In my experience, I've only needed to ever do this for ClientIDs and sometimes properties of controls that don't have a clientside API.
Calling Services
If you don't code generate function that returns 42, maybe you can leave the function on the server and just have the JS gather the parameters. For one, calling a webservice isn't going to be subject to XSS-- the user would have to attack the parameters of the webservice, where as in code generation, the user can do all sorts of attacks if only he can figure out how to get his code output (esp on someone elses browser). So now you get to create a JS friendly web API. Here are some things that can go wrong:
<script >
//Things that used to be somewhat secret are potentially public now.
PageMethods.GetSesion("Blah",onSuccess);
//Wow, something that used to be hard for the user to tamper with is now convenient to
//tamper with. Now Session is ALL user input (and hence evil)
PageMethods.SetSession("Blah",42);
//Okay, now the user has the ability to read your secrets, conveniently
PageMethods.Encrypt("Blah", onSuccess);
PageMethods.Decrypt("Blah", onSuccess);
if(password=="xyzzy")
{
PageMethods.ShipTheGoods(address,goods); //User can call this directly.
}
</script >
(I'm not promoting PageMethods, but they sure are shorter for sample code than the alternatives)
The above sort of code is another common issue when you write JS code when you're used to writing server side code. One book called this overly granular APIs and attacks on control of flow (that if statement that doesn't really protect ShipTheGoods from being called without a password)
Anyhow, in a JS page, the way to track state (i.e. Session) is just a variable, "var customerInFocus = 'joe'). You can use code generation to output a value-- then when you are ready to save, send it back to the server in a pagemethod (or web service) call and treat all of those parameters as user input that has possibly, probably been tampered with along the way.

Related

How to share data between two web pages?

Im trying working on a web app project and trying to figure out how to display my answer on the second web page.
I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.
Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;
var cost = ((int)duration.TotalMinutes) * 0.35m;
txtCost.Text = cost.ToString("c");
I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?
Sharing value between two views in MVC application, try following
// To save into the Cache
System.Web.HttpContext.Current.Cache["CostKey"] = cost;
// To retrieve Cache Value
var cachedValue = System.Web.HttpContext.Current.Cache["CostKey"] as double;
For Session State, have a look at this link
In ASP.NET WebForms application, you can pass data around in various ways:
Cache
See the Learning Curve answer for examples.
However, the object put in the cache is not guaranteed to be found again if the server experiences memory shortage or alike. The ASP.NET manages the cache and evicts objects on its own to maintain memory availability. This is in contrast with ApplicationState and SessionState where the objects are kept until they are removed manually, or the Application ends or Session expires.
Session and Application states
You can put any object in the SessionState object and retrieve it elsewhere in your code. However, you need to cast it appropriately as the SessionState accepts object-s. E.g. if you store a number, when you retrieving it, you must do the casting yourself, just as you already did it.
The reason it doesn't work, is perhaps you're trying to retrieve it from within another user's SessionState. Yes, the SessionState is a per-user structure. If you need to add the value as from one device and use it on another, use ApplicationState:
Application["cost"] = cost;
Redirecting Response
Using this technique, you could force the browser to request another page from the server and specify the full query string, including the variables you need. E.g. :
var destination = Server.UrlEncode("/someOtherPage.aspx?cost=34.65");
Response.Redirect(destination);
As an alternative, you can use Server.Transfer("someOtherPage.aspx") to save the roundtrip. However, in that case, the browser doesn't change the address in the address bar so the user is misled that she browses one page, but in fact, it is the someOtherPage.aspx.

Coldfusion - How to update Table Cells in Real time?

I am relatively new to ColdFusion (using ColdFusion 10) and I have a question regarding creating a real-time updated table.
Currently I have a C# application that I have writing stock prices to a csv (text) file every 2 seconds and would like to reflect these changes as they happen in a table on web page. I know I could have the entire table refresh every 2 seconds, but this would generate a lot of requests to the server and I would like to know if there is a better way of doing it ? Could this be easily achieved using ColdFusion 10's new html5 Web-sockets functionality ?
Any advice/guidance on which way to proceed or how to achieve this would be greatly appreciated !
Thanks, AlanJames.
I think you could rewrite your question and get at least 5 answers in first hour.
Now to answer it, if I understood well what you're asking.
IMHO websockets aren't there yet, if your website is for wide population and you are not 100% sure that they're coming with most recent Chrome or FF, forget it.
You could use some javascript websocket library which would gracefully fallback to flash or AJAX HTTP polling, like http://socket.io/ or cloud service like pusher.com . But this will complicate your life because you have 2-3 times more work in backend if you implement polling and websocket.
Regarding amount of requests, if you want real time data on screen, you gotta have server to support it.
You could optimize if you request once and refresh data for all the table, so not per cell. You'd get all new data at once and update those cells which changed with jquery. So not pulling all data again, or whole table HTML, just minimal amount of data.
AJAX polling would certainly help with amount of requests, time of the request being open is another possible problem though. You could do polling with BlazeDS which is even in ColdFusion 9.
some pages to look at:
http://www.bennadel.com/blog/2351-ColdFusion-10-Using-WebSockets-To-Push-A-Message-To-A-Target-User.htm
http://www.bennadel.com/blog/1956-Very-Simple-Pusher-And-ColdFusion-Powered-Chat.htm
http://nil.checksite.co.uk/index.cfm/2010/1/28/CF-BlazeDS-AJAX-LongPolling-Part1
There isn't a way to get live updates every 2 seconds without making some kind of request from your page to your server, otherwise how would it know if anything has changed?
Personally I would write a CFC method to read in your text file and see if it's changed, then poll that method every few seconds using jQuery to return whether it has changed or not, and pass back any updated content.
Without knowing the details of your text file etc. it's hard to write anything accurate. Fundamentally your CFC method would have to store (in a SESSION var probably) a copy of the text file data, so it could compare it with the latest read-in data and tell if anything has changed. If it has changed then send a structure back with the updates, or return a response saying it's unchanged.
Your CFC code would look something like this:
<cffunction name="check_update" access="remote" output="false">
<cfset response = structNew()>
<cffile action="read"
file="path\to\your\textfile.txt"
variable="file_content"
>
<cfif file_content NEQ SESSION.file_content>
<cfset response.updated = true>
<cfset SESSION.file_content = file_content>
<cfset response.content = structNew()>
<!--- code here to populate 'content' variable with updated info --->
<cfelse>
<cfset response.updated = false>
</cfif>
<cfreturn response>
</cffunction>
Then the jQuery code to poll that data would look like this:
var update_interval;
var update_pause = 3000;
function check_update() {
var request = {
returnformat : 'json',
queryformat : 'column',
method: 'check_update'
}
$.getJSON("path/to/your/service.cfc", request, function(data) {
if(data.UPDATED == true) {
/* code here to iterate through data.CONTENT */
/* and render out your updated info to your table */
}
});
}
$(document).ready(function () {
update_interval = setInterval(check_update(), update_pause);
});
So once the DOM is ready we create an interval that in this case fires every 3 seconds (3000ms) and calls the check_update() function. That function makes a call to your CFC, and checks the response. If the response UPDATED value is true then it runs whatever code to render your updates.
That's the most straightforward method of achieving what you need, and should work regardless of browser. In my experience the overhead of polling a CFC like that is really very small indeed and the amount of data you're transferring will by tiny, so it should be no problem to handle.
I don't think there's any other method that could be more lightweight / easy to put together. The benefits of long polling or SSE (with dodgy browser support) are negligible and not worth the programming overhead.
Thanks, Henry

adding razor statement in javascript

Im trying to add some C# code in my javascript. But I can't parse my var name into the C# code.
What I want is this:
$.ready(function(){
var name = $("#input");
#Class.text(name)
});
But it wont allow me to parse the name.
This is a short version of what i got, the #Class represent a more complex function
The syntax is indeed incorrect.
The var name = $("#input"); is javascript. It is executed at the client end after the document is loaded. The #Class is server side and is executed when the page is being generated.
You cannot use javascript variables in C#. What is it that you are trying to achieve; there may be a different way to do so.
--
Update : You are trying to call a c# method from javascript.
Overall this will require a post back to the server - see http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
#MichaelTotKorsgaard Based on our discussion in the comments of your question, I think I now understand. Unfortunately what you're trying to do simply won't work. It doesn't work that way. The reason you do AJAX/JSON is because, once C#/MVC/ASP.NET returns HTML (it doesn't actually know if what it returns is valid), it's up to the Client to "do stuff" with it. That's where Javascript comes in. But the server-side MVC and client-side JS don't actually know anything about each other. You Need to either 1) post back or 2) use AJAX.
It's time to saddle up and learn how to do it :)
If you give more details about what you're actually trying to accomplish -- like what you're trying to load from JS/AJAX -- then I'm sure SO can give you more information to set you on the right path.

Javascript var inside a c# function inside Javascript

I am trying to write a javascript function that calls an Dictionary value and than tries to split it on a ยด_'. The problem is that the Key to get the value from Dictionary is in an Javascript var that is extracted from a dropdownlist. Is it possible to use an Javascript var inside an c# function inside Javascript?
the Code as it is now:
var Category = document.getElementById('Properties').value;
var Name = document.getElementById(Category).value;
Category = '#Model.Dictionary[Name].Split('_')[0]';
EDIT:
People are misinterpreting my problem, the .Split function does work but the Dictionary[Name] is giving me problems. if i enter
var Category = document.getElementById('Properties').value;
var Name = document.getElementById(Category).value;
Category = '#Model.Dictionary["Bicycle"].Split('_')[0]';
into the code it works perfectly, but I want to get the "Bicycle" part dynamically out of an DropDownList.
EDIT 2:
Okay I have decided that what I am over thinking the situation and that what I am trying to do needs alot more work than is needed, found a beter solutions, thanks for everybody that tried to help me.
You're a bit mixed up between client and server side. To interact with server side code like this, you'll need to either post to the server or write an AJAX callback to call a server method.
http://mikehadlow.blogspot.com/2008/10/mvc-framework-and-jquery-ajax-heaven.html
No, that is not possible. All the server code runs before the page is sent to the browser, and all the client code runs after.
What you would have to do to use the dictionary in the client code is to create Javascript code from the server side, that recreates the dictionary on the client side.
If that's not possible, you would have to make an AJAX call to the server.
I have avoided the issue completely by having the DropDownList have different values in Value and Text, doing this is can get the wanted input that used to be in the Dictionary out of the Value of the DropDownList without changing the Text.

jquery datatables fnfilter + script performace

I am away from my development workstation so I thought I'd ask this in hopes of getting an answer when I try it tomorrow. I have a two part question relating to a web application i built using c# jquery and jquery datatables:
1) I know that we can set the value of fnfilter as metioned on their page using something like:
var oTable;
$(document).ready(function() {
oTable = $('#example').dataTable();
/* Filter immediately */
oTable.fnFilter( 'test string' );
} );
however is there a way to retrieve the value entered by the use in the search bar? I was thinking along the lines of
var aContainer= oTable.fnFilter()
or
var aContainer= oTable.fnFilter($(this).html())
2) My application has to retrieve values from another source on the web. These are the value displayed in the datatable. Most of my processing(counting, etc..) is done client side and has drastically slowed down generating the web app. Does anyone know of any suggestions to increase performance of client side scripts specifically datatables?
If your datatable is really instantiated as oTable = $('#example').dataTable(); then doing this:
var textEntered = $('#example_filter input:text')[0].value;
Should return whatever the user entered on the field for filtering.
In answer to #1, you can get the value of the text entered into the search box by doing
// Assume the table's id attribute is 'blah'
var search_string = $('#blah_filter>input').val();
As far as #2, have you considered server-side processing of the data and sending the result to the client?
This article
might give you a big help if you decide to write server side code. Now researching it myself (and not looking forward to implementing custom filtering!).

Categories