• Wei Dong 10
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 17
    Replies
Hi,

I have an EmailMessage trigger (after insert), I'll do some checks of attachments (Notice my attachments are of ContentDocumentLink!)
The code looks like this following:
private static void doNotAllowProfilesSendEmailsWithAttachments(List<EmailMessage> newMessages) {

        if (!validateCurrentUserRule()) {
            System.debug('====User without the permission===');
            String digitalSignature = [SELECT CA_Digital_Signature__c FROM User WHERE Id = :UserInfo.getUserId()][0].CA_Digital_Signature__c;
            System.debug('===digitalSignature===='+digitalSignature);
            System.debug('===newMessages===='+newMessages);
            Set<String> msgIdSet = new Set<String>();
            Map<String, Set<String>> attMap = new Map<String, Set<String>>();
            for(EmailMessage msg:newMessages){
                msgIdSet.add(msg.Id);
            }
            System.debug('===msgIdSet===='+msgIdSet);
            for(ContentDocumentLink cdl :[SELECT Id, LinkedEntityId, ContentDocumentId, ContentDocument.title FROM ContentDocumentLink where LinkedEntityId IN :msgIdSet]){
                if(!attMap.containsKey(cdl.LinkedEntityId)){
                    attMap.put(cdl.LinkedEntityId, new Set<string>());
                }
                attMap.get(cdl.LinkedEntityId).add(cdl.ContentDocument.title);
            }
            System.debug('===attMap===='+attMap);
            for(EmailMessage msg:newMessages){
                if(msg.Incoming == FALSE){
                    for(String title : attMap.get(msg.Id)){
                        if(!digitalSignature.contains(title)){
                            msg.addError('You may not include an attachment in outbound emails.');
                            break;
                        }
                    }
                }
            }
        }
    }
And then my Unit test is:
@IsTest
    public static void doNotAllowProfilesSendEmailsWithAttachments_TestWrong() {

        String[]emails = new String[]{
                'wei.dong@pwc.com'
        };
        Boolean isSentSuccessful = true;

        // Test when we attach an attachment with 'Stand User'
        Profile p = [SELECT Id FROM Profile WHERE Name = 'Consumer Care Agent'];
        User u = new User(Alias = 'standt', Email = 'standarduser@testorg.com',
                EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US', ProfileId = p.Id,
                TimeZoneSidKey = 'America/Los_Angeles',
                UserName = 'standarduser_dongwei_test@testorg.com');

        Test.startTest();

        System.runAs(u) {

            // Insert a new contact for inner search contact ID
            Contact newContact = new Contact();
            newContact.LastName = 'Last Name';
            insert newContact;

            // 1. Create a Document as an attachment
            Document doc = new Document();
            doc.Name = 'Test document';
            doc.Body = Blob.valueOf('Test me');
            doc.ContentType = 'text/plain';
            doc.Type = 'txt';
            doc.FolderId = UserInfo.getUserId();
            insert doc;

            // 2. Preparing to attach the attachment
            Messaging.EmailFileAttachment file = new Messaging.EmailFileAttachment();
            file.setContentType('application/txt');
            file.setFileName('testAttachment.txt');
            // Make this as an attachment
            file.setInline(false);
            file.Body = doc.Body;


            // 3. Successfully sent
            Map<String, String> replacers = new Map<String, String>();
            replacers.put('dongwei', '');
            isSentSuccessful = CA_Utility.sendSingleEmail(emails,
                    'Test', 'Test body',replacers, 'DongWei',
                    true, new Messaging.EmailFileAttachment[]{
                            file
                    });
            System.assert(isSentSuccessful);

            EmailMessage email = new EmailMessage();
            email.FromAddress = 'test@abc.org';
            email.Incoming = True;
            email.ToAddress = 'test@xyz.org';
            email.Subject = 'Test email';
            email.HtmlBody = 'Test email body';

            Blob beforeblob = Blob.valueOf('Unit Test Attachment Body');

            ContentVersion cv = new ContentVersion();
            cv.title = 'Bad Signature Here';
            cv.PathOnClient = 'test';
            cv.VersionData = beforeblob;
            insert cv;

            ContentVersion testContent = [SELECT id, ContentDocumentId FROM ContentVersion where Id = :cv.Id];

            ContentDocumentLink contentlink = new ContentDocumentLink();
            contentlink.LinkedEntityId = email.Id;
            contentlink.ShareType = 'V';
            contentlink.ContentDocumentId = testcontent.ContentDocumentId;
            contentlink.LinkedEntityId = email.Id;

            email.ContentDocumentLinks.add(contentlink);
            insert email;
        }

        Test.stopTest();
    }
