Dynamics CRM 2011 plugin set custom field value - plugins

I have Dynamics CRM 2011 plugin (retrieve, post-action) which should simply set the value of custom field when retrieving Contact entity:
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = PluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.OutputParameters != null)
{
Entity entity = (Entity)context.OutputParameters["BusinessEntity"];
if (entity.Attributes.ContainsKey("new_markerexists") == false)
return;
entity["new_markerexists"] = "Marker exists.";
However, CRM plugin can not find this or any other custom field. It works fine with the standard fields.
What am I missing here?
Thanks!

As stated here: https://stackoverflow.com/a/9903306/1023562
In CRM, only properties that have been set or updated are included.
My custom fields did not have any value set, so CRM simply did not include them in entity.Attributes collection.

If your custom field is empty then it will not add the field in the attribute collection. If you want to get the Custom field you will must have to provide some value to it. I have tested and it is working.

Related

Why is my update in my plugin on my custom entity not occurring?

I'm writing an auto number plugin for MS Dynamics CRM 2015. It works on the creation of an opportunity, when a new number needs to be generated. The current number is stored in another entity, which is retrieved at the time of creating the opportunity and then adds 1. The auto number entity is then updated with the new number (except it isn't as this isn't working at the moment).
At the moment the number is retrieved and 1 is added to it and is used in the opportunity correctly. However, as the update to the auto number entity does not occur when another opportunity is created it gets the same number as the previous one.
Here's my plugin code so far:
protected void ExecuteGenerateOpportunityAutoNumber(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == OPPORTUNITY_ENTITY_NAME)
{
if (!entity.Attributes.Contains(OPPORTUNITY_REF_ID))
{
try
{
string newId = RetrieveAndUpdateLastId(service);
entity.Attributes.Add(OPPORTUNITY_REF_ID, newId);
}
catch (FaultException ex)
{
throw new InvalidPluginExecutionException("GenerateOpportunityAutoNumber plugin error: ", ex);
//tracingService.Trace("GenerateOpportunityAutoNumber plugin error: {0}", ex.Message);
}
}
}
}
}
The RetrieveAndUpdateLastId method code is below:
private string RetrieveAndUpdateLastId(IOrganizationService service)
{
lock (lastIdentifierLock)
{
string result = null;
ColumnSet cols = new ColumnSet();
cols.AddColumns(LAST_REF_LAST_VALUE, LAST_REF_PRIMARY_KEY);
QueryExpression query = new QueryExpression();
query.ColumnSet = cols;
query.EntityName = LAST_REF_ENTITY_NAME;
EntityCollection ec = service.RetrieveMultiple(query);
if (ec.Entities.Count >= 1)
{
foreach (Entity identifier in ec.Entities)
{
if (identifier.Attributes.Contains(LAST_REF_LAST_VALUE))
{
int? lastValue = identifier[LAST_REF_LAST_VALUE] as int?;
if (lastValue != null)
{
string newValue = (lastValue.Value + 1).ToString().PadLeft(7, '0');
result = String.Format("SN{0}", newValue); //This is clearly happening as I'm getting the next number back.
identifier[LAST_REF_LAST_VALUE] = lastValue.Value + 1;
//Tried this also:
//identifier.Attributes.Remove(LAST_REF_LAST_VALUE);
//identifier.Attributes.Add(LAST_REF_LAST_VALUE, lastValue.Value + 1);
service.Update(identifier); //This doesn't seem to be happening.
break;
}
}
}
}
return result;
}
}
No error is thrown but the update of the auto number just isn't happening. I've checked the user I'm running this as has the required update privileges on the auto number entity as well. Any ideas?
UPDATE
After debugging I found that it was throwing an error that the Principal user is missing the prvWrite privilege. This would explain why the update isn't happening, but now raises another issue. I've setup the plugin to run as a specific user (one with the correct privileges), but the Guid of the 'Principal user' in the error was of the calling user. Why would it run as the calling user when I've set it up to use a specific user?
UPDATE 2
I think I may have found the issue but wonder if anyone else can confirm / shed some more light on this. It seems that according to this, the issue may lie with the user not being in a specific AD group, specifically
User account (A) needs the privilege prvActOnBehalfOfAnotherUser,
which is included in the Delegate role.
Alternately, for Active Directory directory service deployments only,
user account (A) under which the impersonation code is to run can be
added to the PrivUserGroup group in Active Directory. This group is
created by Microsoft Dynamics CRM during installation and setup. User
account (A) does not have to be associated with a licensed Microsoft
Dynamics CRM user. However, the user who is being impersonated (B)
must be a licensed Microsoft Dynamics CRM user.
For my purposes I think the user I'm trying to run as needs to be in PrivUserGroup in AD (which it's not), otherwise it defaults to the calling user.
UPDATE 3
I've been able to identify 2 fundamental problems. The first is as explained above, in that the context always runs as the calling user. The 2nd is that when either giving the calling user system admin privileges OR creating the IOrganizationService with a null parameter it still doesn't update. HOWEVER, and this seems very odd, these 2 scenarios DO work when profiling the plugin. Why would this be?
UPDATE 4
It seems I may have resolved the issue, though I'm not certain (hence why I've not written an answer as yet). As per the documentation we've added the user to be impersonated into the PrivUserGroup. The plugin now works. However, I don't understand why this is needed. Also, is this best practice in this scenario or have I done something that should never be done?
On a related note I also unregistered the plugin before deploying it this time, so I'm now wondering if this solved this issue. To confirm I've now removed the user from the PrivUserGroup in AD, but this takes some time (not sure exactly how long) to filter through apparently. If it still works then it looks like this actually resolved it. Do you normally need to unregister a plugin before re-deploying it to make sure it works?
UPDATE 5
Ok, so this if my final update. I'm not marking this as the answer as I'm not 100% certain, but it appears that removing the assembly using the plugin registration tool may have done the trick. From everything I've read you shouldn't need to unregister a plugin to redeploy, so my perhaps my assembly was corrupt somehow and by removing it and creating it again using the new assembly solve the issue. Unfortunately I don't have the original assembly to test with.
I would suggest to debug your plugin. Following article contains a video that describes how to debug plugins using Plugin Debugger and Plugin Regitration Tool - http://blogs.msdn.com/b/devkeydet/archive/2015/02/17/debug-crm-online-plugins.aspx
Updated How to have 2 instances of IOrganizationService for user context and system:
Open Plugin.cs file.
Locate following code:
internal IOrganizationService OrganizationService
{
get;
private set;
}
Add following code after:
internal IOrganizationService SystemOrganizationService
{
get;
private set;
}
Find following code:
// Use the factory to generate the Organization Service.
this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);
Add following code after:
this.SystemOrganizationService = factory.CreateOrganizationService(null);
Use this instance of IOrganizationService in the place where you need higher level of privileges.

