How to access IMemoryCache from C# and Javascript - javascript

I stored values in my cache using my Controller class using the dependency IMemoryCache. I am also accessing my cache and get few values from it like so:
//IMemoryCache initailized before this variable : _cache
public void foo()
{
var token = _cache.Get<TokenModel>("Token" + HttpContext.Session.GetString("TokenGuid"));
//Do something with token
}
Question is:
How can I can access the cache from my Javascript file?

Cache is located on the server while JavaScript is executed on the client. The only way I can think of is if you create a cache controller and create a Get action on it. After that you would call this action in Ajax and asynchronously get the server cache value.
public class CacheController : Controller
{
[HttpGet("{key}")]
public IActionResult GetCacheValue(string key)
{
var cacheValue = //get your cache
return Json(cacheValue);
}
}

IMemoryCache allows you to speed up your application by storing your data "in-memory". So you can reach memory from your javascript code.
Please have a look to the documentation of the IMemoryCache here: https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.1
What I would suggest you is get your cached data on backend side and put it cookie. Then later you can get cookie value from your javascript code.
I assume you have an instance of IMemoryCache which name is _cache.
You can set cache by like this.
_cache.Set(cacheKey, cacheEntry, cacheEntryOptions);
HttpCookie myCookie = new HttpCookie("yourCookieName");
myCookie["cacheData"] = cacheEntry;
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
or you can do the same after you get your cached data. Just get the data from your memory and set it to cookie.
You can get the cookie from your Javascript by using both DOM or JQuery.
If you would like to use DOM:
var x = document.cookie;
For jquery have a look at this answer on StackOverFlow:
https://stackoverflow.com/a/1599367/1261525

Related

Getting data from a .cs file to a .cshtml

I'm trying to pass the data received from my function to a .cshtml file that uses javascript.
public static int LastID()
{
int LastArticleNr;
SqlConnection conn = GetSqlConnection(null);
conn.Open();
LastArticleNr = conn.QueryFirstOrDefault <int> ("SELECT CAST(isnull(last_value,0) AS INT) AS ID FROM sys.identity_columns WHERE object_id = OBJECT_ID('Artikel')");
conn.Close();
return LastArticleNr;
}
Now I don't know whether this is possible or not, or whether I would need to use a different method of getting this data. However what I've tried is simply calling the function which, to probably no-ones surprise didn't do much. I've also tried this:
#using namespace.Classes.DataLayer;
#{
var LastID = DataLayer.LastID();
}
However even if the using clause should include the class in which this function exists, it fails to recognise the DataLayer class.
It really depends on how your application is structured. Like: What error do you get when you try to access the Data Access Layer?
But If this is being done on page load, you could pass the data into TempData:
TempData['LastId'] = LastID();
And then in your razor page:
#{
var lastId = TempData['LastId'];
}
However if you wanted to get it at any time after the page has loaded and do not want to refresh the page, you would have make an ajax call

Passing section of query result into session variables with Javascript

I'm having trouble passing the result of a query into a session variable, I think that the easiest way to do this is through Javascript. I have the query result showing but they will not pass to the session variable. At the end of each query resultant row, I have an add button that will activate the JS function to add to the session variable.
Query Result:
echo '<tr><td>'.$products['Name'].'</td><td>£'.$products['Price'].'</td><td>'.$products['Category'].'</td><td><img src="'.$products['Image'].'" width=100px /></td><td>'.$products['ProductID'].'</td><td><button onclick="setProduct('.$products['ProductID'].')">Add to Basket</button></td></tr>';
JS Function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
Code displaying contents of session variable:
echo $_SESSION['ProductID'];
$_SESSION is a server-side variable. You'd most likely want to set a $_COOKIE instead. Those are accessible on the client-side.
In addition to the answer posted, you can create a jQuery post request (or you can use AJAX) and send the JS session as value to a PHP file where you can access that value and create the corresponding PHP session.
Let's say, your JS function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
// ...
$.post('example.php', { session_name: YOUR-SESSION-NAME, session_value: YOUR-SESSION-VALUE });
example.php:
if (isset($_POST['session_name']) && isset($_POST['session_value'])) {
$_SESSION[$_POST['session_name']] = $_POST['session_value'];
}
This is not taking into consideration security issues you might face. You should encrypt your data before sending it.

Is there any way to use the JQuery GetJSON method to get HTML from an external page?

