Salesforce Tooling API - Deactivate Trigger - salesforce

I am attempting to deactivate triggers using the tooling API. I have successfully in a developer ORG. But was unable to do this in a real developer org. Is this a Salesforce tooling api bug?
Here is the basis of the algorithm,
Create a MetadataContainer with a unique Name
save MetadataContainer
Create an ApexTriggerMember setting the Body, MetadataContainerId, ContentEntityId, and Metadata[apiVersion=33.0 packageVersions=[] status="Inactive" urls=nil>]
Modify Metadata["status"]="Inactive"
save ApexTriggerMember
Create/Save ContainerAsyncRequest
monitor container until completed.
display errors if appropriate
In the sandbox, I have confirmed after requerying the Apex enter code hereTriggerMember that the read-only field "Content" looks appropriate. I also confirmed that the MetadataContainerId now points to a ContainerAsyncRequest that has a State of "Completed"
Here are my results, it appears to be a success, but the ApexTrigger is never deactivated
ContentEntityId = 01q.............[The ApexTrigger I want deactivated]
Content="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<ApexTrigger xmlns=\"urn:metadata.tooling.soap.sforce.com\">
<apiVersion>33.0</apiVersion>
<status>Inactive</status>
</ApexTrigger>"
Metadata={apiVersion=33.0 packageVersions=nil status="Inactive" urls=nil> attributes= {type="ApexTriggerMember"
url="/services/data/v33.0/tooling/sobjects/ ApexTriggerMember/401L0000000DCI8IAO"
}
}

I think you need to deploy the inactive Trigger from Sandbox to Production. You can't simply deactivate the Trigger in Production. This is true even in the UI.
There are other options, such as using a Custom Setting or Metadata Type to store a Run/Don't Run value. You would query that value in the Trigger to decide whether or not to run it.
https://developer.salesforce.com/forums/?id=906F0000000MJM9IAO

Related

Using Opportunity Selector to retrieve OpportunityContactRole

I am very new to apex, I am trying to understand apex code written by someone else. Its retrieving opportunity data. It gets all the fields except opportunity contact role. Its always empty, even though there is data in it.
It calls the opportunity selector from the service class
Opportunity opp = cq.Opportunities.GetByIdWithOCR(new Set{opportunityId})[0];
in the opportunitySelector.apxc
public List<Opportunity> GetByIdWithOCR(Set<Id> idSet) {
return (List<Opportunity>) GetQueryFactory()
.WithCriteria(cq_Criteria.ValueIn(Opportunity.Id, idSet))
.WithRelatedField(Opportunity.AccountId, Account.Name)
.WithRelatedField(Opportunity.AccountId, Account.BillingStreet)
.WithRelatedField(Opportunity.AccountId, Account.BillingCity)
.WithRelatedField(Opportunity.AccountId, Account.BillingState)
.WithRelatedField(Opportunity.AccountId, Account.BillingPostalCode)
.WithRelatedField(Opportunity.AccountId, Account.BillingCountry)
.WithChildQuery(
cq.OpportunityContactRoles.GetQueryFactory()
.WithCriteria(cq_Criteria.Equals(OpportunityContactRole.Role, 'Decision Maker'))
.WithRelatedField(OpportunityContactRole.ContactId, Contact.Name)
.WithRelatedField(OpportunityContactRole.ContactId, Contact.Phone)
.WithRelatedField(OpportunityContactRole.ContactId, Contact.Email))
.Execute();
}
all the values are there but contact role is empty. Please advice
This is all custom written by your colleague, some attempt at ORM layer. "Normal" apex would be to write the query directly, better performance, some compile-time checks... Hard to say what lurks in that code.
Which community it is? Customer or Partner? Last I checked customer community has no access to Opportunity. Assuming it's Partner - do you know how to check the Profile of the community user and access to whole OpportunityContactRole table and all fields in it?
There are some hacks to let code jump out of the Salesforce security model (without sharing etc) but I wouldn't recommend unless you really know what you're doing and normal ways of controlling data visibility (profiles/permission sets, sharing rules, like sharing sets) failed you.
Try to capture debug logs. Open developer console (if possible, you tagged this as communities) and run your page or experiment with Setup -> Debug Logs. You should be able to find the query and try to execute it manually.
If you want to rule out issues with this query factory try to swap the code with this and see if it's any better:
return [SELECT Account.Name, Account.BillingStreet, Account.BillingCity,
Account.BillingState, Account.BillingPostalCode, Account.BillingCountry,
(SELECT Contact.Name, Contact.Phone, Contact.Email
FROM OpportunityContactRoles
WHERE Role = 'Decision Maker')
FROM Opportunity
WHERE Id IN :idSet];