SSRS CreateSubscription - setting Locale

We have a custom built application, based on silverlight, which manages our report subscriptions. The problem is that whenever you add a new subscription, it sets the Locale value in the Subscriptions table to 'en-US'.
When you create subscriptions directly in Report Manager, the value in the Locale field is determined by your browser language settings (this is exactly what we want to achieve).
We can't find a way to set the Locale field before we call the CreateSubscription method as it doesn't seem to accept the Locale parameter and it defaults to en-US (which I believe is a server setting).
Do you know of any way to set Locale when creating subscriptions in SSRS?
As far as I can see there is no way to do this; I've been using the service via C#.
I decided upon a solution of obtaining the language/locale of the report via the service, and then making the changes directly in the ReportServer database, as an UPDATE statement on the SubscriptionID.
To get the language/locale of the report I use something like:
private static void Main()
{
ReportingService2010 service = new ReportingService2010();
service.Url = "URL of service";
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
string reportItemPath = "Path of report";
string language = GetReportPropertyValue(service, reportItemPath, "Language", "en-GB");
// Create the subscription, then update the database using the returned SubscriptionID.
}
private static string GetReportPropertyValue(ReportingService2010 service, string itemPath, string propertyName, string defaultValue)
{
Property[] properties = service.GetProperties(itemPath, null);
if (properties.Any(p => p.Name == propertyName))
return properties.First(p => p.Name == propertyName).Value;
else
return defaultValue;
}
I haven't tried it via the SOAP API yet, but shouldn't it be possible to set the Accept-Language header?
I'm doing this when rendering reports in different languages. The language of each report is set to =User!Language.
When using WCF to access the reporting service, you can do (example as VB.NET)
Using oReportingService As New ReportingService2010SoapClient
oReportingService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation
Using oScope As OperationContextScope = New OperationContextScope(oReportingService.InnerChannel)
If i_oSubscription.Language IsNot Nothing Then
' Accept-Language
Dim oHttpRequestProperty As New HttpRequestMessageProperty
oHttpRequestProperty.Headers.Add(HttpRequestHeader.AcceptLanguage, i_oSubscription.Language)
OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = oHttpRequestProperty
End If
oReportingService.CreateSubscription(New ReportingService2010.TrustedUserHeader(), i_oSubscription.Path, oExtensionSettings, i_oSubscription.Description, "TimedSubscription", sMatchData, lstParameters.ToArray(), sSubscriptionId)
Return sSubscriptionId
End Using
End Using
Edit: This is the way I'm doing it myself and it seems to work :)
i_oSubscription is just a simple container with properties like Description
Note: this seems to work for the most part. However, the "Days" field in a MonthlyRecurrence is to be formatted locale-dependent (see: https://stackoverflow.com/questions/16011008/ssrs-monthlyrecurrence-formatting-for-different-languages)

Adding a custom/relate field in Email template in Sugarcrm

I have created a custom module named surveys which will be in many to many relationship with targets. I need to insert survey name while sending campaign mails to targets.
Currently I managed to populate survey module entities in insert variable by following the guide from adding a custom module in insert variable dropdownlist in email template but the issue is it will never parse the survey name and displays $survey_name in emails that are delivered.
Any help/guidance to sort this out.
I just added the answer to that forum. The sugarCrm EmailTemplate modules basically is a lot of code to get just few beans working (Accounts, Contacts, Leads, Users, Prospects), I get some templates working with other beans with this steps, this code is based on SugarCrm 6.0.2, class modules/Email.php details on the forum:
1) Let the Email.php create the own bean. Example: LOC510
if (... $_REQUEST['parent_type'] == 'Prospects' || TRUE)
2) Create an array of replace fields. Example: LOC521
foreach($bean->field_defs as $key => $field_def) {
$replace_fields ['$'.strtolower(get_class($bean).'_'.$field_def['name'])]
= $bean->$field_def['name'];
//example of fieldnames: $bug_name, $bug_type, $case_date_created, $case_name, etc...
}
3) Replace the fields on html template. Example: LOC545
$this->description_html = str_replace(array_keys($replace_fields), $replace_fields, $this->description_html);
3) Replace the fields on txt template. Example: LOC549
$this->description = str_replace(array_keys($replace_fields), $replace_fields, $this->description);

