Hello, I am posting chatter from flow, i want to change Chatter sender name to specific user name. How can i change the sender name of that chatter - apex-code

I am posting chatter from flow, chatter is posted by opportunity owner name, i want to change that and use custom field's user name. I am calling apex from flow to post this chatter. How can i change the sender name of that chatter.
`
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
ConnectApi.MentionSegmentInput mentionSegmentInput1 = new ConnectApi.MentionSegmentInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
for(Request requests:input)
{
for(Opportunity opps:opp)
{
if(opps.Status__c == 'Escalated'){
mentionSegmentInput1.id = '0057R00000AubfwQAB';
mentionSegmentInput.id = managerid;
}
messageBodyInput.messageSegments.add(mentionSegmentInput1);
messageBodyInput.messageSegments.add(mentionSegmentInput);
textSegmentInput.text = '\n ATTENTION: '+opps.owner.name+ '\n\n'+ 'Current project status:' +opps.Status__c +
'\n'+ 'Customer health score:' +opps.Health_score__c +
'\n\n'+ 'Update summary:' +opps.Status_Summary__c+
'\n\n'+ 'Next milestone:' +opps.Next_Milestone__c+
'\n'+ 'Milestone date: date:' +opps.Next_Milestone_Date__c;
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;
feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
feedItemInput.subjectId = opps.Id;
ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(null, feedItemInput);
//feedElement.header = opps.Customer_success_manager__c;
}
}
`

Related

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

What is the correct way to define models and their validation?

I want to create a supplier model i.e code, name, address, phone
I am also going to use the aurelia-validation classes.
Using them both together with the viewmodel - SupplierMaint.js & view - SupplierMaint.html is fine but I want to keep the Supplier model in another file so that I can use it in many places to ensure a consistent validation of values lengths etc.
How should I go about this?
I suspect the #NoView annotation might have something to do with it but I am not sure how to import the external file and wire it up to the submit & validation processing in the SupplierMaint.js
Bob
Models
This is how I do it -
export class Supplier {
name = '';
modelId = '';
constructor(data) {
Object.assign(this, data);
}
}
This let's anyone consume your model and create a new instance of it. The data that is passed in will override the default values you define, but if they do not you still have those default values.
Validation
Validation is currently in a state of flux. I'm hoping to be done with the initial refactoring work by the end of this weekend but here is a preview for what I propose as the best usage, feedback welcome.
import {ValidationReporter} from 'aurelia-validate';
export class PersonViewModel {
activePerson;
static inject = [ValidationReporter];
constructor(reporter) {
this.activePerson = new PersonModel({firstName: 'Lucky Luke'});
this.reporter = reporter.subscribe(validationErrors => {
// do something with validationErrors
});
}
}
class PersonModel {
#length({ minimum: 5, maximum: 25 }) firstName = 'Luke';
#required lastName = 'Skywalker';
#date lastUpdated = new Date();
#datetime lastTimeUpdated = new Date();
#email email = 'luke#skywalker.net';
#length({ minimum: 5, maximum: 25 }) password = 'equal';
#equality confirmPassword = 'equal';
#url website = 'http://www.google.com';
#numericality friendCount = 25;
#numericality({ noStrings: true }) age = 25;
constructor(data) {
Object.assign(this, data);
}
}

How to use a confirmation button in Google Apps Script spreadsheet embedded scripts?