So let's say you're trying to do a jquery ajax request, something like:
$.ajax({
...
url: http://other-website.com
...
})
I understand that because of the same-origin principle, this request will fail because the URL is an external domain.
However I've heard that GetJSON() does not obey this principle and can send asynchronous get requests to external servers using JSONP and an appended URL.
My question is: is it possible to use GetJSON() to retrieve all the HTML from an external name as a single string within a JSON object? If it doesn't do so by default, is there any way I can force / trick it into doing so?
Yes, you can request html from a remote location, however you must use a proxy to do so. One publicly available proxy is YQL.
http://jsfiddle.net/BKJWu/
var query = 'SELECT * FROM html WHERE url="http://mattgemmell.com/2008/12/08/what-have-you-tried/" and xpath="//h1" and class="entry-title"';
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=??";
$.getJSON(url,function(data){
alert(data.query.results.h1.content);
})
You could of course build your own on your server that returns plain html rather than json.
The answer is no, you cannot trick it or force it to load html from an external source. GetJSON only works on servers that serve JSONP, and only valid JSON objects are able to be read.
You can retrieve any JSON object that you have access to with GetJSON. Here is an example with Razor an MVC Controller.
jQuery Code
$(function () {
$.getJSON('#Url.Action("GetColorsJson", "Json")', function (jsonData) {
var css = new customContentJs.css.apply(jsonData);
});
});
Controller Code
using System.Web.Mvc;
using DAL;
using Newtonsoft.Json;
public class JsonController : Controller
{
private readonly CustomContentContext _db = new CustomContentContext();
/// <summary>
/// Return a json serialized object of user saved colors
/// </summary>
/// <returns></returns>
public string GetColorsJson()
{
return JsonConvert.SerializeObject(_db.Site.Include("Colors"));
}
}

Accessing .json file to get bank holidays access denied

I am very new to jQuery and json. I am trying to get UK Bank Holiday data from the following API/link so that I can create a function which determines if a selected date is a working day.
https://www.gov.uk/bank-holidays.json
I had an error for No Transport which I fixed by putting in:
jQuery.support.cors = true;
I am now getting Access Denied. I have no idea how to gain access to this because as I say, I am still learning all this.
function IsWorkingDay(date) {
var day = new moment(value, "DD-MM-YYYY").day();
jQuery.support.cors = true;
var bankHolidays = $.getJSON("https://www.gov.uk/bank-holidays.json").done(function(data) {
alert(data);
})
.fail(function(a, b, c) {
alert(b + ',' + c);
return day != 0 && day != 6;
}
});
My question is in two phases:
How do I get access? (Main question)
How do I move on to access the data? I have downloaded the json onto my computer to look at, just how I am going to go about translating this to javascript is what I am struggling on.
If you are blocked by CORS, and the service doesn't support JSONP, the easiest way to solve it is to create a proxy service for the actual service. So if you create a service on your server (which is the same that is serving the javascript), you can call that service, which in turn will fetch the data from the external service. On the server side, there is no CORS to worry about.
I don't know what your backend is, but the steps are as follows:
Create a service on your side that is exposed with a URL (e.g. /myapp/workingday)
Call this service instead of the real service
Your proxy service will get the JSON data and return it to the javascript
Edit
I don't know MVC4, but I suspect it's some of the same concepts as Spring MVC, so here's a Java example:
#Controller
public class HolidaysController {
#RequestMapping("/workingday")
public void isworkingDay(#RequestParam("day") Date day, HttpServletResponse response) {
// Call external service and get JSON
String json = callExternalService(day);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
And in your javascript:
function IsWorkingDay(date) {
var day = new moment(value, "DD-MM-YYYY").day();
var bankHolidays = $.getJSON("/workingday").done(function(data) {
// process data
});
}
For this to work you need to use jsonp as illustrated here
BUT
running the above code throw an invalid label exception which as explained here and as #NilsH suggests is due to the server blocking it

How to use MS Ajax PageMethods to call a function on the server

I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured
"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."
Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:
function OnRequestComplete(result,
userContext, methodName) {
var Person = eval('(' + result + ')');
alert(Person.Forename);
alert(Person.Surname); }
So is the first technique is correct? or what?
P.S:
the function on the server is defined on the default.aspx.cs file as follows:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] Foo(string s);
from the client side the calling is as follows
PageMethods.Foo("value",OnSuccess);
Also all the users have the same browser version (IE8)
I don't know if it's the entire problem, but your first issue is manually serializing the return value. PageMethods and ScriptServices automatically JSON serialize their return values. Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).
To return an instance of your Person class, this is all you need:
public static Person GetPerson() {
Person p = new Person();
// Populate the Person object here.
return p;
}
Then, on the client-side you can work with the object's properties as expected:
function OnRequestComplete(result, userContext, methodName) {
console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}
Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods. You can directly call page methods with jQuery and skip all that overhead.
Without knowing how the request is made and how the server end is coded, my answer may not be accurate.
Where is the WebMethod decorated method in your server side code? If it is an a separate class with the ScriptService attribute, and if JSON is specified while making the request, then the JSON values should have been automatically serialized and dont need to be serialized manually again. With this set up ASP.NET 3.5 wraps the response in a "d" object
Some users getting the exception might be due to the browser that they are using. If you are using jQuery, I'd specify the content type as so in the ajax request body
contentType: "application/json; charset=utf-8",
Hakeem
This is a bit funky. ASP.NET always adds the "d" to all results. So it either should work or not. Here is some background on the "d" issue:
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/

Categories