GWT Editor Framework: Drop Down List

I'm looking for someone to point me in the right direction (link) or provide a code example for implementing a drop down list for a many-to-one relationship using RequestFactory and the Editor framework in GWT. One of the models for my project has a many to one relationship:
#Entity
public class Book {
#ManyToOne
private Author author;
}
When I build the view to add/edit a book, I want to show a drop down list that can be used to choose which author wrote the book. How can this be done with the Editor framework?
For the drop-down list, you need a ValueListBox<AuthorProxy>, and it happens to be an editor of AuthorProxy, so all is well. But you then need to populate the list (setAcceptableValues), so you'll likely have to make a request to your server to load the list of authors.
Beware the setAcceptableValues automatically adds the current value (returned by getValue, and defaults to null) to the list (and setValue automatically adds the value to the list of acceptable values too if needed), so make sure you pass null as an acceptable value, or you call setValue with a value from the list before calling setAcceptableValues.
I know it's an old question but here's my two cents anyway.
I had some trouble with a similar scenario. The problem is that the acceptable values (AuthorProxy instances) were retrieved in a RequestContext different than the one the BookEditor used to edit a BookProxy.
The result is that the current AuthorProxy was always repeated in the ValueListBoxwhen I tried to edit a BookProxy object. After some research I found this post in the GWT Google group, where Thomas explained that
"EntityProxy#equals() actually compares their request-context and stableId()."
So, as I could not change my editing workflow, I chose to change the way the ValueListBox handled its values by setting a custom ProvidesKey that used a different object field in its comparison process.
My final solution is similar to this:
#UiFactory
#Ignore
ValueListBox<AuthorProxy> createValueListBox ()
{
return new ValueListBox<AuthorProxy>(new Renderer<AuthorProxy>()
{
...
}, new ProvidesKey<AuthorProxy>()
{
#Override
public Object getKey (AuthorProxy author)
{
return (author != null && author.getId() != null) ? author.getId() : Long.MIN_VALUE;
}
});
}
This solution seems ok to me. I hope it helps someone else.

