Passing values to HTML File STORED in Asset Folder in Android - javascript

I was trying to pass the parameters to HTML file stored in android Asset Folder. I was passing the parameters to the function written in java script on my HTML file. But at certain times, I'm getting Exception, which I find difficult to sort out the issue.
Exception::
`I/chromium: [INFO:CONSOLE(1)] "Uncaught SyntaxError: missing ) after argument list", source: file:///android_asset/templateOffer.html (1)`.
Java script Code in HTML file:
function setWineDetails(tempOffer,wineBrnd,wineName,
wineCurrency,winePrice,placeLineOne,PlaceLineTwo,userName,wineMtchVal){
document.getElementById("usrname").innerHTML = userName;
document.getElementById("wineTpe").innerHTML = tempOffer;
document.getElementById("wine_brnd_id").innerHTML = wineBrnd;
document.getElementById("wine_name_id").innerHTML = wineName;
document.getElementById("wine_currcy_id").innerHTML = wineCurrency;
document.getElementById("wine_price_id").innerHTML = winePrice;
if (placeLineOne != = "" || placeLineOne != = null) {
document.getElementById("place_line_one_id").innerHTML = placeLineOne;
document.getElementById("place_line_second_id").innerHTML = PlaceLineTwo;
}
if (wineMtchVal == "" || wineMtchVal == null) {
document.getElementById("wine-percentages").style.visibility = 'hidden';
} else {
document.getElementById("wine-percentages").style.visibility = 'visible';
document.getElementById("wineMtch_id").innerHTML = wineMtchVal;
}
}
function setImage(wineImage){
document.getElementById("wineImage_id").src = wineImage;
}
function setValuesToOfferView(offerPercentage,offerExpiry){
document.getElementById("offer_per_id").innerHTML = offerPercentage;
document.getElementById("offer_expiry_id").innerHTML = offerExpiry;
}
passing parameteres::
private void loadWebViewContent(){
offerWebView.getSettings().setJavaScriptEnabled(true);
offerWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
//Here you want to use .loadUrl again
//on the webview object and pass in
//"javascript:<your javaScript function"
offerWebView.loadUrl("javascript:setWineDetails('"+offerTemp+"','"+wineBrand+"','"+wineName+"','"+wineCurrency+"','"+winePrice+"','"+placeLineOne+"','"+PlaceLineTwo+"','"+userName+"','"+wineMatch+"')");
offerWebView.loadUrl("javascript:setValuesToOfferView('"+offerPercentage+"','"+offerExpiry+"')"); //if passing in an object. Mapping may need to take place
offerWebView.loadUrl("javascript:setImage('"+wineImage+"')"); //if passing in an object. Mapping may need to take place
}
});
offerWebView.loadUrl("file:///android_asset/templateOffer.html");
}

Related

Execute Javascript on external url using HybridView, Xamarin cross platform