I tried to use Email attach to attach an attachments, but nothing hopes to improve the coverage; And when I tried to use "ContentDocumentLink" it still doesn't help. 

Any one can help me to improve the coverage about entering the 'for' of ContentDocumentLink in my trigger?
I have a RESTful API that lets me update something.

Since this is an External User (A user is automatically created with a Personal Account). I wanna know why I cannot update User's username? If I update this, there'll be the error occuring:

10:38:10:978 USER_DEBUG [283]|DEBUG|=== User Updated Error ===Update failed. First exception on row 0 with id 0030m00000IztRaAAJ; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: User: []

Here're the codes:
 
public static CA_RSEUserResponse updateUserInfo(CA_RSEUserInfo rseUserInfo) {

    User u = null;
    CA_RSEUserResponse resp = new CA_RSEUserResponse();
    Savepoint sv = Database.setSavepoint();

    try {
        // 1. Update User
        u = [
                SELECT Username,Email,FirstName,LastName,Id,ContactId
                FROM User
                WHERE Id = :rseUserInfo.id
                LIMIT 1
        ];

        System.debug('=== User ID is ===' + rseUserInfo.id);
        System.debug('User Contact ID is ===' + u.ContactId);

        u.Username = rseUserInfo.email_address;
        u.Email = rseUserInfo.email_address;
        u.FirstName = rseUserInfo.first_name;
        u.LastName = rseUserInfo.last_name;
        update u;


        // 2. Find the related contact and fill in the info
        Contact foundContact = [
                SELECT LastName,FirstName,Birthdate,MailingCity,MailingState,
                        MailingPostalCode,Phone,CA_Subscription_Status__c,CA_Gender__c,
                        CA_Dependants__c,CA_SkillLevel__c,CA_FavoriteCuisines__c,
                        CA_RecipeDislikes__c,CA_RecipeLikes__c,CA_Retailer__c,
                        CA_LanguagePreference__c,CA_EnjoymentLevel__c,CA_RepeatFrequency__c,
                        CA_AdventureLevel__c,CA_CreatedProfile__c,CA_CompletedProfile__c,
                        CA_HouseholdAdults__c
                FROM Contact
                WHERE Id = :u.ContactId
                LIMIT 1
        ];

        System.debug('Birth Year ==='+rseUserInfo.birth_year);

        foundContact.LastName = rseUserInfo.last_name;
        foundContact.FirstName = rseUserInfo.first_name;
        foundContact.Birthdate = rseUserInfo.birth_year;
        foundContact.MailingCity = rseUserInfo.city;
        foundContact.MailingState = rseUserInfo.state;
        foundContact.MailingPostalCode = rseUserInfo.zip;
        foundContact.Phone = rseUserInfo.mobile_phone;
        foundContact.CA_Subscription_Status__c = rseUserInfo.subscription_status;
        foundContact.CA_Gender__c = rseUserInfo.gender;
        foundContact.CA_Dependants__c = rseUserInfo.dependants;
        foundContact.CA_SkillLevel__c = rseUserInfo.skill_level;
        foundContact.CA_FavoriteCuisines__c = rseUserInfo.favorite_cuisines;
        foundContact.CA_RecipeDislikes__c = rseUserInfo.recipe_dislikes;
        foundContact.CA_RecipeLikes__c = rseUserInfo.recipe_favorites;
        foundContact.CA_Retailer__c = rseUserInfo.retailer;
        foundContact.CA_LanguagePreference__c = rseUserInfo.language_preference;
        foundContact.CA_EnjoymentLevel__c = rseUserInfo.enjoyment_level;
        foundContact.CA_RepeatFrequency__c = rseUserInfo.repeat_frequency;
        foundContact.CA_AdventureLevel__c = rseUserInfo.adventure_level;
        foundContact.CA_CreatedProfile__c = rseUserInfo.created_profile;
        foundContact.CA_CompletedProfile__c = rseUserInfo.completed_profile;
        foundContact.CA_HouseholdAdults__c = rseUserInfo.household_adults;
        update foundContact;

        resp.errorMsg = null;
        resp.content = rseUserInfo;
    } catch (Exception ex) {
        Database.rollback(sv);
        System.debug('=== User Updated Error ===' + ex.getMessage());
        rseUserInfo = null;
    }

    return resp;
If I remove 'User.username = xxx' for update, everything is good……so why and how to update that?
Hi,
I have created an EmailMessage, but I cannot fetch the name of the attachments through "EmailMessage.Attachments", so how? Any examples?
Hello all:

I tried to embed my own website's page with Salesforce, and I've deployed my static HTML page into Azure as an example , the codes look like this following (this is the WebSite's URL:https://salesforcehtmltest.azurewebsites.net/).
 
<!DOCTYPE html>
<html>

<head>
    <meta name="salesforce-community" content="https://dev-conagradev.cs65.force.com">
    <meta name="salesforce-client-id" content="3MVG9aFryxgomHTbDJ87BGyiOIOX.JQ_GDxC3h1i72cfZeP_Wm9dgVzNm31vXngKKGYRv665beVbQQL_Bdq9d">
    <meta name="salesforce-redirect-uri" content="https://loginwidget.herokuapp.com/latest/_callback.html">
    <meta name="salesforce-mode" content="modal">
    <meta name="salesforce-target" content="#salesforce-login">
    <meta name="salesforce-login-handler" content="onLogin">
    <meta name="salesforce-logout-handler" content="onLogout">
    <link href="https://dev-conagradev.cs65.force.com/readyseteat/servlet/servlet.loginwidgetcontroller?type=css"
        rel="stylesheet" type="text/css" />
    <script src="https://dev-conagradev.cs65.force.com/readyseteat/servlet/servlet.loginwidgetcontroller?type=javascript_widget"
        async defer></script>

    <script>
        function onLogin(identity) {

            var targetDiv = document.querySelector(SFIDWidget.config.target);
            var img = document.createElement('img');
            img.src = identity.photos.thumbnail;
            img.className = "sfid-avatar";

            var username = document.createElement('span');
            username.innerHTML = identity.username;
            username.className = "sfid-avatar-name";

            var iddiv = document.createElement('div');
            iddiv.id = "sfid-identity";
            iddiv.appendChild(img);
            iddiv.appendChild(username);

            targetDiv.innerHTML = '';
            targetDiv.appendChild(iddiv);
        }

        function onLogout() {
            SFIDWidget.init();
        }

    </script>


</head>

<body>
    <div id="salesforce-login" data-login-event="onLogin"></div>
</body>

</html>

2) Add this website into CORS:
User-added image
3) When I run the page on Azure, it still doesn't work……Why?
User-added image
A very simple question,