Preventing Validation in Entity Framework 4

I'm using Entity Framework 4 and a Dynamic Data site to expose a bare-bones admin interface to a few users. Working pretty well in general, but I have run into this one problem on a couple of fields on my model.
Several tables have some audit-related fields - CreatedBy, CreatedDate, ModifiedBy, and ModifiedDate. These fields are required in the database and the associated models are marking the properties as non-nullable (all as it should be). However I am handing setting the values for these fields in code - the field templates for the field types mark these specific fields as disabled on the page, and in the SavingChanges event I set these fields to the appropriate values. All works great when I'm updating an existing item.
The problem comes in when I try to create a new item. I want these fields to remain empty on the page and be auto-populated by my code when submitted, but the Field Templates set up RequiredFieldValidators for these fields and won't let me submit them without a value. Normally this would be great, except that I want to prevent EF from validating these fields at the point of page submission.
I realize that I could mark the fields as nullable in the database and that would resolve the issue - it would probably even be just fine from the data standpoint, but I'm not comfortable with doing so - for one thing it's not unlikely that some of the models these fields appear on will be bulk loaded, possibly by someone else, at a later date. I would rather still have the database enforce the non-nullability of these fields. In the field templates I've tried moving the built-in SetUpValidator() call for the RequiredFieldValidator not to run when these specific fields are being loaded, and I've also tried disabling the RequiredFieldValidators and forcing their IsValid property to true. None of these actions allows me to submit the page.
Is there a way to tell EF/Dynamic Data to skip the validation for some fields?
EDIT
As noted below, I also tried marking them nullable in the model and not in the database, which caused an error: Problem in mapping fragments...Non-nullable column...in table...is mapped to a nullable entity property.
EDIT #2
I have found a solution that works, but requires modifying the auto-generated designer file for the entity set, which is fragile at best. I would love to know a "righter" way to do it, but if nothing becomes apparent in the next couple of days I'll post my own answer.
So here are the edits I found I had to make. When allowing the tool to create the entities in the edmx Designer.cs file I get properties like these:
for a datetime on the server side
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.DateTime CreatedDate
{
get
{
return _CreatedDate;
}
set
{
OnCreatedDateChanging(value);
ReportPropertyChanging("CreatedDate");
_CreatedDate = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CreatedDate");
OnCreatedDateChanged();
}
}
for a varchar
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String CreatedBy
{
get
{
return _CreatedBy;
}
set
{
OnCreatedByChanging(value);
ReportPropertyChanging("CreatedBy");
_CreatedBy = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("CreatedBy");
OnCreatedByChanged();
}
}
To make it work without validation for a DateTime property setting the IsNullable parameter of the EdmScalarPropertyAttribute to true is sufficient to avoid the issue. For the String property you also have to change the 2nd parameter of the SetValidValue method call to "true."
All of this said, the only reason that I'm leaving this as it is is because I don't expect to have to regenerated the entities more than once or twice before we move to a different platform for this site. And in this case, merging the version in I have checked in to git with the version generated by the tool allows me to avoid most of the headaches,
Here is my meta information for a read-only auto generated date field. I don't get validation controls validating these fields. Hope this helps.
[ReadOnly(true)]
[DataType(DataType.Date)]
[Column(IsDbGenerated = true, UpdateCheck = UpdateCheck.Never, AutoSync = AutoSync.Never)]
[UIHint("DateTime")]
[Display(Name = "Modified", Order = 1000)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public object DateModified { get; private set; }