I have tried to execute JavaScript on an external url (ie: http://facebook.com) using WebView from Visual Studio Mac 2019, and so far no results.
To do so, I have tried to follow along with the official tutorial here https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview, and also tried a simpler one here: https://xamarinhelp.com/xamarin-forms-webview-executing-javascript/
Here is what I did with explanations:
On my shared folder, I created an HybridWebView class with the following code:
public class HybridWebView : WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(Func<string, Task<string>>),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get => (string)GetValue(UriProperty);
set
{
SetValue(UriProperty, value);
}
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
public Func<string, Task<string>> ExecuteJavascript
{
get { return (Func<string, Task<string>>)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
From The macOS project which I use to test my cross-platform app, I tried the following custom renderer:
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged(e);
var webView = e.NewElement as HybridWebView;
if (webView != null)
{
Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.ExecuteJavascript.ToString())));
}
}
}
To note that the following part wouldn't work:
var webView = e.NewElement as HybridWebView;
if (webView != null)
webView.ExecuteJavascript = (js) =>
{
return Task.FromResult(this.ExecuteJavascript(js)); // issue at ExecuteJavascript with following error ('HybridWebViewRenderer' does not contain a definition for 'ExecuteJavascript' ), hence replaced by Control.LoadRequest ...
};
From my ViewModel, I did the following:
public Func<string, Task<string>> EvaluateJavascript { get; set; }
public async Task OnConnectTapped()
{
Console.WriteLine("on connect tapped");
// passing the url onto a connection service
var hybridWebView = new HybridWebView
{
Uri = "https://facebook.com/"
};
//hybridWebView.InvokeAction("document.getElementById('td');");
//var result = await hybridWebView.RegisterAction(data => DisplayAlert("Alert", "Hello " + data, "OK"));
var result = await hybridWebView.ExecuteJavascript("document.cookie;");
Console.WriteLine("result is {0}", result);
}
Here is the error when trying to execute my code:
System.NullReferenceException: Object reference not set to an instance of an object
at MyApp.ViewModel.MainModel.OnConnectTapped () [0x00031] in .../../././/ViewModel/MainModel.cs:451
at .......<.ctor>g__c5|48_9 () [0x0001f] in /../../../.cs:143
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/external/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00002] in /Library/Frameworks/Xamarin.Mac.framework/Versions/6.6.0.12/src/Xamarin.Mac/Foundation/NSAction.cs:178
at at (wrapper managed-to-native) AppKit.NSApplication.NSApplicationMain(int,string[])
at AppKit.NSApplication.Main (System.String[] args) [0x00040] in /Library/Frameworks/Xamarin.Mac.framework/Versions/6.6.0.12/src/Xamarin.Mac/AppKit/NSApplication.cs:100
at redacted.macOS.MainClass.Main (System.String[] args) [0x00017] in /Users/dom-bruise/Projects/redacted/redacted.macOS/Main.cs:11
For me, it could either be because I can't execute external pages, or the part where I replaced by the following messing up my attempt.
if (webView != null)
{
Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.ExecuteJavascript.ToString())));
}
My main goal here is to have my app execute JavaScript underneath the hood on pages using WebView, and fill in forms automatically calling back C# from my app.

ReportViewer 15.0.0 Renerding: Sys.ArgumentNullException: Value cannot be null. Parameter name: element