Meteor - How safe it is?

I'm actually creating my first app using meteor, in particular using angular 2. I've experience with Angular 1 and 2, so based on it. I've some points of concern...
Let's imagine this scenario...My data stored on MongoDb:
Collection: clients
{
name : "Happy client",
password : "Something non encrypted",
fullCrediCardNumber : "0000 0000 0000 0000"
}
Now, on my meteor client folder, I've this struncture...
collection clients.ts (server folder)
export var Clients = new Mongo.Collection('clients');
component client.ts (not server folder)
import {Clients} from '../collections/clients.ts';
class MyClients {
clients: Array<Object>;
constructor(zone: NgZone) {
this.clients = Clients.find();
}
}
..and for last: the html page to render it, but just display the name of the clients:
<li *ngFor="#item of clients">
{{client.name}}
</li>
Ok so far. but my concern is: In angular 1 & 2 applications the component or controller or directive runs on the client side, not server side.
I set my html just to show the name of the client. but since it's ah html rendering, probably with some skill is pretty easy to inject some code into the HTML render on angular to display all my fields.
Or could be easy to go to the console and type some commands to display the entire object from the database collection.
So, my question is: How safe meteor is in this sense ? Does my concerns correct ? Is meteor capable to protect my data , protect the name of the collections ? I know that I can specify on the find() to not bring me those sensitive data, but since the find() could be running not on the server side, it could be easy to modify it on the fly, no ?
Anyway...I will appreciate explanations about how meteor is safe (or not) in this sense.
ty !
You can protect data by simply not publishing any sensitive data on the server side.
Meteor.publish("my-clients", function () {
return Clients.find({
contractorId: this.userId // Publish only the current user's clients
}, {
name: 1, // Publish only the fields you want the browser to know of
phoneNumber: 1
});
});
This example only publishes the name and address fields of the currently logged in user's clients, but not their password or fullCreditCardNumber.
Another good example is the Meteor.users collection. On the server it contains all user data, login credentials, profiles etc. for all users. But it's also accessible on the client side. Meteor does two important things to protect this very sensitive collection:
By default it only publishes one document: the user that's logged in. If you type Meteor.users.find().fetch() into the browser console, you'll only see the currently logged in user's data, and there's no way on the client side to get the entire MongoDB users collection. The correct way to do this is to restrict the amount of published documents in your Meteor.publish function. See my example above, or 10.9 in the Meteor publish and subscribe tutorial.
Not the entire user document gets published. For example OAuth login credentials and password hashes aren't, you won't find them in the client-side collection. You can always choose which part of a document gets published, a simple way to do that is using MongoDB projections, like in the example above.

I'm unable to see system.debug statements on a trigger

