need help please! question regarding Salesforce Apex Scheduled class.
I need to call an action from visual force page the action located on the apex class. The apex class is quite long to post, but the action totally works from VF page.
Here is sample version of the code. But scheduled class doesn't work, just keep giving errors to save.
VF Page
<apex:page standardController="Account" Extensions="ProvisionAccount">
<apex:commandButton value="Proceed" action="{!provision}" rendered="{!renderProceedButton}" onComplete="window.close();" />
Here is my code that I can't make it work:
global class AutoProv implements Schedulable {
global void execute(SchedulableContext ctx) {
List <Account> A = [SELECT Id FROM Account
WHERE ToBeProcessed__C = True ];
ProvisionAccount.provision(A);
}
}
Anyone knows how to call action from VF or Apex Class
You have not created new instance to your controller class and simply passing the list of accounts as a parameter .
Can you please try the below code and test whether it is working or not
global class AutoProv implements Schedulable {
global void execute(SchedulableContext ctx) {
List <Account> A = [SELECT Id FROM Account
WHERE ToBeProcessed__C = True ];
ProvisionAccount sch = new ProvisionAccount(A);
}
}
Related
As above. In salesforce, I would like to create a trigger so that an event is created when the owner id changes for an account. This is so that the changes in owner id can be tracked in the activity timeline of the account. I have searched for solutions but did not find anything.
Would be great if someone can help me! (or if I've missed a post, to point me in the right direction.)
Thanks!
You would create a trigger that implements the onUpdate event and write an associated class to execute your Apex code.
AccountUpdate.trigger
trigger AccountUpdateTrigger on Account (after update) {
if (!TriggerUtil.ExecutingTriggers.containsKey('AccountUpdateTrigger')){
Set<Id> processedIds = new Set<Id>();
TriggerUtil.ExecutingTriggers.put('AccountUpdateTrigger',processedIds);
}
if(trigger.isAfter && trigger.isUpdate) {
AccountUpdateTriggerHandler.OnAfterUpdate(trigger.newMap, trigger.oldMap);
}
}
Then in your AccountUpdateTriggerHandler class you would write a handler
public Class DocumentRequestTriggerHandler {
public static void onAfterUpdate(Map<Id, Account> newMap, Map<Id, Account> oldMap){
updateTracking(newMap,oldMap);
}
public static void updateTracking(Map<Id, Account> newMap, Map<Id, Account> oldMap){
// your necessary code here
}
}
Alternatively, for your use cse you could also just turn on History Tracking at the field level.
I am using Angular in an ASP.NET Core with ASP.NET Identity application.
I have the following controller action
[HttpGet("users/{userId:int:min(1)}/notes"), Authorize]
public async Task<IActionResult> GetNotesBy(userId) {
var data = _service.getNotesBy(userId);
return Ok(data);
} // GetNotesBy
I would like to restrict the access to the API so:
If a user is authenticated than it can only access its notes.
I want to prevent an authenticate user with ID=X to access the notes of a user with ID=Y. How can I block an user in this situation?
This is what resource based authorization is aimed at.
As resource based authorization requires the actual resource it needs to happen imperatively, inside your controller.
The following is for ASP.NET Core RC1.
So, let's assume your getNotesBy returns a Notes class, and you have a few operations, read, write, update, delete.
First we need to define the operations. There's a suitable base class in Microsoft.AspNet.Authorization.Infrastructure, OperationAuthorizationRequirement. So we'd do something like this.
public static class Operations
{
public static OperationAuthorizationRequirement Create =
new OperationAuthorizationRequirement { Name = "Create" };
public static OperationAuthorizationRequirement Read =
new OperationAuthorizationRequirement { Name = "Read" };
public static OperationAuthorizationRequirement Update =
new OperationAuthorizationRequirement { Name = "Update" };
public static OperationAuthorizationRequirement Delete =
new OperationAuthorizationRequirement { Name = "Delete" };
}
So now we have our operations, we think about how we handle authorization. You have two ways operations can succeed, if the current user owns the notes, or the current user is an admin. This equates to two handlers for a single requirement/operation.
The admin one is easy, it would look something like this;
public class AdminAuthorizationHander :
AuthorizationHandler<OperationAuthorizationRequirement, Notes>
{
protected override void Handle(AuthorizationContext context,
OperationAuthorizationRequirement requirement,
Document resource)
{
var isSuperUser = context.User.FindFirst(c => c.Type == "Superuser" &&
c.Value == "True");
if (isSuperUser != null)
{
context.Succeed(requirement);
return;
}
}
}
Here we're looking for a Superuser claim with a value of True. If that's present we succeed the requirement. You can see from the method signature we're taking the OperationAuthorizationRequirement and a resource, the Notes class. This handler doesn't limit itself to a single operation, admins have rights to every operation.
Now we can write the handler which looks for the actual user.
public class NotesAuthorizationHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Notes>
{
protected override void Handle(AuthorizationContext context,
OperationAuthorizationRequirement requirement,
Notes resource)
{
if (context.User.Name == resource.Owner)
{
context.Succeed(requirement);
}
}
}
Here we are writing something that will work for all resources, and checks an Owner property on the resource against the name of the current user.
So we have two handlers now for a single requirement, the OperationAuthorizationRequirement.
Now we need to register our handlers. In startup.cs you register handlers in DI in the ConfigureServices() method. After the call to services.AddAuthorization() you need to put your handlers into DI. You would do this like so;
services.AddSingleton<IAuthorizationHandler, AdminAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, NotesAuthorizationHandler>();
You can adjust the scope from Singleton to whatever you like if you are taking things like a DbContext.
Finally we're almost ready to call this, but first you need to change your controller constructor to take an instance of IAuthorizationService. Once you have that you can call AuthorizeAsync() and away you go.
[Authorize]
public class NotesController : Controller
{
IAuthorizationService _authorizationService;
public NotesController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
[HttpGet("users/{userId:int:min(1)}/notes"), Authorize]
public async Task<IActionResult> GetNotesBy(userId)
{
var resource = _service.getNotesBy(userId);
if (await authorizationService.AuthorizeAsync(User, resource, Operations.Read))
{
return Ok(data);
}
return new ChallengeResult();
}
}
So what you are doing is getting your resource, and then authorizing the current user against it and the operation. When this happens all handlers which can handle that resource and operation will get called. As there are multiple handlers any one can succeed and allow access.
I have a class.Class contain a method ParseJSONResponse().I want that method should get executed on daily basis at midnight.How I can achieve this in salesforce.
I know there is schedule apex mechanism is available in salesforce to perform such a thing but I need no. of steps or code to achieve this.I am new to salesforce.Any help would be appreciated.
public with sharing class ConsumeCloudArmsWebserviceCallout{
public void ParseJSONResponse(){
// handling customerList and inserting records for it
DateTime lastModifiedDate =Common.getSynchDateByDataObject(CloudArmsWebserviceCallout.DataObject.CustomerContact);
List<Account> lstAccounts = ConsumeCustomers.CreateCustomers(lastModifiedDate);
ConsumeContacts.CreateContacts(lastModifiedDate);
Common.updateSynchByDataObject(CloudArmsWebserviceCallout.DataObject.CustomerContact);
}
}
You can implement the Schedulable interface directly to your ConsumeCloudArmsWebserviceCallout class:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
In order to perform callout -which apparently you will according to your class name- you can use the Queueable interface:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm
public with sharing class ConsumeCloudArmsWebserviceCallout implements Schedulable {
public void ParseJSONResponse(){
// handling customerList and inserting records for it
DateTime lastModifiedDate =Common.getSynchDateByDataObject(CloudArmsWebserviceCallout.DataObject.CustomerContact);
List<Account> lstAccounts = ConsumeCustomers.CreateCustomers(lastModifiedDate);
ConsumeContacts.CreateContacts(lastModifiedDate);
Common.updateSynchByDataObject(CloudArmsWebserviceCallout.DataObject.CustomerContact);
}
//Method implemented in order to use the Schedulable interface
public void execute(SchedulableContext ctx) {
ConsumeCloudQueueable cloudQueueable = new ConsumeCloudQueueable();
ID jobID = System.enqueueJob(cloudQueueable);
}
//Inner class that implements Queueable and can perform callouts.
private class ConsumeCloudQueueable implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext context) {
ConsumeCloudArmsWebserviceCallout cloudArms = new ConsumeCloudArmsWebserviceCallout();
cloudArms.ParseJSONResponse();
}
}
}
Then go onto the class page on Salesforce setup.
There you will find a schedule class button.
You will be able to schedule all classes implementing the Schedulable interface.
What will happen is that it will schedule your class daily.
Then your schedule will only en-queue a ConsumeCloudQueueable class that will do the job whenever Salesforce runs it (pretty much straight away).
Once the job runs, it will execute whatever is on you ParseJSONResponse() method.
Let me know if you have any question.
Cheers,
Seb
and welcome to salesforce development.
If I assume something wrong let me know. So you are looking to
Every Day at Midnight
Fire a job that makes a callout to another system
Then Parses the results and creates stuff
You are looking for Apex Scheduler code: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm
global class ConsumeCloudArmsWebserviceCallout_Job implements Schedulable {
global void execute(SchedulableContext sc) {
new ConsumeCloudArmsWebserviceCallout().ParseJSONResponse();
}
}
Then you can schedule the job in yourname -> Developer Console. Debug -> Open Execute Anonymous Window.
system.schedule('Consumer Cloud Arms Service', '0 0 0 * * ?', new ConsumeCloudArmsWebserviceCallout_Job());
Keep in mind:
you can only make 5 callouts in one apex transation. Meaning if you need to do more, you need to use a batch job or #future calls.
Be careful with large data sets, if your job is expensive (creating and modifying lots of data) you need to be sure that you don't run in to CPU limits, So a batch job requesting smaller portions of data from the service you are calling out may be needed.
I don't think you will be running in to those issues, but they will catch you off guard sometimes.
EDIT: fixed the call to a new object, less psudo-code
Quick question about page objects in selenium webdriver. our site is very dynamic with lots of ajax and various authentication states. It is tough to figure out how to define each page object BUT lets say I have figured that out and defined several page objects that represent our site.
How do you handle crossing from page to page. So I get a page object for my home page and one for my account page and one for my results page. Then I need to write a test that traverses all my pages to simulate a user performing multiple actions.
How do you say give me a HomePage object to create a new use -> then get a account page object to go perform some user actions - then get a result page object to verify those actions all from a single script.
How are people doing this?
thanks
When you're simulating having the user enter a new URL into the URL bar of the browser, then it's the responsibility of the test class to create the page object it needs.
On the other hand, when you're doing some operation on the page that would cause the browser to point to another page -- for example, clicking a link or submitting a form -- then it's the responsibility of that page object to return the next page object.
Since I don't know enough about the relationships between your home page, account page, and result page to tell you exactly how it'd play out in your site, I'll use an online store app as an example instead.
Let's say you've got a SearchPage. When you submit the form on the SearchPage, it returns a ResultsPage. And when you click on a result, you get a ProductPage. So the classes would look something like this (abbreviated to just the relevant methods):
public class SearchPage {
public void open() {
return driver.get(url);
}
public ResultsPage search(String term) {
// Code to enter the term into the search box goes here
// Code to click the submit button goes here
return new ResultsPage();
}
}
public class ResultsPage {
public ProductPage openResult(int resultNumber) {
// Code to locate the relevant result link and click on it
return new ProductPage();
}
}
The test method to execute this story would look something like this:
#Test
public void testSearch() {
// Here we want to simulate the user going to the search page
// as if opening a browser and entering the URL in the address bar.
// So we instantiate it here in the test code.
SearchPage searchPage = new SearchPage();
searchPage.open(); // calls driver.get() on the correct URL
// Now search for "video games"
ResultsPage videoGameResultsPage = searchPage.search("video games");
// Now open the first result
ProductPage firstProductPage = videoGameResultsPage.openResult(0);
// Some assertion would probably go here
}
So as you can see, there's this "chaining" of Page Objects where each one returns the next one.
The result is that you end up with lots of different page objects instantiating other page objects. So if you've got a site of any considerable size, you could consider using a dependency injection framework for creating those page objects.
Well, I created my own Java classes which represent the pages:
Say, the below is code to represent home page. Here user can login:
public class HomePage{
private WebDriver driver;
private WebElement loginInput;
private WebElement passwordInput;
private WebElement loginSubmit;
public WebDriver getDriver(){
return driver;
}
public HomePage(){
driver = new FirefoxDriver();
}
public CustomerPage login(String username, String password){
driver.get("http://the-test-page.com");
loginInput = driver.findElement(By.id("username"));
loginInput.sendKeys(username);
passwordInput = driver.findElement(By.id("password"));
passwordInput.sendKeys(password);
loginSubmit = driver.findElement(By.id("login"));
loginSubmit.click();
return new CustomerPage(this);
}
}
And the page for Customer can look like this. Here I am demonstrating, how to get, say, logged in user:
public class CustomerPage{
private HomePage homePage;
private WebElement loggedInUserSpan;
public CustomerPage(HomePage hp){
this.homePage = hp;
}
public String getLoggedInUser(){
loggedInUserSpan = homePage.getDriver().findElement(By.id("usrLongName"));
return loggedInUserSpan.getText();
}
}
And the test can go like this:
#Test
public void testLogin(){
HomePage home = new HomePage();
CustomerPage customer = home.login("janipav", "extrasecretpassword");
Assert.assertEquals(customer.getLoggedInUser(), "Pavel Janicek");
}
You generally want to model what a user actually does when using your site. This ends up taking the form of a Domain Specific Language (DSL) when using page objects. It gets confusing with reusable page components though.
Now that Java 8 is out with default methods, reusable page components can be treated as mixins using default methods. I have a blog post with some code samples found here that explains this in more detail: http://blog.jsdevel.me/2015/04/pageobjects-done-right-in-java-8.html
I suggest you use a framework that provides support for these patterns. Geb is one of the best one out there. Below is an example taken from their manual
Browser.drive {
to LoginPage
assert at(LoginPage)
loginForm.with {
username = "admin"
password = "password"
}
loginButton.click()
assert at(AdminPage)
}
class LoginPage extends Page {
static url = "http://myapp.com/login"
static at = { heading.text() == "Please Login" }
static content = {
heading { $("h1") }
loginForm { $("form.login") }
loginButton(to: AdminPage) { loginForm.login() }
}
}
class AdminPage extends Page {
static at = { heading.text() == "Admin Section" }
static content = {
heading { $("h1") }
}
}
I enjoy writing Selenium Webdriver tests using the Page Object pattern. But was personally annoyed at the verbosity and repetition of having to always explicitly instantiate and return the next page or page component. So with the benefit of Python's metaclasses I wrote a library, called Keteparaha, that automatically figures out what should be returned from a selenium page object's method calls.
I'm currently learning apex (using the Force.com IDE), and I'm running into some trouble when writing a test for a custom controller.
The controller class is as follows:
public with sharing class CustomController {
private List<TestObject__c> objects;
public CustomController() {
objects = [SELECT id, name FROM TestObject__c];
}
public List<TestObject__c> getObjects() {
return objects;
}
}
and the test class is:
#isTest
private class ControllerTest {
static testMethod void customControllerTest() {
CustomController controller = new CustomController();
System.assertNotEquals(controller, null);
List<TestObject__c> objects;
objects = controller.getObjects();
System.assertNotEquals(objects, null);
}
}
On the objects = controller.getObjects(); line I'm getting an error which says:
Save error: Method does not exist or incorrect signature: [CustomController].getObjects()
Anyone have an idea as to why I'm getting this error?
A nice shorthand:
public List<TestObject__c> objects {get; private set;}
It creates the getter/setter for you and looks cleaner imo. As for your current issue, yes - it's hard saving code directly into production - especially with test classes in separate files.
Best to do this in a sandbox/dev org then deploy to production (deploy to server - Force.com IDE). But if you must save directly into production then I'd combine test methods with your class. But in the long run, having #test atop a dedicated test class is the way to go. It won't consume your valuable resources this way.