I am semi-new to ASP.NET MVC. I am building an app that is used internally for my company.
The scenario is this: There are two Html.Listbox's. One has all database information, and the other is initally empty. The user would add items from the database listbox to the empty listbox.
Every time the user adds a command, I call a js function that calls an ActionResult "AddCommand" in my EditController. In the controller, the selected items that are added are saved to another database table.
Here is the code (this gets called every time an item is added):
function Add(listbox) {
...
//skipping initializing code for berevity
var url = "/Edit/AddCommand/" + cmd;
$.post(url);
}
So the problem occurs when the 'cmd' is an item that has a '/', ':', '%', '?', etc (some kind of special character)
So what I'm wondering is, what's the best way to escape these characters? Right now I'm checking the database's listbox item's text, and rebuilding the string, then in the Controller, I'm taking that built string and turning it back into its original state.
So for example, if the item they are adding is 'Cats/Dogs', I am posting 'Cats[SLASH]Dogs' to the controller, and in the controller changing it back to 'Cats/Dogs'.
Obviously this is a horrible hack, so I must be missing something. Any help would be greatly appreciated.
Why not just take this out of the URI? You're doing a POST, so put it in the form.
If your action is:
public ActionResult AddCommand(string cmd) { // ...
...then you can do:
var url = "/Edit/AddCommand";
var data = { cmd: cmd };
$.post(url, data);
... and everything will "just work" with no separate encoding step.
Have you tried using the 'escape' function, before sending the data? This way, all special characters are encoded in safe characters. On the server-side, you can decode the value.
function Add(listbox) { ...
//skipping initializing code for berevity
var url = "/Edit/AddCommand/" + escape(cmd);
$.post(url);
}
use javascript escaping, it does urlencoding.
Javascript encoding
Then in C# you can simple decode it.
It will look as such
function Add(listbox) { ...
//skipping initializing code for berevity
var url = "/Edit/AddCommand/" + escape(cmd);
$.post(url);
}
Have you tried just wrapping your cmd variable in a call to escape()?
You could pass the details as a query string. At the moment I'm guessing you action looks like:
public virtual ActionResult AddCommand( string id )
you could change it to:
public virtual ActionResult AddCommand( string cmd )
and then in you javascript call:
var url = "/Edit/AddCommand?cmd=" + cmd;
That way you don't need to worry about the encoding.
A better way would be if you could pass the databases item id rather than a string. This would probably be better performance for your db as well.
Related
http://www.biletix.com/search/TURKIYE/en#!subcat_interval:12/12/15TO19/12/15
I want to get data from this website. When i use jsoup, it cant execute because of javascript. Despite all my efforts, still couldnot manage.
enter image description here
As you can see, i only want to get name and url. Then i can go to that url and get begin-end time and location.
I dont want to use headless browsers. Do you know any alternatives?
Sometimes javascript and json based web pages are easier to scrape than plain html ones.
If you inspect carefully the network traffic (for example, with browser developer tools) you'll realize that page is making a GET request that returns a json string with all the data you need. You'll be able to parse that json with any json library.
URL is:
http://www.biletix.com/solr/en/select/?start=0&rows=100&fq=end%3A[2015-12-12T00%3A00%3A00Z%20TO%202015-12-19T00%3A00%3A00Z%2B1DAY]&sort=vote%20desc,start%20asc&&wt=json
You can generate this URL in a similar way you are generating the URL you put in your question.
A fragment of the json you'll get is:
....
"id":"SZ683",
"venuecount":"1",
"category":"ART",
"start":"2015-12-12T18:30:00Z",
"subcategory":"tiyatro$ART",
"name":"The Last Couple to Meet Online",
"venuecode":"BT",
.....
There you can see the name and URL is easily generated using id field (SZ683), for example: http://www.biletix.com/etkinlik/SZ683/TURKIYE/en
------- EDIT -------
Get the json data is more difficult than I initially thought. Server requires a cookie in order to return correct data so we need:
To do a first GET, fetch the cookie and do a second GET for obtain the json data. This is easy using Jsoup.
Then we will parse the response using org.json.
This is a working example:
//Only as example please DON'T use in production code without error control and more robust parsing
//note the smaller change in server will break this code!!
public static void main(String[] args) throws IOException {
//We do a initial GET to retrieve the cookie
Document doc = Jsoup.connect("http://www.biletix.com/").get();
Element body = doc.head();
//needs error control
String script = body.select("script").get(0).html();
//Not the more robust way of doing it ...
Pattern p = Pattern.compile("document\\.cookie\\s*=\\s*'(\\w+)=(.*?);");
Matcher m = p.matcher(script);
m.find();
String cookieName = m.group(1);
String cookieValue = m.group(2);
//I'm supposing url is already built
//removing url last part (json.wrf=jsonp1450136314484) result will be parsed more easily
String url = "http://www.biletix.com/solr/tr/select/?start=0&rows=100&q=subcategory:tiyatro$ART&qt=standard&fq=region:%22ISTANBUL%22&fq=end%3A%5B2015-12-15T00%3A00%3A00Z%20TO%202017-12-15T00%3A00%3A00Z%2B1DAY%5D&sort=start%20asc&&wt=json";
Document document = Jsoup.connect(url)
.cookie(cookieName, cookieValue) //introducing the cookie we will get the corect results
.get();
String bodyText = document.body().text();
//We parse the json and extract the data
JSONObject jsonObject = new JSONObject(bodyText);
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("docs");
for (Object object : jsonArray) {
JSONObject item = (JSONObject) object;
System.out.println("name = " + item.getString("name"));
System.out.println("link = " + "http://www.biletix.com/etkinlik/" + item.getString("id") + "/TURKIYE/en");
//similarly you can fetch more info ...
System.out.println();
}
}
I skipped the URL generation as I suppose you know how to generate it.
I hope all the explanation is clear, english isn't my first language so it is difficult for me to explain myself.
I have created a Web API that will receive Input from Jquery and will use this input to dynamically alter a string that's stored in a resource file.
This String happens to be an almost complete piece of vbscript code that I plan on passing back down to my website.
My problem is that the resource automatically "stringifies" the Code and the output is flooded with escape characters which renders it completly unusable as actual code.
Is there a way to store the code in a way that makes escape strings unneccesary while still enabling me to alter it similiar to "if it were a string" and pass it down to my Website?
The goal is to then use Jquery/Javascript to make this code into an actual vbscript file and let the user download it.
As per request here some Code.
public string GetDeployment(Deployment deployment)
{
string vbs = Resource1.vbs;
vbs = vbs.Replace("%environment%", deployment.SystemKind);
vbs = vbs.Replace("%platform%", deployment.PlatformKind);
vbs = vbs.Replace("%application%", deployment.ApplicationName);
vbs = vbs.Replace("%config", deployment.ConfigInfix ?? "Null");
vbs = vbs.Replace("%subFolder%", deployment.subFolder ?? "Null");
return vbs;
}
This method alters the vbscript depending on the Input. The API itself receives a JSON with Data for all the properties of deployment.
public class DeploymentController : ApiController
{
private DeploymentRepository DeploymentRepository;
public DeploymentController()
{
DeploymentRepository = new DeploymentRepository();
}
[HttpPost]
public string Post([FromBody]Deployment deployment)
{
return DeploymentRepository.GetDeployment(deployment);
}
}
I am trying to notify the browser of the user of a change of the status of the model. I am trying to use the live-module of Rails for that. Here is what I have got so far:
require 'json'
class Admin::NotificationsController < ActionController::Base
include ActionController::Live
def index
puts "sending message"
videos = Video.all
response.headers['Content-Type'] = 'text/event-stream'
begin
if(params[:id].present?)
response.stream.write(sse({id: params[:id]},{event: "video_encoded"}))
end
rescue IOError
ensure
response.stream.close
end
end
private
def sse(object, options = {})
(options.map{|k,v| "#{k}: #{v}" } << "data: #{JSON.dump object}").join("\n") + "\n\n"
end
end
The idea behind the above controller is, that when its url gets called with a parameter, it would send this parameter (in this case the id) to the user. Here is how I am trying to call the controller:
notifications_path(id: video.id)
Unfortunately though, the following event-listener in the browser does not fire, even if I use curl to provoke an event:
var source = new EventSource('/notifications');
source.addEventListener("video_encoded", function(event) {
console.log("message")
console.log(event)
});
The goal of this is, that I want to add an dom-element to a certain page (later on) if there is a change. There may be a better way, but Ruby Live seemed like a suitable solution. Any tips or proposals of a different approach are appreciated.
Your use case does not seem like a valid use case for ActionController::Live. You are not sending a streaming output to the browser. You do a one time check on ID and send the JSON output.
Use a regular controller and get the request by AJAX instead of EventSource.
Having issues with Jade and the way the data is passed to it when it is rendered.
I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}];
format but having issues as it shows up as the result below.
Result
key: xyz value:[{"artist":"Lady Gaga",...
This is the code I am working with on the server-side Node.js which is passing it fine ...
res.render('musics', {
title: 'site',
result: JSON.stringify(result)
});
This is the code I am having issues with because of the way I have to call result in jade...
script
function local (arr) {
var i;
i = "#{result}";
localStorage.setItem('xyz', i);
}
console.log('stored');
local();
The quotes around result are messing it up but without them I get an error for unexpected identifier...
Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.
your jade snippet should look like this then:
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"
by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.
As an improvement to #greelgork's answer:
This is for JSON array
script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"
Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, #greelgorke's answer should be modified so:
single item
script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"
So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx
Credit Push JSON Objects to array in localStorage
if usersList.length
script.
const userList = !{JSON.stringify(usersList)}
localStorage.setItem('xyz',JSON.stringify(userList))
const loader = document.querySelector(".loader");
loader.className +=" hidden";
I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks