I'm currently stuck at a problem and was hoping someone here could help me. I also certainly hope this is the right place to ask it.
I'm trying to create a custom Invoice record with its corresponding Invoice Line records upon firing an event. I already have some logic in place to gather ID of selected rows in the JS.
I've gone so far as to be able to create the Invoice record (using LDS) and the Invoice Line records (using Apex), but can't seem to pass the Invoice ID for the Invoice Line records. I know I'm able to create the records because it works when I tested this with a hardcoded Invoice ID.
Would it be possible to pass multiple parameters of List and String to an Apex method in LWC?
I would appreciate any help. Thanks in advance!
JS
selectedRowsEvent(event) {
...some codes here...
this.selectedRecords = Array.from(conIds);
}
handleSave() {
**invId;**
...some codes here...
createRecord(recordInput)
.then(invoice => {
**this.invId = invoice.Id;**
**createInvLines({ lstConIds : this.selectedRecords, invoiceId : this.invId})**
}).catch(error => {
...some codes here...
});
}
Controller
#AuraEnabled
public static void createInvLines(list<Id> lstConIds, string invoiceId){
if(lstConIds.size() > 0){
List<OpportunityLine__c> oppLst = new List<OpportunityLine__c>([SELECT Id, Description__c FROM OpportunityLine__c WHERE Id = :lstConIds]);
try {
List<InvoiceLine__c> lstInvLinesToInsert = new List<InvoiceLine__c>();
for(OpportunityLine__c idCon : oppLst) {
lstInvLinesToInsert.add(new InvoiceLine__c(**InvoiceId__c = invoiceId**, Description__c = idCon.Description__c));
}
if(!lstInvLinesToInsert.isEmpty()) {
insert lstInvLinesToInsert;
}
}
catch(Exception ex) {
throw new AuraHandledException(ex.getMessage());
}
}
}
Yes, you can pass complex parameters to methods marked as #AuraEnabled. On client side it'll be a JSON object with right field names, like you already have { lstConIds : this.selectedRecords, invoiceId : this.invId}. On Apex side it can be a function with multiple arguments or just 1 argument (some helper wrapper class, again with right field names). Salesforce will "unpack" that JSON for you and put into right fields before your code is called.
Your preference which would be cleaner. I tend to use wrappers. If you have a reusable service-like function and you want to add some optional parameters later - you'd simply put new field in wrapper class and job done. Might be not as easy to add a new parameter to function used in other apex code, bit messier.
(in your scenario I'd definitely try to create invoice and line items as 1 call so if anything fails - the normal transaction rollback will help you. if one of items fails - you don't want to be left with just invoice header, right?)
Have you seen https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex ? it's a wall of text but it mentions interesting example, search for "apexImperativeMethodWithParams" in there.
Look at JS file here: https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/apexImperativeMethodWithComplexParams
And see how it calls
ApexTypesController {
#AuraEnabled(cacheable=true)
public static String checkApexTypes(CustomWrapper wrapper) {
...
Where CustomWrapper is
public with sharing class CustomWrapper {
class InnerWrapper {
#AuraEnabled
public Integer someInnerInteger { get; set; }
#AuraEnabled
public String someInnerString { get; set; }
}
#AuraEnabled
public Integer someInteger { get; set; }
#AuraEnabled
public String someString { get; set; }
#AuraEnabled
public List<InnerWrapper> someList { get; set; }
}
The issue is that the inserts are asynchronous and you are firing them synchronously. So, that means you are trying to insert the lines before the parent record has completed.
// CREATE THE INVOICE RECORD
createRecord(recordInput)
.then(invoice => {
**this.invId = invoice.Id;**
// Call the next function here
// CREATE THE INVOICE LINE RECORDS
**createInvLines({ lstConIds : this.selectedRecords, invoiceId : this.invId})**
.then(result => {
...some codes here...
})
.catch(error => {
...some codes here...
});
);
}
I have an ASP.NET Project, where I want to use the FileSystemWatcher. To do that I created an class "Watcher":
public class Watcher
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
Console.WriteLine("FileWatcherStarted");
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = #"C:\\FilesToWatch";
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.EnableRaisingEvents = true;
}
}
private static void OnChanged(object source, FileSystemEventArgs e) =>
Console.WriteLine($"{e.FullPath}, {e.ChangeType}");
}
Then I call this Run method in the IActionResult Index() method in the home controller with:
Watcher.Run();
Now when I want to run or debug my project i get no result from my file watcher. No error occurs. Theres just the message "Thread 0x123 ended with Code 0 (0x0)".
Anyone, who had the same problem or knows the solution?
Why I'm getting this error?
System.InvalidCastException was unhandled by user code
Message=Specified cast is not valid.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
at System.Windows.Forms.WebBrowser.get_Document()
at System.Windows.Forms.WebBrowser.get_DocumentStream()
at System.Windows.Forms.WebBrowser.get_DocumentText()
at SiteBot.MainWindow.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\Documents\Visual Studio 2010\Projects\SiteBot\MainWindow.cs:line 35
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
The following solves your cross thread issue.
public delegate string GetStringHandler();
public string GetDocumentText()
{
if (InvokeRequired)
return Invoke(new GetStringHandler(GetDocumentText)) as string;
else
return webBrowser.DocumentText;
}
if (regAddId.IsMatch(GetDocumentText()))
{
}
I get a threading exception with this test:
public class Test
{
private readonly WebBrowser wb;
public Test()
{
wb = new WebBrowser();
var bw = new BackgroundWorker();
bw.DoWork += DoWork;
bw.RunWorkerAsync();
while (bw.IsBusy)
{
Thread.Sleep(10);
Application.DoEvents();
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
wb.Navigate(#"www.clix-cents.com/pages/clickads");
Thread.Sleep(1000);
var regex = new Regex("onclick=\\'openad\\(\"([\\d\\w]+\"\\);");
regex.IsMatch(wb.DocumentText);
}
}
public class Program
{
[STAThread]
public static void Main(string[] args)
{
new Test();
}
}
The exception looks like this:
Since WebBrowser is really just a wrapper around IE's ActiveX control, you'll need to be careful about threading issues. I think what you really want to use here is a WebClient and not a WebBrowser, but I'm just guessing about your application.
[EDIT]
Like #Fun states you can just Invoke over to the GUI thread (assuming thats where the control was created. I'd still recommend using a WebClient.
I'm having some trouble going through and visualizing how I accomplish pagination over a large dataset with a MySQL database, Java servlets, and using javascript to display the results.
I was working on a personal project with a small dataset to try and learn Java servlets / MySQL / JavaScript. I have a movie database with some movie names and other attributes in MySQL:
CREATE TABLE `movies` (
`id` int(11) NOT NULL AUTO INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '',
`year` int(4) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I then have a Movie java bean:
// Movie bean
import java.io.Serializable;
public class Movie implements Serializable {
// Instance variables
private Long id;
private String title;
private int year;
public Movie() {}
// Setters
public void setId (long id) { this.id = id; }
public void setTitle (String title) { this.title = title; }
public void setYear (int year) { this.year = year; }
// Getters
public long getId() { return id; }
public String getTitle() { return title; }
public int getYear() { return year; }
}
A MovieDAO which accesses the database and retrieves a list of all movies (below is an excerpt, assume I already connect to the database):
public class MovieDAO {
private List<Movie> movies;
private static ResultSet queryMovies(String st) throws SQLException {
ResultSet res = null;
try {
PreparedStatement ps = dbcon.prepareStatement(st);
res = ps.executeQuery();
} catch(SQLException e) {
System.out.println("Error with movieDAO query");
e.printStackTrace();
}
return res;
}
public List<Movie> listMovies() throws SQLException {
movies = new ArrayList<Movie>();
ResultSet res = queryMovies("SELECT * FROM movies");
while(res.next()) {
Movie mov = new Movie();
mov.setId(res.getLong("id"));
mov.setTitle(res.getString("title"));
mov.setYear(res.getInt("year"));
movies.add(mov);
}
return movies;
}
}
And finally my MovieServlet class which just displays all the information as a JSP variable that is a list:
#WebServlet("/movies")
public class MovieServlet extends HttpServlet {
private MovieDAO movieDAO;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
movieDAO = new MovieDAO();
try {
List<Movie> movies = movieDAO.listMovies();
request.setAttribute("movies", movies); // JSP variable: ${movies}
request.getRequestDispatcher("movies.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Could not retrieve movies from the database",e);
}
movieDAO.closeMovieDAO();
}
}
For the front end side of things I have a table which is populated through jsp and javascript. I originally just had a list of page numbers that were generated like so:
function showPageNumber() {
var html = '';
for(i = num_of_pages; i > 0; i--) { html += "<li class='page'><a>" + i + "</a></li>"; }
$('.page').click(function() {
result_min = ($(this).text() - 1) * results_per_page;
result_max = $(this).text() * results_per_page;
show(result_min,result_max);
});
}
function show(min,max) {
var $rows = $('#result_table');
$rows.hide().slice(min, max).show();
}
Inside each row of the table with the id of result_table, I had the jsp variables. I also had a sort function so when the user clicked on each header of the table, it would sort by that header (ie. clicking id would sort by ascending id). This worked great with even a few thousand records of movies and was actually relatively quick.
I then inserted about 80,000 more records into the database. Much to no ones surprise, loading all of that data takes ages. Sorting it takes even longer.
To deal with this, I only want to let the user access a next button, the first ten page number buttons, and a last button which goes to the last page. I figured limiting the number of possible movies helps display the data faster.
My problem is now how can I sort every record and display everything correctly? For example, if the user sorts by id they will get a list of ascending id's like so:
1 - movie1 - 1990
2 - movie2 - 1996
3 - movie3 - 1934
And if they click the same header the order will reverse like so:
3 - movie3 - 1934
2 - movie2 - 1996
1 - movie1 - 1990
But if I limit the amount of data retrieved, but I have a range of id's from 1 - 80,000 , how can I re-sort through all that data and retrieve the id values in reverse order now.. without having to call SELECT again?
I'm starting out with SignalR and I have a situation where I'm going to have a SignalR site that will be broadcasting messages to clients, but I also need an admin interface that will actually trigger those messages. The admin page will call server side methods that will, in turn, call client side Javascript methods for regular users. So I'm thinking I can either set up two separate hubs (one for admin, one for everybody else) or I can have methods in a single hub that can only be called by the admin that will check authorization.
But in addition to the authorization, I'd like to have SignalR not include admin methods or an admin hub in the generated Javascript proxy classes so that I'm not advertising their existence (again - this is NOT the only security, I will be checking authorization). Is there an attribute or property I can set on individual hubs or on methods within a hub that will suppress them from being included in the proxy (but still have them callable from Javascript)? I know you can set EnableJavaScriptProxies to false in your HubConfiguration, but that seems to be global and I'd like to keep the proxy for the stuff I do want the regular client to be using.
There is one trick using interfaces. As proxy will generate only public methods in proxy, you can create hub using interface like this:
public class MyHub : Hub, IMyHub
{
void IMyHub.NotGeneratedOnClient()
{
}
public void GeneratedOnClient()
{
}
}
NotGeneratedOnClient method will not be visible if you use object of type MyHub, you can access it only using interface. As method is not public proxy generator is not going to add it to client proxy
We don't have a way of excluding specific methods from the proxy today. You'd have to re-implement your own proxy generator that basically does what we do in our default impl but has knowledge of some attribute to skip generation of specific methods.
We can conceivable add this in a future version of SignalR. File an issue on github if you feel strongly about having this.
Here's the default implementation (it would have been easier if we made more methods virtual and non static).
https://github.com/SignalR/SignalR/blob/master/src/Microsoft.AspNet.SignalR.Core/Hubs/DefaultJavaScriptProxyGenerator.cs
Here is a modified DefaultJavaScriptProxyGenerator with the following changes:
It will exclude functions from Javascript proxy generation with a new [HubMethodExcludeFromProxy] attribute.
The private static functions have changed to protected virtual for future derivatives.
The GenerateProxy( ) function has an overload to include DocComments, but that was not caching the results like the non DocComments version. Now they both cache.
Two resources, Resources.DynamicComment_CallsMethodOnServerSideDeferredPromise and Resources.DynamicComment_ServerSideTypeIs were private to another assembly, so to get things to compile, I copied the text from the resource file directly. These two resources are only used if DocComments is true.
All of the DefaultJavaScriptProxyGenerator references were changed to CustomJavaScriptProxyGenerator except for one, which is used to locate the resource script Microsoft.AspNet.SignalR.Scripts.hubs.js, located in a different assembly.
First, you will need to update the dependency resolver to use the new CustomJavaScriptProxyGenerator for the IJavaScriptProxyGenerator interface. If you are using the default resolver, you can set up a custom resolver like this:
map.RunSignalR(
new HubConfiguration() {
Resolver = new CustomDependencyResolver()
}
);
And here is a custom resolver that derives from the DefaultDependecyResolver:
namespace Microsoft.AspNet.SignalR
{
public class CustomDependencyResolver : DefaultDependencyResolver
{
MyDependencyResolver() : base()
{
var proxyGenerator = new Lazy(() => new CustomJavaScriptProxyGenerator(this));
Register(typeof(IJavaScriptProxyGenerator), () => proxyGenerator.Value);
}
}
}
And finally, here is the new CustomJavaScriptProxyGenerator.cs file (the HubMethodExcludeFromProxyAttribute class is at the bottom):
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Mods by Brain2000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNet.SignalR.Json;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
namespace Microsoft.AspNet.SignalR.Hubs
{
public class CustomJavaScriptProxyGenerator : IJavaScriptProxyGenerator
{
protected static readonly Lazy _templateFromResource = new Lazy(GetTemplateFromResource);
protected static readonly Type[] _numberTypes = new[] { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(decimal), typeof(double) };
protected static readonly Type[] _dateTypes = new[] { typeof(DateTime), typeof(DateTimeOffset) };
protected const string ScriptResource = "Microsoft.AspNet.SignalR.Scripts.hubs.js";
protected readonly IHubManager _manager;
protected readonly IJavaScriptMinifier _javaScriptMinifier;
protected readonly Lazy _generatedTemplate;
protected readonly Lazy _generatedTemplateWithComments;
public CustomJavaScriptProxyGenerator(IDependencyResolver resolver) :
this(resolver.Resolve(),
resolver.Resolve())
{
}
public CustomJavaScriptProxyGenerator(IHubManager manager, IJavaScriptMinifier javaScriptMinifier)
{
_manager = manager;
_javaScriptMinifier = javaScriptMinifier ?? NullJavaScriptMinifier.Instance;
_generatedTemplate = new Lazy(() => GenerateProxy(_manager, _javaScriptMinifier, includeDocComments: false));
_generatedTemplateWithComments = new Lazy(() => GenerateProxy(_manager, _javaScriptMinifier, includeDocComments: true));
}
public string GenerateProxy(string serviceUrl)
{
serviceUrl = JavaScriptEncode(serviceUrl);
return _generatedTemplate.Value.Replace("{serviceUrl}", serviceUrl);
}
public string GenerateProxy(string serviceUrl, bool includeDocComments)
{
if (!includeDocComments) return GenerateProxy(serviceUrl); //use the includeDocComments: false cached version
serviceUrl = JavaScriptEncode(serviceUrl);
return _generatedTemplateWithComments.Value.Replace("{serviceUrl}", serviceUrl);
}
protected virtual string GenerateProxy(IHubManager hubManager, IJavaScriptMinifier javaScriptMinifier, bool includeDocComments)
{
string script = _templateFromResource.Value;
var hubs = new StringBuilder();
var first = true;
foreach (var descriptor in hubManager.GetHubs().OrderBy(h => h.Name))
{
if (!first)
{
hubs.AppendLine(";");
hubs.AppendLine();
hubs.Append(" ");
}
GenerateType(hubManager, hubs, descriptor, includeDocComments);
first = false;
}
if (hubs.Length > 0)
{
hubs.Append(";");
}
script = script.Replace("/*hubs*/", hubs.ToString());
return javaScriptMinifier.Minify(script);
}
protected virtual void GenerateType(IHubManager hubManager, StringBuilder sb, HubDescriptor descriptor, bool includeDocComments)
{
// Get only actions with minimum number of parameters.
var methods = GetMethods(hubManager, descriptor);
var hubName = GetDescriptorName(descriptor);
sb.AppendFormat(" proxies['{0}'] = this.createHubProxy('{1}'); ", hubName, hubName).AppendLine();
sb.AppendFormat(" proxies['{0}'].client = {{ }};", hubName).AppendLine();
sb.AppendFormat(" proxies['{0}'].server = {{", hubName);
bool first = true;
foreach (var method in methods)
{
if (!first)
{
sb.Append(",").AppendLine();
}
GenerateMethod(sb, method, includeDocComments, hubName);
first = false;
}
sb.AppendLine();
sb.Append(" }");
}
protected virtual string GetDescriptorName(Descriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException("descriptor");
}
string name = descriptor.Name;
// If the name was not specified then do not camel case
if (!descriptor.NameSpecified)
{
name = JsonUtility.CamelCase(name);
}
return name;
}
protected virtual IEnumerable GetMethods(IHubManager manager, HubDescriptor descriptor)
{
return from method in manager.GetHubMethods(descriptor.Name).Where(md => md.Attributes.FirstOrDefault(a => (a.GetType() == typeof(HubMethodExcludeFromProxyAttribute))) == null)
group method by method.Name into overloads
let oload = (from overload in overloads
orderby overload.Parameters.Count
select overload).FirstOrDefault()
orderby oload.Name
select oload;
}
protected virtual void GenerateMethod(StringBuilder sb, MethodDescriptor method, bool includeDocComments, string hubName)
{
var parameterNames = method.Parameters.Select(p => p.Name).ToList();
sb.AppendLine();
sb.AppendFormat(" {0}: function ({1}) {{", GetDescriptorName(method), Commas(parameterNames)).AppendLine();
if (includeDocComments)
{
sb.AppendFormat(" /// Calls the {0} method on the server-side {1} hub.\nReturns a jQuery.Deferred() promise.", method.Name, method.Hub.Name).AppendLine();
var parameterDoc = method.Parameters.Select(p => String.Format(CultureInfo.CurrentCulture, " /// Server side type is {2}", p.Name, MapToJavaScriptType(p.ParameterType), p.ParameterType)).ToList();
if (parameterDoc.Any())
{
sb.AppendLine(String.Join(Environment.NewLine, parameterDoc));
}
}
sb.AppendFormat(" return proxies['{0}'].invoke.apply(proxies['{0}'], $.merge([\"{1}\"], $.makeArray(arguments)));", hubName, method.Name).AppendLine();
sb.Append(" }");
}
protected virtual string MapToJavaScriptType(Type type)
{
if (!type.IsPrimitive && !(type == typeof(string)))
{
return "Object";
}
if (type == typeof(string))
{
return "String";
}
if (_numberTypes.Contains(type))
{
return "Number";
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return "Array";
}
if (_dateTypes.Contains(type))
{
return "Date";
}
return String.Empty;
}
protected virtual string Commas(IEnumerable values)
{
return Commas(values, v => v);
}
protected virtual string Commas(IEnumerable values, Func selector)
{
return String.Join(", ", values.Select(selector));
}
protected static string GetTemplateFromResource()
{
//this must remain "DefaultJavaScriptProxyGenerator" because the resource "Microsoft.AspNet.SignalR.Scripts.hubs.js" lives there
using (Stream resourceStream = typeof(DefaultJavaScriptProxyGenerator).Assembly.GetManifestResourceStream(ScriptResource))
{
var reader = new StreamReader(resourceStream);
return reader.ReadToEnd();
}
}
protected virtual string JavaScriptEncode(string value)
{
value = JsonConvert.SerializeObject(value);
// Remove the quotes
return value.Substring(1, value.Length - 2);
}
}
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class HubMethodExcludeFromProxyAttribute : Attribute
{
}
}
Now all you need to do is all a decorator to your hub methods, such as:
public class MyHub : Hub
{
[HubMethodExcludeFromProxy]
public void NotGeneratedOnClient()
{
}
public void GeneratedOnClient()
{
}
}
EDIT : There is an issue with dependency injection where if you have two different instances of a resolver, one in the GlobalHost.DependencyResolver and one in the Signalr configuration, it will cause remote methods to sometimes not work. Here is the fix:
//use only !ONE! instance of the resolver, or remote SignalR functions may not run!
var resolver = new CustomDependencyResolver();
GlobalHost.Configuration.DependencyResolver = resolver;
map.RunSignalR(
new HubConfiguration() {
Resolver = resolver;
}
);
Reference: https://github.com/SignalR/SignalR/issues/2807