I have the following issue with rendering a report(with a certain set of parameters) using MS ReportViewer. The JS invoked from the internal ReportViewer JS code is failing, specifically this section of "ScriptResource.axd":
var $addHandlers = Sys.UI.DomEvent.addHandlers = function Sys$UI$DomEvent$addHandlers(element, events, handlerOwner, autoRemove) {
/// <summary locid="M:J#Sys.UI.DomEvent.addHandlers" />
/// <param name="element"></param>
/// <param name="events" type="Object"></param>
/// <param name="handlerOwner" optional="true"></param>
/// <param name="autoRemove" type="Boolean" optional="true"></param>
var e = Function._validateParams(arguments, [
{name: "element"},
{name: "events", type: Object},
{name: "handlerOwner", optional: true},
{name: "autoRemove", type: Boolean, optional: true}
]);
if (e) throw e;
Sys.UI.DomEvent._ensureDomNode(element);
for (var name in events) {
var handler = events[name];
if (typeof(handler) !== 'function') throw Error.invalidOperation(Sys.Res.cantAddNonFunctionhandler);
if (handlerOwner) {
handler = Function.createDelegate(handlerOwner, handler);
}
$addHandler(element, name, handler, autoRemove || false);
}
}
The "Sys.UI.DomEvent._ensureDomNode(element);" line is failing with the following error:
Sys.ArgumentNullException: Value cannot be null. Parameter name:
element
When I look up the stack trace:
It appears that the source of this issue is from JS called from the main "Report" page:
Sys.Application.add_init(function() {
$create(Microsoft.Reporting.WebFormsClient._Splitter, {"HoverStyle":"SplitterHover","ImageCollapse":"/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=15.0.900.148\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapse.png","ImageCollapseHover":"/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=15.0.900.148\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapseHover.png","ImageExpand":"/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=15.0.900.148\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizExpand.png","ImageExpandHover":"/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=15.0.900.148\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizExpandHover.png","ImageId":"ctl00_ApplicationBody_rvReport_ToggleParam_img","IsCollapsable":true,"NormalStyle":"SplitterNormal","Resizable":false,"StoreCollapseField":"ctl00_ApplicationBody_rvReport_ToggleParam_collapse","StorePositionField":"ctl00_ApplicationBody_rvReport_ToggleParam_store","TooltipCollapse":"Hide Parameters","TooltipExpand":"Show Parameters","Vertical":false}, null, null, $get("ctl00_ApplicationBody_rvReport_ToggleParam"));
});
This is breaking the rendered report. I'm not sure how to track this down any further, I know that you can get the report to format with different parameters, but I don't understand how one can debug minified JS internal to the ReportViewer library.
Is this JS failure a known issue with certain reports? I am running the latest version of the library(15.0.0). I would post both the report and parameters, however they contain sensitive information. How does one debug issues internal to the ReportViewer library to solve issues such as this one?
Very Tricky, I had a C# method running in the MasterPage disabling certain types of control so that the user could not "Edit" the page, looked something like this:
//CommonFunctions
public static List<T> GetAllControlsRecursiveByType<T>(ControlCollection Controls) where T : Control
{
List<T> results = new List<T>();
foreach (Control c in Controls)
{
if (c is T)
{
results.Add((T)c);
}
if (c.HasControls())
{
results.AddRange(GetAllControlsRecursiveByType<T>(c.Controls));
}
}
return results;
}
public void DisableControls(Control control)
{
if (control == null)
{
return;
}
DisableControl(control);
foreach (System.Web.UI.Control c in control.Controls)
{
DisableControl(c);
// Recurse into child controls.
if (c.Controls.Count > 0)
{
DisableControls(c);
}
}
}
foreach (Control element in CommonFunctions.GetAllControlsRecursiveByType<Control>(FindControl("ApplicationBody").Controls))
{
List<string> excludedIDs = new List<string>() { "btnAjaxDynamicFilterApplyFilter", "btnClose", "btnCancel", "btnExport" };
List<Type> includedTypes = new List<Type>() { typeof(LinkButton), typeof(Button), typeof(ImageButton), typeof(Repeater), typeof(ABC.Controls.ABCRepeater),
typeof(GridView), typeof(ABC.Controls.ABCGridView), typeof(ABC.Controls.ImageCheckBox) };
if (!excludedIDs.Contains(element.ID) && includedTypes.Contains(element.GetType()))
{
DisableControls(element);
}
}
Turns out this was "Disabling" certain rendered controls within the report viewer, this was in turn breaking the JS in the front end. I fixed this by excluding the "ReportViewer" from this logic:
public bool ControlHasParentWithType(Control control, Type type)
{
if (control == null || control.Parent == null)
{
return false;
}
else if (control.Parent.GetType() == type)
{
return true;
}
return ControlHasParentWithType(control.Parent, type);
}
//Within Method before disabling the control
if (ControlHasParentWithType(element, typeof(ReportViewer)))
{
continue;
}

Getting Script on Top of the page so getting error like $ not define