Suppose I send a request to oauth (part of my codes are shown here):
 
<html>

<head>
    <script type="text/javascript">
        function login() {

            alert("Now you are going to log into Salesforce...");
            // According to the client_id, client_secret, you can directly
            // go to the Salesforce

            window.open('https://test.salesforce.com/services/oauth2/authorize?response_type=code&client_id=xxxx&redirect_uri=https://www.getpostman.com/oauth2/callback&display=popup');
        }
    </script>
</head>

<body>
    <button onclick="login()">Login To Salesforce</button>
</body>

</html>

I want to make it a Modal Popup, so can this be done?
Hi all,
I have several questions during my dev of customize self-registeration:

1) I've created a Community called "https://dev-conagradev.cs65.force.com/readyseteat",  but to my surprise is that there's a suffix "/s"……Why? I cannot remove that at all. How can I remove that?
User-added image

2) I entered the "builder" of that to select a self-registeration page (My selection is "SelRegister"——A lightning page with some components):
User-added image

But to my surprise——When I run the page I always receive an error (See the red below), why? I do nothing to do codes at all.
Even if I tried to do some alerts, I didn't see anything popped up to me?No alert dialog pops out?
User-added image

In my Server-side code, where to see "System.Debug"? I see nothing outputted in the Developer Console……
User-added image

Is there any full example of using SelfRegister page to implement your own registeration step by step? Thanks!
Hi,
I have to use "window.confirm(……)" in the Lightning page to confirm, is there anything like "showToast" window in the Lightning or any other solutions?