I have been wondering that how we could query to get list of Accounts which is Shared for a user. By using SDK I have tried the following methods but could not able to find out the proper solution:
QueryExpression query1 = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet("name", "address1_city")
};
query1.LinkEntities.Add(new LinkEntity("account", "systemuser", "ownerid", "systemuserid", JoinOperator.Inner));
query1.LinkEntities[0].Columns.AddColumns("fullname");
query1.LinkEntities[0].EntityAlias = "share";
I am new to CRM sdk working my head around this the whole day.
Can anyone please help?
Try using a RetrieveSharedPrincipalsAndAccessRequest.
MSDN.
var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest
{
Target = leadReference
};
// The RetrieveSharedPrincipalsAndAccessResponse returns an entity reference
// that has a LogicalName of "user" when returning access information for a
// "team."
var accessResponse = (RetrieveSharedPrincipalsAndAccessResponse)_serviceProxy.Execute(accessRequest);
Console.WriteLine("The following have the specified granted access to the lead.");
foreach (var principalAccess in accessResponse.PrincipalAccesses)
{
Console.WriteLine("\t{0}:\r\n\t\t{1}", GetEntityReferenceString(principalAccess.Principal), principalAccess.AccessMask);
}
Related
Context:
I am trying to add new team with more than one owner using MS Graph API in C#
Problem:
I am getting error message:
Adding more than one member is not supported.
If I add only one member (owner) the team is created. Error occures only for multiple members.
It seems to be impossible it is really not supported but I can't see what am I doing wrong.
My code:
var owners = model.Owners.Select(x => new AadUserConversationMember
{
Roles = new [] { "owner" },
UserId = x
});
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
var team = await graph.Teams.Request().AddAsync(newTeam);
model.Owners is a list of teams user ids (List<string>)
Yes, you cannot add multiple owners while creating a team. Only one owner is only supported in the above scenario. When you see anytime in the Microsoft Document "Not supported" means "it's not going to work, nor they tested to behave to work in other way". Hence, it's by design.
I'm generating Power BI embed token using C# SDK.
using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
{
var workspaceId = groupId.ToString();
var report = await client.Reports.GetReportInGroupAsync(workspaceId, reportId);
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponsex = await client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);
result.EmbedToken = tokenResponsex;
result.EmbedUrl = report.EmbedUrl;
result.Id = report.Id;
}
I need to pass a parameter for filtering. But couldn't find a straightforward way to do this.
How do I get this done?
You can use RLS in embedded reports implemented with app owns data scenario (a single master account for authentication) by passing EffectiveIdentity information when generating access token for this report with GenerateTokenInGroup.
To implement RLS in the report itself you need either to use USERPRINCIPALNAME() DAX function to filter the data, or define roles and filter the data based on them. If you implement it with roles, after publishing the report go to dataset's security settings and add users to the roles.
To generate the token by providing an effective identity and roles membership, use code like this:
var credentials = new TokenCredentials(accessToken, "Bearer");
using (var client = new PowerBIClient(new Uri("https://api.powerbi.com"), credentials))
{
var datasets = new List<string>() { datasetId }; // Dataset's GUID as a string
var roles = new List<string>();
roles.Add('ROLE1');
roles.Add('ROLE2');
roles.Add('ROLE3');
var effectiveIdentity = new EffectiveIdentity('user#example.com', datasets, roles);
var r = new GenerateTokenRequest("view", effectiveIdentity);
var token = client.Reports.GenerateTokenInGroup(groupId, reportId, r).Token;
}
I have seen example of creating Accounts Entity records, Contacts entity records through C#, i wanted to know how do we create a service record in CRM through C#(.net) code.
Eg: We already have "Plumbing service" record in service entity view. So i wanted to create a new record in service entity through C# code (early or late binding doesn't matter).
Can someone help me on this with code.
Quite some XML is required when creating this Services from code. Additionally, before you can create a Service you will need to create a ResourceSpec and a ConstraintBasedGroup.
First create a ConstraintBasedGroup:
var bu = context.BusinessUnitSet.First().ToEntityReference();
var cbg = new ConstraintBasedGroup
{
BusinessUnitId = bu,
Name = "CBG1",
Constraints = "<Constraints><Constraint><Expression><Body>false</Body><Parameters><Parameter name=\"resource\"/></Parameters></Expression></Constraint></Constraints>"
};
var cbgId = OrganizationService.Create(cbg);
Then create a ResourceSpec:
var resSpec = new ResourceSpec
{
BusinessUnitId = bu,
Name = "RS1",
RequiredCount = 1,
ObjectiveExpression = "<Expression><Body>udf\"Random\"(factory,resource,appointment,request,leftoffset,rightoffset)</Body><Parameters><Parameter name=\"factory\"/><Parameter name=\"resource\"/><Parameter name=\"appointment\"/><Parameter name=\"request\"/><Parameter name=\"leftoffset\"/><Parameter name=\"rightoffset\"/></Parameters><Properties EvaluationInterval=\"P0D\" evaluationcost=\"0\"/></Expression>",
GroupObjectId = cbgId
};
var resSpecId = OrganizationService.Create(resSpec);
And finally, you can create your Service:
var svc = new Service
{
Name = "Service1",
Granularity = "FREQ=MINUTELY;INTERVAL=15",
ResourceSpecId = new EntityReference(ResourceSpec.EntityLogicalName, resSpecId),
InitialStatusCode = new OptionSetValue(0),
Duration = 15
};
OrganizationService.Create(svc);
I would suggest you create similar things using the UI of CRM in case you are wondering about the specific formats of the XML you require. The XML I used in my examples is pretty much the default XML CRM generates.
I am working on a C# code that retrieves all site collection paths from a On-Premise Sharepoint 2013 server. I have the following Site Collections on the server:
/serverurl/
/serverurl/my
/serverurl/my/personal/site1
/serverurl/my/personal/site2
/serverurl/sites/TestSite
/serverurl/custompath/site3
when I run my code , I only get the following site collections:
/serverurl/
/serverurl/my
/serverurl/my/personal/site1
/serverurl/my/personal/site2
I was wondering why my search does not return all the site collections?
here is my code:
ClientContext context = new ClientContext(siteUrl);
var cred = new NetworkCredential(userName, password, domain);
context.Credentials = cred;
KeywordQuery query = new KeywordQuery(context);
query.QueryText = "contentclass:STS_Site";
SearchExecutor executor = new SearchExecutor(context);
query.TrimDuplicates = true;
var resultTable = executor.ExecuteQuery(query);
context.ExecuteQuery();
foreach (var row in resultTable.Value[0].ResultRows)
{
string siteName = row["siteName"] as string;
Console.WriteLine("Site Name: {0}", siteName);
}
Thanks!
I was having the same problem today. I found two solutions.
Regardless if your on-prem or on Office365 we can use Microsoft.Online.SharePoint.Client.Tenant dll. You can use this to get all the Site Collections. You do need your admins to run some power shell if your on-prem. Vesa was nice enough to write a blog about it here
Once you get that done, you can do something like the following (Note:I have not tested this method with a non Admin account) (solution taken from here) Sadly this one will not work for me as I want security trimming and this will code must be ran by a user with tenant read permissions which our users would not normal have.
var tenant = new Tenant(clientContext);
SPOSitePropertiesEnumerable spp = tenant.GetSiteProperties(0, true);
clientContext.Load(spp);
clientContext.ExecuteQuery();
foreach(SiteProperties sp in spp)
{
// you'll get your site collections here
}
I ended up doing this which gets back to using search, I still have a problem, we have well over 500 sites/webs so I'm working with our admins to see if we can increase the max rows search can return. However, the true secret here is TrimDuplicates being set to false, I don't know why SP thinks the results are dups, but it obviously does, so set it to false and you should see all your sits.
KeywordQuery query = new KeywordQuery(ctx);
query.QueryText = "contentclass:\"STS_Site\"";
query.RowLimit = 500;//max row limit is 500 for KeywordQuery
query.EnableStemming = true;
query.TrimDuplicates = false;
SearchExecutor searchExecutor = new SearchExecutor(ctx);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(query);
ctx.ExecuteQuery();
var data = results.Value.SelectMany(rs => rs.ResultRows.Select(r => r["Path"])).ToList();
Hope one of the two will work for you.
Working with CRM 2013, how can I get a list of all entities in the CRM via the connectionManager class? I want to get all the entities for the current connection.
Thank you for your comment and answer it work now,
this is my function
public static EntityMetadata[] GetEntities ( IOrganizationService organizationService)
{
Dictionary<string, string> attributesData = new Dictionary<string, string>();
RetrieveAllEntitiesRequest metaDataRequest = new RetrieveAllEntitiesRequest();
RetrieveAllEntitiesResponse metaDataResponse = new RetrieveAllEntitiesResponse();
metaDataRequest.EntityFilters = EntityFilters.Entity;
// Execute the request.
metaDataResponse = (RetrieveAllEntitiesResponse)organizationService.Execute(metaDataRequest);
var entities = metaDataResponse.EntityMetadata;
return entities;
}
and i call my function in the windows app form like this:
var allEntities = CRMHelpers.GetEntities(service);
foreach (EntityMetadata Entity in allEntities)
{
cbxEntity.Items.Add(Entity.LogicalName);
}
If you are looking for getting the entity metadata using code (C#) then we have inbuilt messages to get all entities and if required attribute level information as well. You can use the message "RetrieveAllEntitiesRequest". A sample code would be as follows to achieve the same.
RetrieveAllEntitiesRequest retrieveAllEntityRequest = new RetrieveAllEntitiesRequest
{
RetrieveAsIfPublished = true,
EntityFilters = EntityFilters.Attributes
};
RetrieveAllEntitiesResponse retrieveAllEntityResponse = (RetrieveAllEntitiesResponse)serviceProxy.Execute(retrieveAllEntityRequest);
If you need to get a specific entity information then you may use the message "RetrieveEntityRequest". A sample for the same would be as follows,
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Attributes,
LogicalName = entityName,
RetrieveAsIfPublished = true
};
RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)serviceProxy.Execute(entityRequest);
Hope this is what you were looking for. Let us know if you need any more information on the same.