I created a trigger that looks like this:
trigger DG_CM_Trigger on CampaignMember (before insert) {
System.debug('DG_CM_Trigger - START');
if (Trigger.isBefore && Trigger.isInsert){
DG_CampaignMember_Class.populateCustomAttributes(trigger.New);
}
System.debug('DG_CM_Trigger - END');
}
As you can see, I have system debug statements at the beginning and end of the trigger. When I look at the debug logs, I can see that the trigger is called...
09:42:46.524 (524616000)|CODE_UNIT_STARTED|[EXTERNAL]|01qc00000004eIV|DG_CM_Trigger on CampaignMember trigger event BeforeInsert for [new]
09:42:46.540 (540035000)|METHOD_ENTRY| [1]|01pc00000006aDT|DG_CampaignMember_Class.DG_CampaignMember_Class()
09:42:46.540 (540101000)|METHOD_EXIT|[1]|DG_CampaignMember_Class
09:42:46.540 (540725000)|METHOD_ENTRY|[4]|01pc00000006aDT|DG_CampaignMember_Class.populateCustomAttributes(LIST<CampaignMember>)
09:42:46.543 (543070000)|CONSTRUCTOR_ENTRY|[114]|01pc00000006aDT|<init>()
09:42:46.543 (543199000)|CONSTRUCTOR_EXIT|[114]|01pc00000006aDT|<init>()
09:42:46.543 (543273000)|METHOD_ENTRY|[114]|01pc00000006aDT|DG_CampaignMember_Class.LeadFieldMapping()
09:42:46.548 (548241000)|METHOD_ENTRY|[41]|01pc00000006aDT|DG_CampaignMember_Class.getCMFieldMapping()
09:42:46.693 (693286000)|METHOD_EXIT|[41]|01pc00000006aDT|DG_CampaignMember_Class.getCMFieldMapping()
09:42:46.703 (703469000)|METHOD_EXIT|[114]|01pc00000006aDT|DG_CampaignMember_Class.LeadFieldMapping()
09:42:46.781 (781457000)|METHOD_EXIT|[4]|01pc00000006aDT|DG_CampaignMember_Class.populateCustomAttributes(LIST<CampaignMember>)
09:42:46.781 (781790000)|CODE_UNIT_FINISHED|DG_CM_Trigger on CampaignMember trigger event BeforeInsert for [new]
However, I do not see my System.debug statement. I had debug statements in the class as well, but does do not show either. I have set the debug log filters to apex code: debug and system: debug (the rest are info). I even tried setting the 'override log filters' on the CampaignMember_Class and also set the levels to apex code: debug and system:debug. I can't seem to figure out why the debug statements are not showing up on the log which is making debugging extremely difficult. Peharps there is some kind of user setting I'm not aware of? User permissions? (although I'm in the admin profile, but I perhaps something in the profile settings that is not set?) Any help would be appreciated.
Try specifying the LoggingLevel as the first parameter to the System.debug calls. E.g.
System.debug(LoggingLevel.Error, 'hello');
Also, if this is a deployed managed package Salesforce will hide all logging.

Updating user info in liferay database

I need to update info of an existing user in my database programmaticaly
I need to update user name birth date values in user_ table in Liferay database
basically I need to run an update query.
It is not recommended to update the liferay database directly, you should use Liferay API instead to do these things. As per this liferay forum post:
The Liferay database is not published for a reason. The reason is the API does significantly more stuff than just simple SQL insert statements. There are internally managed foreign keys, there are things which are updated not just in the database but also in the indices, in jackrabbit, etc.
Since all of this is managed by the code and not by the database, any updates to the code will change how and when the database is updated. Even if it did work for you in a 6.1 GA1 version, GA2 is coming out in a couple of weeks and the database/code may change again.
Sticking with the API is the only way to insure the changes are done correctly.
Ok enough preaching and back to your problem, here are some ways you can do these:
you can either build a custom portlet and use liferay's services and update the username, birthdate etc using UserLocalServiceUtil.updateUser() method.
Or you can build a web-service client based on SOAP or JSON to update the details which would call the same method
Or you can use Liferay's Beanshell tool to do this from the control panel, following is some code to update the user (created just for you ASAP):
import com.liferay.portal.model.Company;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.ContactConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.ContactLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
long companyId = 10135; // this would be different for you
User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, "test#liferay.com");
// Updating User's details
user.setEmailAddress("myTest#liferay.com");
user.setFirstName("First Test");
user.setLastName("Last Test");
user.setScreenName("myTestScreenName");
UserLocalServiceUtil.updateUser(user, false);
// Updating User's Birthday
// December 12, 1912
int birthdayMonth = 11;
int birthdayDay = 12;
int birthdayYear = 1912;
Calendar cal = new GregorianCalendar();
cal.set(birthdayYear, birthdayMonth, birthdayDay, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date birthday = cal.getTime();
System.out.println("Updated User: " + user + "\nBirthdate to be updated: " + birthday);
long contactId = user.getContactId();
Contact contact = ContactLocalServiceUtil.getContact(contactId);
if(contact == null) {
contact = ContactLocalServiceUtil.createContact(contactId);
Company company = CompanyLocalServiceUtil.getCompany(user.getCompanyId());
contact.setCompanyId(user.getCompanyId());
contact.setUserName(StringPool.BLANK);
contact.setCreateDate(new Date());
contact.setAccountId(company.getAccountId());
contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
}
contact.setModifiedDate(new Date());
contact.setBirthday(birthday);
ContactLocalServiceUtil.updateContact(contact, false);
System.out.println("Users birthdate updated successfully");
The contact code is built with the help of Liferay's source code for UserLocalServiceImpl#updateUser method
In case you are wondering what is bean-shell and where to put this code, here is where you can find it in Liferay Control Panel Control Panel --> Server --> Server Administration --> Script
It depends on whether you have to do this in a portlet code or by sending a direct query to db.
Liferay basically caches everything, so if you update a record in the Liferay database while the portal is running, most likely that record is already in cache, and so the new column values won't be read at all. You will have to clear the database cache by going to Control Panel -> Server Administration.
On the contrary, if you have to do such a thing in a portlet code, you should call one of the methods of the Liferay services. You're trying to update a User, so you should call the method UserLocalServiceUtil.updateUser (or UserServiceUtil.updateUser if you also want to check permissions).
You can see there are some different updateUser methods, one of them has a lot of parameters and another has only the bean as a parameter. While the first one contains all the business logic (validation, reindexing, update of related entities, etc.), the second one was just autogenerated and should not be used (except when you absolutely know what you're doing). So, use the method with a lot of parameters, simply passing user.getCOLUMN() (eg. user.getFacebookId()) if you don't want to change the value of that column.
Hope it helps, and sorry for my bad English...
update user_ set firstName="New First Name", lastName="New Last Name" where emailAddress="test#test.com";
update contact_ set birthday="date string" where contactId in(select contactId from user_ where emailAddress="test#test.com");
By first update query you can change firstName, lastName of user and by second query you can change birthdate of user.
Hope its clear!
Try this code..
Here i am updating only user First name(rest you can do by your own way)
userId = you can get this using theme display
User user = UserLocalServiceUtil.getUser(userId);
user.setFirstName("new name");
UserLocalServiceUtil.updateUser(user);
Hope this will help you !!!

How do I detect the environment in Salesforce?

I am integrating our back end systems with Salesforce using the web services. I have production and stage environments running on different URLs. I need to be able to have the endpoint of the web service call be different depending on whether the code is running in the production or sandbox Salesforce instance.
How do I detect the environment.
Currently I am considering looking up a user to see if there user name ends in 'devsandbox' as I have been unable to identify a system object that I can query to get the environment.
Further clarification:
The location I need to determine this is within the Apex code that is invoked when I select a button in Salesforce. My custom controller needs to know if it running in the production or sandbox Salesforce environment.
For y'all finding this via search results, there is an important update. As Daniel Hoechst pointed out in another post, SF now directly provides sandbox vs. production information:
In Summer '14, (version 31.0), there is a new field available on the
Organization object.
select Id, IsSandbox from Organization limit 1
From the release notes under New and Change Objects:
The Organization object has the following new read-only fields.
InstanceName
IsSandbox
Based on the responses it appears that Salesforce does not have a system object that can tell me if my Apex code is running in production or a sandbox environment.
I am going to proceed based on the following assumptions:
I can read the organisation id of the current environment
The organisation id of my production system will always remain constant.
The organisation id of a sandbox will always be different to production (as they are unique)
The current organization ID can be found with System.getOrganizationId()
My solution is to have my code compare the current org id to the constant value representing production.
I'm performing necromancy here and the answer is already accepted, but maybe somebody will benefit from it...
Use one of these merge fields on your Visualforce page / S-Control:
{!$Api.Enterprise_Server_URL_180}, {!$Api.Partner_Server_URL_180}, {!$Api.Session_ID}
You can easily parse out organization ID out of them.
In Apex code: UserInfo.getOrganisationId()
I know this is an old post, but just for the sake of people looking for an updated answer as of Spring '11 release there is a new method System.URL.getSalesforceBaseUrl().toExternalForm() that returns the current url.
You can work from there to get all the info you need.
Here's the link to docs: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_url.htm
The Login API call returns a sandbox element in the returned LoginResult structure that indicates if its a sandbox environment or not, from the WSDL.
<complexType name="LoginResult">
<sequence>
<element name="metadataServerUrl" type="xsd:string" nillable="true"/>
<element name="passwordExpired" type="xsd:boolean" />
<element name="sandbox" type="xsd:boolean"/>
<element name="serverUrl" type="xsd:string" nillable="true"/>
<element name="sessionId" type="xsd:string" nillable="true"/>
<element name="userId" type="tns:ID" nillable="true"/>
<element name="userInfo" type="tns:GetUserInfoResult" minOccurs="0"/>
</sequence>
</complexType>
Sandboxes may have a personalized url (e.g. acme.cs1.my.salesforce.com), or might be hosting a visualforce page (cs2.visual.force.com) or both (acme.cs2.visual.force.com) so I use this method:
public static Boolean isRunningInSandbox() {
String s = System.URL.getSalesforceBaseUrl().getHost();
return (Pattern.matches('(.*\\.)?cs[0-9]*(-api)?\\..*force.com',s));
}
I think the easiest way to do this would be to create a custom object in Salesforce, and then store a value indicating sandbox or production there. Your Apex code can then query that object. One suggestion would be to use Apex static constructors to load this information and cache it for the request.
Another thought I had (but hate to suggest) is to use an external service to determine where your Apex code is executing. This would probably be difficult to pull off, as every time the SalesForce server farm changes there is a change your code would break, but I just thought I'd throw this out there.
HttpRequest req = new HttpRequest();
req.setEndpoint('http://www.whatismyip.com/automation/n09230945.asp');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
You have to add "http://www.whatismyip.com" to the Remote Site settings to get this to work (Setup > Administration Setup > Security Controls > Remote Site Settings). This code should run in the debug window when you click "System Log".
In your apex code you can use the following to get the instance of SF that you are in.
Keeping it dynamic will make sure you don't have to update your code when your org is migrated to a different instance.
String s = System.URL.getSalesforceBaseUrl().getHost();
//this will return "na1.salesforce.com" or "na1-api.salesforce.com",
// where na1 is your instance of SF, and -api may be there depending on where you run this
s = s.substring(0,s.indexOf('.'));
if(s.contains('-'))
{
s = s.substring(0,s.indexOf('-'));
}
system.debug(s);
There is a similar question on the Salesforce StackExchange for detecting if you are in a Sandbox or not - Can we determine if the Salesforce instance is production org or a Sandbox org?
In the solutions in search of a problem category, you could use the pod identifier from the OrgId to determine if you are dealing with a sandbox.
string podId = UserInfo.getOrganizationId().substring(3,4);
boolean isSandbox = 'TSRQPONMLKJZVWcefg'.contains(podId);
System.debug('IsSandbox: ' + isSandbox);
Caveat Confector: The big weakness here is that you will need to update the list of know sandbox pods as and when Salesforce brings new ones online (so it might be safer sticking with the other solutions).
You can use the following code block from Michael Farrington an authority on Salesforce.
Original blog post here: Michael Farrington: Where Am I Method
This method will return true if you are in a test or sandbox environment and false otherwise.
public Static Boolean isSandbox(){
String host = URL.getSalesforceBaseUrl().getHost();
String server = host.substring(0,host.indexOf('.'));
// It's easiest to check for 'my domain' sandboxes first
// even though that will be rare
if(server.contains('--'))
return true;
// tapp0 is a unique "non-cs" server so we check it now
if(server == 'tapp0')
return true;
// If server is 'cs' followed by a number it's a sandbox
if(server.length()>2){
if(server.substring(0,2)=='cs'){
try{
Integer.valueOf(server.substring(2,server.length()));
}
catch(exception e){
//started with cs, but not followed by a number
return false;
}
//cs followed by a number, that's a hit
return true;
}
}
// If we made it here it's a production box
return false;
}

Resources