i am use asp.net core code for popup and append html and js file in main view but i get error like $ not found if anyone know how to solve please help
My ActionFilter Code:-
private readonly IStoreContext _storeContext;
private readonly ISettingService _settingService;
private readonly ILogger _logger;
private readonly ILocalizationService _localizationService;
private readonly IWorkContext _workContext;
private readonly ITopicService _topicService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
#endregion
#region const
public PopupEngageFilterAttribute()
{
this._storeContext = EngineContext.Current.Resolve<IStoreContext>();
this._settingService = EngineContext.Current.Resolve<ISettingService>();
this._logger = EngineContext.Current.Resolve<ILogger>();
this._localizationService = EngineContext.Current.Resolve<ILocalizationService>();
this._workContext = EngineContext.Current.Resolve<IWorkContext>();
this._topicService = EngineContext.Current.Resolve<ITopicService>();
this._newsLetterSubscriptionService = EngineContext.Current.Resolve<INewsLetterSubscriptionService>();
}
#endregion
#region methods
public void PopupEngageOnResultExecuted(ActionExecutedContext filterContext)
{
var storeId = _storeContext.CurrentStore.Id;
LicenseImplementer licenseImplementer = new LicenseImplementer();
// load plugin settings
var _setting = _settingService.LoadSetting<PopupEngageSetting>(storeId);
var allStoreSettings = _settingService.LoadSetting<PopupEngageSetting>(0);
//check plugin is enabled or not
if (_setting.PopupEngageEnabled)
{
// check license
//if (!licenseImplementer.IsLicenseActive(allStoreSettings.LicenseKey, allStoreSettings.OtherLicenseSettings))
// return;
StringBuilder sb = new StringBuilder();
string bioepEngageScript = string.Empty;
string popupEngageView = string.Empty;
string popupEngageScript = string.Empty;
string newsLetterScript = string.Empty;
// get current customer
var customer = _workContext.CurrentCustomer;
// check customer cart
string customerCart = Convert.ToString(customer.HasShoppingCartItems);
// set cookie for customer cart
filterContext.HttpContext.Response.Cookies.Append("CustomerCart", customerCart, new CookieOptions() { Path = "/", HttpOnly = false, Secure = false });
if(customerCart == "True")
{
// get bioep script file
Stream bioepScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.bioep.min.js");
if (bioepScriptFile != null)
using (StreamReader reader = new StreamReader(bioepScriptFile))
{
bioepEngageScript = reader.ReadToEnd();
}
// get PopupEngage script
string path = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Script"), "PopupEngage.js");
if (File.Exists(path))
{
popupEngageScript = File.ReadAllText(path);
}
// check current customers role
var customerRole = customer.CustomerRoles.Where(x => x.Name == "Guests").FirstOrDefault();
if (customerRole != null)
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngageNewsLetter.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
// get NewsLetter Script file
Stream newsLetterScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.NewsLetter.js");
if (newsLetterScriptFile != null)
using (StreamReader reader = new StreamReader(newsLetterScriptFile))
{
newsLetterScript = reader.ReadToEnd();
}
}
else
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngage.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
}
var topicBody=string.Empty;
// get topic from settings
var topic = _setting.TopicName;
if (!string.IsNullOrEmpty(topic))
{
// get topic by system name
var topicRecord = _topicService.GetTopicBySystemName(topic);
if(topicRecord != null)
{
topicBody = topicRecord.Body;
}
}
// replace new line with slash and double coute with single coute
popupEngageView = popupEngageView.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
topicBody = topicBody.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
// append script
sb.Append("<script type=\"text/javascript\" src=\"/wwwroot/lib/jquery-1.10.2.min.js\">\n\t");
sb.Append(bioepEngageScript);
sb.Append(popupEngageScript);
sb.Append("$(\"" + popupEngageView + "\").insertAfter(\".newsletter\");");
sb.Append("$('.popupengage_popupmsg').html(\"" + topicBody + "\");");
sb.Append(newsLetterScript);
sb.Append("</script>\n");
var bytes = Encoding.ASCII.GetBytes(sb.ToString());
filterContext.HttpContext.Response.Body.WriteAsync(bytes,0, bytes.Length);
}
}
}
#endregion
file append in perfect way but it append script in top of the page before jquery. and that script append by string builder.Popup js example
if u are using jquery, make sure it is included before the script files that use jquery functionality;
For ex: if u have a js file named 'main.js' which has includes a line like $().forEach then your order of inclusion in the html file should be
<script>jquery.js </scrpt>
<script>main.js </scrpt>

Javascript receiving Resource object containing chars instead of String

