Cast Exception When Using Foreach on Microsoft.SharePoint.Client.ListCollection - service

I have exhausted my resources on this issue. I'm hoping you all can assist me.
I have an agent polling Microsoft O365 for list collections in order to walk through all the lists in a given site. Here is the code:
Microsoft.SharePoint.Client = CSOM
ListCollection lists = CSOM.web.Lists;
clientContext.Load(lists);
clientContext.ExecuteQuery();
try
{
foreach(CSOM.List list in lists
{
do.stuff()
}
}
catch(Excetion ex)
{
// I get this excetpion in my log at CSOM.List after 'in lists' is read.
/*System.InvalidCastException: Unable to cast object of type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
to type 'Microsoft.SharePoint.Client.List'.*/
}
When in debug and tracing through the code ex appears 'null', but I still get the excetion in my debug logs when I write ex.ToString() to a log file.
I am using .Net 4.6. This code has worked before, during dev tests, but wont work running in a service. I can't find any Namespace issues. The O365 account I amusing has 2FA disabled and has admin rights. Any thoughts would be very helpful. Thank you.

Related

Mongo Aggregation to replace Java 8 Streaming

I am new to "Mongodb". I have the following java code where I find an list of permission and from each permission I trying to get the list of actions that contains this uuid. How can I write the equivalent in JPA for Mongodb aggregation. The problem with the current code is that I get out of memory errors because if the document Permission table is big my java code will get out of memory issue.
Any help or hint would be greatly appreciated it!!
`
List<PermissionEntity> permissionEntities = permissionRepository.findAll();
if (!ObjectUtils.isEmpty(permissionEntities)) {
Optional<PermissionEntity> permission = permissionEntities.stream().filter(permissionEntity ->
permissionEntity.getActions()!= null && permissionEntity.getActions().contains(uuid)
).findAny();
if (!ObjectUtils.isEmpty(permission)) {
throw new ResponseStatusException( HttpStatus.CONFLICT, "EndPoint in use");
}
actionRepository.deleteByUuid(uuid);
}
`
I wrote it in Java and I trying to write it in JPA.

Error handling in extensions to visual studio code

Can someone point me to best practices for error handling in a Visual Studio Code extension?
I'm writing an extension in TypeScript that contributes a debugger. I want to log unexpected behavior, sometimes as information to the user explaining that something didn't go right, sometimes to create a trail for debugging, but certainly not to fail silently. Using console.log or console.error shows up in the debug output when I am debugging the extension, but I can't find it when the extension is installed. Do I have to open an output channel specifically for my extension and write everything there? Should I be throwing up showInformationMessage and showErrorMessage windows? Should I just be throwing exceptions and hope that code will do the right thing?
In my extension I use two ways for feedback. One is an output channel for errors produced by an external process that I'm using for the work.
Create the channel in your activation method:
outputChannel = window.createOutputChannel("ANTLR4 Errors");
and push output to it whenever you have something:
} catch (reason) {
outputChannel.appendLine("Cannot parse sentence generation config file:");
outputChannel.appendLine((reason as SyntaxError).message);
outputChannel.show(true);
return;
}
The other one is what you already considered:
if (workspace.getConfiguration("antlr4.generation").mode === "none") {
void window.showErrorMessage("Interpreter data generation is disabled in the preferences (see " +
"'antlr4.generation'). Set this at least to 'internal' to enable debugging.");
return null;
}
which is for messages I create in the extension and that users need to see and take seriously.

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.

Error calling Exchange Powershell command remotely in code (c#)

I'm posting the problem and the solution. I would have loved to know this half a day ago.
The error:
"The WriteObject and WriteError methods cannot be called from outside
the overrides of the BeginProcessing, ProcessRecord, and EndProcessing
methods, and only from that same thread. Validate that the cmdlet
makes these calls correctly, or please contact Microsoft Support
Services."
The bug:
foreach (KeyValuePair<string, string> cp in args.CP)
{
command.AddCommand(args.Command);
command.AddParameter(cp.Key, cp.Value);
}
Solved, Solution:
command.AddCommand(args.Command);
foreach (KeyValuePair<string, string> cp in args.CP)
{
command.AddParameter(cp.Key, cp.Value);
}
The error still doesn't make since to me. I went off on a tangent looking at PS async stuff.
Hope this helps others...

How to fix issues when MSCRM Plugin Registration fails

When you register a plug-in in Microsoft CRM all kinds of things can go wrong. Most commonly, the error I get is "An error occurred."
When you look for more detail you just get: "Server was unable to process request" and under detail you see "An unexpected error occurred."
Not very helpful. However, there are some good answers out there if you really dig. Anybody out there encountered this and how do you fix it?
The most common issue is that the meta parameter names must match.
For example:
public static DependencyProperty householdProperty = DependencyProperty.Register("household", typeof(Microsoft.Crm.Sdk.Lookup), typeof(AssignHouseholds));
[CrmInput("AccountId")]
[CrmReferenceTarget("account")]
public Microsoft.Crm.Sdk.Lookup household
{
get
{
return (Microsoft.Crm.Sdk.Lookup)base.GetValue(accountidProperty);
}
set
{
base.SetValue(accountidProperty, value);
}
}
Note the name after DependencyProperty (housedProperty) must exactly match the string after DependencyProperty.Register (in this case ("household") with the word "Property" appended.
Also, that value must match the value of public variabletype (in this case "household"). If any one of them don't match, it will error.
This is by design and is how MSCRM ties the values together.
A common cause is that your CRM SDK references must use the 64 bit version if you are on a 64 bit machine.
These will be located at
C:\sdk\bin\64bit\microsoft.crm.sdk.dll
and
C:\sdk\bin\64bit\microsoft.crm.sdktypeproxy.dll
if you installed the sdk to C:\sdk.
Also your build settings should be set to "Any CPU" under Project properties->Build.
You may also need to move the two dlls to your debug or release folder before you build.