I have this Google Apps Script to send an email with a request to people I choose in a spreadsheet:
function sendRequestEmail() {
var data = SpreadsheetApp.openById(SPREADSHEET);
if(!employee_ID) {
employee_ID = getCurrentRow();
if (employee_ID == 1) {
var employee_ID = Browser.inputBox("VocĂȘ precisa selecionar um assistido?", "Choose a row or type its number here:", Browser.Buttons.OK_CANCEL);
}
}
// Fetch variable names
// they are column names in the spreadsheet
var sheet = data.getSheets()[0];
var columns = getRowAsArray(sheet, 1);
Logger.log("Processing columns =" + columns);
var employeeData = getRowAsArray(sheet, employee_ID);
Logger.log("Processing employeeData = " + employeeData);
// Assume first column holds the name of the person
var email2Send = "pythonist#example.com";
var title = "Request by email";
var name = employeeData[0];
var mother_name = employeeData[1];
var message = "Hi, I have a request for you, " + name + ", this is... example";
// HERE THE
// CONFIRMATION BUTTON!!!
MailApp.sendEmail(email2Send, title, message);
}
And, before sending the email, I want a confirmation button, something like this:
function showConfirmation(name, email2Send) {
var app = UiApp.createApplication().setHeight(150).setWidth(250);
var msg = "Do you confirm the request to " + email2Send + " about " + name + "?";
app.setTitle("Confirmation of request");
app.add(app.createVerticalPanel().add(app.createLabel(msg)));
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
So, if user press OK, the app will execute the line MailApp.sendEmail(email2Send, title, message); and send an e-mail.
I have to admit my ignorance. I'm reading chapter 4 of the book "Google Apps Script" (Oreilly, by James Ferreira) on handlers. I've tried using an example provided in the documentation from Google (already deleted the code!). But I came across an error that I could not understand.
The code used were this sample:
var ui = DocumentApp.getUi();
var response = ui.prompt('Getting to know you', 'May I know your name?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response.getSelectedButton() == ui.Button.YES) ... DO THIS
I have some urgency in this simple project, so forgive-me for asking this question before research more for the answer (I'm searching for it while wating for the answer). So, how can I use a confirmation/cancellation button in this code?
The code snippet you showed is for document embedded UI, the equivalent (well... almost) class for spreadsheet context is Browser.MsgBox(prompt,buttons), see doc here, it will be simpler than create a Ui + a handler function... even if the layout and appearance are fairly basic it's easy and efficient.
In your code it becomes :
...
var confirm = Browser.msgBox('send confirmation','Are you sure you want to send this mail ?', Browser.Buttons.OK_CANCEL);
if(confirm=='ok'){ MailApp.sendEmail(email2Send, title, message)};
...

EWS Managed API : Checking Responses

I'm using EWS Managed API 2.0. I'm using the Calendaring part where you can book appointments as follows :
Appointment appointment = new Appointment(service);
//Set properties on the appointment.
appointment.Subject = "Dentist Appointment";
appointment.Body = "The appointment is with Dr. Smith.";
appointment.Start = new DateTime(2009, 3, 1, 9, 0, 0);
appointment.End = appointment.Start.AddHours(2);
//Save the appointment.
appointment.Save(SendInvitationsMode.SendToNone);
How can I using the API check the status of the booking and whether it was booked or not due to a conflict in the date (Success/Error/Conflict)? right now I'm able to check this through the outlook, but I'd like to know this information from the API. I've looked into the API documentation but I couldn't find anything.
Appreciate your help/guidance.
You should first check the availability of all attendees before saving your appointment. AvailabilityData will return you Result (ServiceResult.Success, ServiceResult.Warning, or ServiceResult.Error) and further you can check ErrorMessage property to find proper return message for each conflicting availability. If availability is not conflicting for any of the attendees, you can save your Appointment object.
AvailabilityOptions availabilityOptions = new AvailabilityOptions();
availabilityOptions.MeetingDuration = 60;
availabilityOptions.MaximumNonWorkHoursSuggestionsPerDay = 4;
availabilityOptions.MinimumSuggestionQuality = SuggestionQuality.Good;
availabilityOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;
List<AttendeeInfo> attendees = new List<AttendeeInfo>();
attendees.Add(
new AttendeeInfo()
{
SmtpAddress = "org#acme.com",
AttendeeType = MeetingAttendeeType.Organizer
});
attendees.Add(
new AttendeeInfo()
{
SmtpAddress = "at1#acme.com",
AttendeeType = MeetingAttendeeType.Required
});
attendees.Add(
new AttendeeInfo()
{
SmtpAddress = "room1#acme.com",
AttendeeType = MeetingAttendeeType.Room
});
GetUserAvailabilityResults availabilityResults =
service.GetUserAvailability(
attendees,
new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),
AvailabilityData.FreeBusyAndSuggestions,
availabilityOptions
);
// Here check the availability Result and ErrorMessage of each attendees
// availabilityResults.AttendeesAvailability[0].Result
// availabilityResults.AttendeesAvailability[0].ErrorMessage
// ServiceResult.Success
// ServiceResult.Warning
// ServiceResult.Error

How to create user properties with EWS or EWS Managed API so that they appear in field chooser

I would like to create User Properties using EWS so that they appear in the field chooser in Outlook. I know it's possible using VBA, the object model exposes an Item.UserProperties collection. However, using EWS I can only access Item.ExtendedProperty.
The issue with ExtendedProperty is that is doesn't appear in the selectable user properties list.
The underlying issue is that our server-side application tries to work nicely together with the Dynamics CRM Outlook Client. The CRM Outlook client uses UserProperty for storing custom properties and our application can only work with EWS and we cannot find a way to create user properties.
Some example code:
User Properties (VBA Outlook):
Dim WithEvents m_objApp As Outlook.AppointmentItem
Private Sub Application_ItemLoad(ByVal Item As Object)
If Item.Class = olAppointment Then
Set m_objApp = Item
End If
End Sub
Private Sub m_objApp_Open(Cancel As Boolean)
Dim oProp1 As UserProperty
Dim oProp2 As UserProperty
If m_objApp.UserProperties.Count = 0 Then
Set oProp1 = m_objApp.UserProperties.Add("crmid", olText)
oProp1.Value = ""
Set oProp2 = m_objApp.UserProperties.Add("crmLinkState", olText)
oProp2.Value = "0"
m_objApp.Save
End If
End Sub
Extended Properties (Exchange EWS):
CalendarItemType item = new CalendarItemType();
item.MeetingTimeZone = new TimeZoneType() { TimeZoneName = _userTimeZone };
item.StartSpecified = true;
item.Start = GetDateFromXml(node.Value);
item.EndSpecified = true;
item.End = GetDateFromXml(node.Value);
List<ExtendedPropertyType> properties = new List<ExtendedPropertyType>();
properties.Add(CreateExtendedProperty("crmid", pending.CrmId.Value.ToString(), MapiPropertyTypeType.String));
properties.Add(CreateExtendedProperty("crmLinkState", "2", MapiPropertyTypeType.Double));
item.ExtendedProperty = properties.ToArray();
CreateRequest createRequest = new CreateItemType()
{
Items = new NonEmptyArrayOfAllItemsType
{
Items = new ItemType[] { item }
},
SavedItemFolderId = new TargetFolderIdType()
{
Item = new DistinguishedFolderIdType()
{
Id = folder,
Mailbox = new EmailAddressType() { EmailAddress = _user.MailBox }
}
},
SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToNone,
SendMeetingInvitationsSpecified = true
};
CreateItemResponseType response = exchange.CreateItem(createRequest);
private ExtendedPropertyType CreateExtendedProperty(string name, string value, MapiPropertyTypeType type)
{
return new ExtendedPropertyType()
{
ExtendedFieldURI = new PathToExtendedFieldType()
{
PropertyName = name,
DistinguishedPropertySetId = DistinguishedPropertySetType.PublicStrings,
DistinguishedPropertySetIdSpecified = true,
PropertyType = type
},
Item = value
};
}
A similar question has been asked on a Microsoft forum almost a year ago, but no answer yet. http://social.technet.microsoft.com/Forums/en-NZ/exchangesvrdevelopment/thread/c4d6bbb9-ba6a-4aa4-9e39-98a52b733a8c
I was hoping SO would be more successful :)
Thanks,
Jeffry
I thought the two methods were equivalent as long as you used publicstrings (which it looks like you do). How about using MFCMAPI to see the difference in what's generated?

Resources