My Java code should return user login as a String, but on Javascript side I'm receiving a strange Resource object whose numbered attributes each contains one char.
Here is my Java code:
#PostMapping(path = "/account/reset_password/finish", produces = MediaType.TEXT_PLAIN_VALUE)
#Timed
public ResponseEntity<String> finishPasswordReset(#RequestBody KeyAndPasswordVM keyAndPassword) {
if (!checkPasswordLength(keyAndPassword.getNewPassword())) {
return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST);
}
return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()).map(
user -> new ResponseEntity<String>(user.getLogin(), HttpStatus.OK)).orElse(
new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}
Javascript controller code:
Auth.resetPasswordFinish({key: $stateParams.key, newPassword: vm.resetAccount.password}).then(function (userLogin) {
vm.success = 'OK';
console.log("userLogin="+userLogin);
}).catch(function () {
vm.success = null;
vm.error = 'ERROR';
});
The console prints:
userLogin=[object Object]
which is not very interesting.
Inspecting the received object gives:
One can see that each char of the String is a numbered attribute of the Resource object.
Javascript Auth code:
function resetPasswordFinish (keyAndPassword, callback) {
var cb = callback || angular.noop;
return PasswordResetFinish.save(keyAndPassword, function (userLogin) {
return cb(userLogin);
}, function (err) {
return cb(err);
}).$promise;
}
This one is just passing the parameter to the callback function.
Do you know how to receive a plain String instead of this Resource object? I apologize if this is a trivial question.
I know that doing this will work in order to retrieve the user login:
var i = 0;
var userLoginToString = "";
while (typeof userLogin[String(i)] !== 'undefined') {
userLoginToString += String(userLogin[String(i)]);
i += 1;
}
however I don't think that this is the intended way to use this Resource object.

.NET AJAX asynchronous calls

I've been tasked with including asynchronous calls to my webpage and I'm not sure where to start. Currently, my webpage takes user input from a drop down list, converts it into a list of CodeDesc objects, serializes it all into JSON and then deserializes it back so it can be displayed in a GridView on the screen. (I could just make it spit out the CodeDesc object back to the GridView but this is the way my manager wanted it so..).
In any case, now I need the results to be displayed without reloading the page and after some research I read that AJAX was a good way to do it. Unfortunately, I'm confused how I can connect it all and actually use it. My attempts are below but I could really use some guidance on the matter.
HTML (partial):
<script>
$("#Button1").on("click", function () {
$.ajax({
type: ??'GET'??,
contentType: ??
success: function (?? Call deserializeJSONResults function ??) {
$('#GridView2').html("");
for (var i = 0; i < deserializedProduct.length; i++) {
$("#GridView2").append(deserializedProduct.id, deserializedProduct.code, deserializedProduct.);
}
}
});
});</script>
Without using AJAX my code is below:
CS:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.deserializeJSONResults(DropDownList1.SelectedValue);
GridView2.DataBind();
}
Backend:
//Return results to GridView2 as list of CodeDesc objects
public List<CodeDesc> getQueryResults(string searchTerm)
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, code, descr from code_desc where code_type_id = (select id from code_desc where descr = :searchTerm)";
// Create the OracleCommand
using (OracleCommand cmd = new OracleCommand(query, con))
{
cmd.Parameters.Add(new OracleParameter("searchTerm", searchTerm));
con.Open();
// Execute command, create OracleDataReader object
using (OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc
{
id = reader.GetInt32(0),
code = reader.GetString(1),
description = reader.GetString(2)
};
L.Add(c);
}
}
}
return L;
}
//catch clause here
}
//Convert to JSON and parse
public List<CodeDesc> deserializeJSONResults(string searchTerm)
{
List<CodeDesc> L = getQueryResults(searchTerm);
string json = JsonConvert.SerializeObject(L, Formatting.Indented);
//deserialize object
List<CodeDesc> deserializedProduct = JsonConvert.DeserializeObject<List<CodeDesc>>(json);
return deserializedProduct;
}
}
Any help would be appreciated. I have little development experience and this is my first time with web/.NET development

Categories