cefsharp ExecuteScriptAsync(json) uri too long - javascript

I am using cefSharp in my winForm application.
I want to pass a long json from my winform to the html page displayed by the cefSharp.
I tried to write the following:
Private WithEvents m_chromeBrowser As ChromiumWebBrowser
...
CefSharp.Cef.Initialize()
page = New Uri("www...")
m_chromeBrowser = New ChromiumWebBrowser(page.ToString)
Panel.Controls.Add(m_chromeBrowser)
...
Dim json as String = "[{code:1,name:a,val:0},{...}....]"
m_chromeBrowser.ExecuteScriptAsync("functionName('" & json & "');")
But I keep getting the following error:
Request-URI Too Long
Do you have any idea how to pass long json from winform to browser.
Thanks

Well, you would be better off exposing a .Net class to JavaScript by registering an AsyncJSObject, execute the class method from JavaScript and parse the return result.
Something like this:
public class CallbackObjectForJs {
public string getJson() {
return myJsonString;
}
}
... then register the class:
_webBrowser.RegisterAsyncJsObject(
"Browser",
new CallbackObjectForJs(),
BindingOptions.DefaultBinder);
... and finally call the method from Javascript and use a promise to get the result:
Browser.getJson().then((result) => {
var myJsonString = JSON.parse(result);
console.log(myJsonString);
});
You can read more about it here:
https://github.com/cefsharp/CefSharp/wiki/General-Usage#3-how-do-you-expose-a-net-class-to-javascript
Hope it helps!

Related

Access RESX file from external javascript file [duplicate]

How would one get resx resource strings into javascript code stored in a .js file?
If your javascript is in a script block in the markup, you can use this syntax:
<%$Resources:Resource, FieldName %>
and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.
I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.
One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?
Or does anyone have any other suggestions?
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.
using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript(string resxFileName)
{
var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
return JavaScript(javaScript);
}
}
// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
So I can do
<script src="/resources/Foo.js"></script>
and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.
There's no native support for this.
I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:
http://www.west-wind.com/Weblog/posts/698097.aspx
I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes.
Partial Javascript...:
messages:
{
<%=txtRequiredField.UniqueID %>:{
required: "<%=Resources.Common.Msg1 %>",
maxlength: "Only 50 character allowed in required field."
}
}
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to:
1) Clear out all the ASP.NET stuff and make it look like a JS file.
2) Set the content-type to "text/javascript" in the codebehind.
Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
If you have your resources in a separate assembly you can use the ResourceSet instead of the filename. Building on #Domenics great answer:
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript()
{
// This avoids the file path dependency.
ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// Create dictionary.
var resourceDictionary = resourceSet
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json);
return JavaScript(javaScript);
}
}
The downside is that this will not enable more than one resource-file per action. In that way #Domenics answer is more generic and reusable.
You may also consider using OutputCache, since the resource won't change a lot between requests.
[OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetResourcesJavaScript()
{
// Logic here...
}
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.
use a hidden field to hold the resource string value and then access the field value in javascript
for example :
" />
var todayString= $("input[name=TodayString][type=hidden]").val();
Add the function in the BasePage class:
protected string GetLanguageText(string _key)
{
System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
return _resourceTemp.GetString(_key);
}
Javascript:
var _resurceValue = "<%=GetLanguageText("UserName")%>";
or direct use:
var _resurceValue = "<%= Resources.Language.UserName %>";
Note:
The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

Spring Boot and html not rendering javascript

I am trying to cache some results of a js script. (note this is working for other things like raw string data returned from a service, just not for this. Also note this is the first time I am trying to do it with a script and .js file.
Working:
in html:
<script src="https://www.notmydomain.com/script.js?param1=blah"></script>
not working:
in html:
<script src="/script.js?param1=blah"></script>
in #RestConroller method (from System.out.println's I know its returning the exact same thing as when I call the script directly):
#GetMapping("/script.js")
public String script(Model model, #RequestParam Map<String,String> allRequestParams) {
String parameters = inputParameterBuilder.buildParametersString(allRequestParams);
String js = pagesCacheService.getPage("script.js"+parameters, null, String.class);
if(null == js) {
js = resttemplate.getForObject("https://www.notmydomain.com/script.js" + parameters, String.class);
pagesCacheService.updatePage("script.js"+parameters, js, String.class);
}
return js;
}
Thanks,
Brian
Solved the issue: #GetMapping(value = "/script.js",produces = "text/javascript")

What type of object does DotNet.invokeMethod pass in c# method?

I'm using Blazor(3.0.0-preview4) and trying to pass an object from javascript through DotNet.invokeMethod. I tested this way and it succesfully passes simple types (strings, int). But if i pass JS object, i get weird object type
I can write it to Console.WriteLine, it looks like JSON, but not string.
So i cant make anything with this, i can't even parse it and there is no information about SimpleJson assembly from Microsoft. How can i deal with this type?
Thanks in advance.
Code example
Blazor:
[JSInvokable]
public static void SetPlayerState(object[] args)
{
Console.WriteLine(args[0]);
Console.WriteLine(args[0].GetType().Name);
}
JS:
window.cInvoke = (methodName, json) => {
DotNet.invokeMethod("ui", methodName, JSON.parse(json));
};
The DotNet.InvokeMethod will send a JSON string as you see in your WASM console log to your JSInvokable method in the Blazor .razor page.
To deserialize it in the blazor page use
[JSInvokable]
public static void SetPlayerState(string msg)
{
var deserialized = Microsoft.JSInterop.Json.Deserialize<myobject>(msg);
}
I found that blazor uses this library
Thanks to this answer
Related issue

How to get JSON file from server? (ASP.NET)

I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}
The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json
You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.
In my client side JQuery I have:
$.post("test.aspx/testMethod",
{
name: "Donald Duck",
city: "Duckburg"
}
);
In my server side (test.aspx.cs) method, I have
public void testMethod()
{
string name = Request.Form("name");
string city = Request.Form("city");
}
But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."
How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.
There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
you can use like this - https://rvieiraweb.wordpress.com/2013/01/21/consuming-webservice-net-json-using-jquery/
try it :)
I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?
I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.
Please let me know if any further details needed.
Found Solution... (Hope someone finds it useful)
JAVA SCRIPT
function myFunction() {
var str= "fname=Henry&lname=Ford";
log("MyString=" + str);
}
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "Default.aspx", true); // Default.aspx being the page being posted to
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(message);
}
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
string code = HttpContext.Current.Request.Form["MyString"];
// code = "fname=Henry"
// For looping etc, see below
}
}
WHAT ELSE YOU CAN GET....
HttpContext.Current.Request.Form.Count // 2
HttpContext.Current.Request.Form.Keys.Count // 2
HttpContext.Current.Request.Form.AllKeys[0] // "MyString"
HttpContext.Current.Request.Form.Keys[0] // "MyString"
HttpContext.Current.Request.Form.AllKeys[1] // "lname"
HttpContext.Current.Request.Form.Keys[1] // "lname"
HttpContext.Current.Request.Form[0] // "fname=Henry"
HttpContext.Current.Request.Form[1] // "Ford"
Loop through keys...
foreach (string key in Request.Form.Keys)
{
DoSomething(Request.Form[key]);
}
The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.
The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
// Reset staticValue
Class1.staticValue = "";
Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
// Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"
}
}
STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)
public class Class1
{
private static string myValue = "";
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public static string staticValue
{
get
{
return myValue;
}
set
{
myValue = value;
}
}
}

Categories

Resources