I'm trying to reproduce the Activities page in Microsoft CRM 4.0 via web services. I can retrieve a list of activities, and I believe I need to use ActivityPointers to retrieve the entities but have so far been unsuccessful. Would I need to loop through every single entity returned from the first query to retrieve the ActivityPointer for it? And if so, how would I then get the "Regarding" field or Subject of the activity (eg: email).
The code to retrieve the activities is:
var svc = GetCrmService();
var cols = new ColumnSet();
cols.Attributes = new[] { "activityid", "addressused", "scheduledstart", "scheduledend", "partyid", "activitypartyid", "participationtypemask", "ownerid" };
var query = new QueryExpression();
query.EntityName = EntityName.activityparty.ToString();
query.ColumnSet = cols;
LinkEntity link = new LinkEntity();
//link.LinkCriteria = filter;
link.LinkFromEntityName = EntityName.activitypointer.ToString();
link.LinkFromAttributeName = "activityid";
link.LinkToEntityName = EntityName.activityparty.ToString();
link.LinkToAttributeName = "activityid";
query.LinkEntities = new[] {link};
var activities = svc.RetrieveMultiple(query);
var entities = new List<ICWebServices.activityparty>();
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse) svc.Execute(request);
//var pointers = new List<activitypointer>();
foreach (activityparty c in activities.BusinessEntities)
{
entities.Add(((activityparty)c));
//the entities don't seem to contain a link to the email which they came from
}
Not sure if I understand your problem, but the field "activityid" in the activitypointer object is the same activityid as the underlying activity (email, task, phonecall, etc). The regardingobjectid is the link to the regarding entity.
Heres what you need to get the equivalent of the Activities page
ColumnSet cols = new ColumnSet()
{
Attributes = new string[] { "subject", "regardingobjectid", "regardingobjectidname", "regardingobjectidtypecode", "activitytypecodename", "createdon", "scheduledstart", "scheduledend" }
};
ConditionExpression condition = new ConditionExpression()
{
AttributeName = "ownerid",
Operator = ConditionOperator.Equal,
Values = new object[] { CurrentUser.systemuserid.Value } //CurrentUser is an systemuser object that represents the current user (WhoAmIRequest)
};
FilterExpression filter = new FilterExpression()
{
Conditions = new ConditionExpression[] { condition },
FilterOperator = LogicalOperator.And
};
QueryExpression query = new QueryExpression()
{
EntityName = EntityName.activitypointer.ToString(),
ColumnSet = cols,
Criteria = filter
};
BusinessEntityCollection activities = svc.RetrieveMultiple(query);
foreach (activitypointer activity in activities)
{
//do something with the activity
//or get the email object
email originalEmail = (email)svc.Retrieve(EntityName.email.ToString(), activity.activityid.Value, new AllColumns());
}
Related
I am using WSO2 IS 5.10 version. As per requirement we can add and remove new roles form our application and call the following API to update groups with users. I am doing thi sas bulk operation as some time it requires to update as bulk. Even for 1 role update it takes 6 seconds where no of users are 30-40 k and in production where users are 90-95 k takes more than 12 seconds.
Is there any way to update in less time. Am I not following the correct way. Please suggest.
foreach (var role in roles)
{
var groupBulkOperation = new WSO2GroupBulkSCIMResourceOperationSchema();
groupBulkOperation.BulkId = Guid.NewGuid().ToString();
groupBulkOperation.Method = "PATCH";
groupBulkOperation.Path = "/Groups/" + role.value;
groupBulkOperation.Data = new WSO2GroupBulkSCIMResourceDataSchema
{
Operations = new List<WSO2GroupOperationSchema>
{
new WSO2GroupOperationSchema
{
op = "add",
path = "members",
value = new List<Members>
{
new Members
{
display = userName,
value = userId
}
}
}
}
};
requestModel.Operations.Add(groupBulkOperation);
}
var response = await CommonServiceResponceModel(
KeyObj.WSO2BaseURL + "scim2/Bulk",
Method.POST,
SerializeObject(requestModel)
I am using powerbi embedded and I would like an export button similar to the one used on powerbi.com, that asks if you want to apply the current filters or not.
How can I get the current filters in javaScript in such a way that these can be passed to the back end, or to the javascript api to generate a PDF?
I am using the following code to generate the PDF currently, I just don't know how to get the current configuration current filters and current page selected in javaScript
public PowerBiExportViewModel CreateExport(Guid groupId,
Guid reportId,
IEnumerable<PowerBiReportPage> reportPages,
FileFormat fileFormat,
string urlFilter,
TimeSpan timeOut)
{
var errorMessage = string.Empty;
Stream stream = null;
var fileSuffix = string.Empty;
var securityToken = GetAccessToken();
using (var client = new PowerBIClient(new Uri(BaseAddress), new TokenCredentials(securityToken, "Bearer")))
{
var powerBiReportExportConfiguration = new PowerBIReportExportConfiguration
{
Settings = new ExportReportSettings
{
Locale = "en-gb",
IncludeHiddenPages = false
},
Pages = reportPages?.Select(pn => new ExportReportPage { PageName = pn.Name }).ToList(),
ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
};
var exportRequest = new ExportReportRequest
{
Format = fileFormat,
PowerBIReportConfiguration = powerBiReportExportConfiguration
};
var export = client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest).Result;
You can go to PowerBi playground and play around with their sample report. Next to "Embed" button you have "Interact" and option to get filters. In response you get JSON with filters. If you are too lazy to go there, here is the code it created for me
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Get a reference to the embedded report.
report = powerbi.get(embedContainer);
// Get the filters applied to the report.
try {
const filters = await report.getFilters();
Log.log(filters);
}
catch (errors) {
Log.log(errors);
}
I am creating teams event using Graph API in my Azure function. For 10-30 members, I am able to create an event in MS Teams using Graph. It is sending an email notification also to the members for Join meeting.
When I tried with 50-100 members, multiple events getting created and multiple email notification also sending to each member.
Is there any member limitation or my code issue?
DateTime dStartDate = DateTime.Parse(session.SessionStartDateTime);
DateTime dEndDate = DateTime.Parse(session.SessionEndDateTime);
List<Microsoft.Graph.DayOfWeek> dayOfWeeks = new List<Microsoft.Graph.DayOfWeek>();
dayOfWeeks.Add(Microsoft.Graph.DayOfWeek.Monday);
dayOfWeeks.Add(Microsoft.Graph.DayOfWeek.Tuesday);
Event #event = new Event
{
Subject = "Test Meeting",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Online Meeting - Test Meeting"
},
Start = new DateTimeTimeZone
{
DateTime = session.StartDateStartTime,
TimeZone = "Eastern Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = session.StartDateEndTime,
TimeZone = "Eastern Standard Time"
},
Location = new Location
{
DisplayName = "Online"
},
Recurrence = new PatternedRecurrence
{
Pattern = new RecurrencePattern
{
Type = Weekly,
Interval = 1,
DaysOfWeek = dayOfWeeks
},
Range = new RecurrenceRange
{
Type = EndDate,
StartDate = new Date(dStartDate.Year, dStartDate.Month, dStartDate.Day),
EndDate = new Date(dEndDate.Year, dEndDate.Month, dEndDate.Day)
}
};
IsOnlineMeeting = true,
OnlineMeetingProvider = "TeamsForBusiness"
};
List<Attendee> attendees = new List<Attendee>();
if (session?.instructors?.Count > 0)
{
session.instructors.ForEach(s =>
{
attendees.Add(new Attendee
{
EmailAddress = new EmailAddress
{
Address = s.Email,
Name = s.Name
},
Type = AttendeeType.Required
});
});
}
if (session?.shoppers?.Count > 0)
{
session.shoppers.ForEach(s =>
{
attendees.Add(new Attendee
{
EmailAddress = new EmailAddress
{
Address = s.Email,
Name = s.Name
},
Type = AttendeeType.Required
});
});
}
#event.Attendees = attendees;
GraphServiceClient graph = GetAuthenticatedClient(session.tenantADInformation);
Event #event = PrepareEvent(session);
string Email = session.instructors.FirstOrDefault()?.Email;
var Event = await graph.Users[Email].Events
.Request()
.Header("Prefer", "outlook.timezone=\"" + session.TenantTimeZone + "\"")
.AddAsync(#event);
If it is 50-100 attendees then my Event is having Event.IsOnlineMeeting as false(even though I have set that to true) and Event.OnlineMeeting is coming as null.
Can anyone help?
I don't think exist any limitation in this case. Since the api allows us to create the event for the members, we can request it although there are many members. The only factor which may limit it is the max number of members in teams is 500. In addition to this, I think the api and the code can work fine.
This appears to be a nightmare, sure its easy to upgrade the nuget package to 3.11 I think the latest is, but then nothing at all compiles. So you fix the compile errors, and then it doesn't work. I'm getting an error when it tries to create the PowerBI client.
Getting the token and also creating the client appears to be totally different to v2.
This is my code:
public PowerBiConfig GetPowerBiConfig(string reportId)
{
var result = new PowerBiConfig();
try
{
if (!Guid.TryParse(reportId, out var _))
{
result.ErrorMessage = $"Invalid report guid: {reportId}";
return result;
}
var credential = new UserPasswordCredential(_powerBiProMasterUsername, _powerBiProMasterPassword);
var authenticationContext = new AuthenticationContext(AuthorityUrl);
// Taken from https://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously
var authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, dataArchiverSettings.PowerBiApplicationId, credential).GetAwaiter().GetResult();
if (authenticationResult == null)
{
result.ErrorMessage = "Authentication Failed.";
return result;
}
var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
var report = client.Reports.GetReportInGroup(dataArchiverSettings.PowerBiWorkspaceId, reportId);
if (report == null)
{
result.ErrorMessage = $"No report with the ID {reportId} was found in the workspace.";
return result;
}
var datasets = client.Datasets.GetDatasetById(dataArchiverSettings.PowerBiWorkspaceId, report.DatasetId);
result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
GenerateTokenRequest tokenRequest;
if (datasets.IsEffectiveIdentityRequired == true)
{
var username = UserHelper.GetCurrentUser();
var roles = _userService.GetRolesForUser(username);
tokenRequest = new GenerateTokenRequest(accessLevel: "view",
identities: new List<EffectiveIdentity>
{
new EffectiveIdentity(username: username,
roles: new List<string> (roles.Select(x=> x.RoleName)),
datasets: new List<string> {datasets.Id})
});
}
else
{
tokenRequest = new GenerateTokenRequest(accessLevel: "view");
}
var tokenResponse =
client.Reports.GenerateTokenInGroup(dataArchiverSettings.PowerBiWorkspaceId, report.Id,
tokenRequest);
if (tokenResponse == null)
{
result.ErrorMessage = "Failed to generate embed token.";
return result;
}
// Generate Embed Configuration.
result.EmbedToken = tokenResponse;
result.EmbedUrl = report.EmbedUrl;
result.Id = report.Id.ToString();
result.WorkloadResourceName = dataArchiverSettings.PowerBiWorkloadResourceName.Trim();
}
}
catch (HttpOperationException exc)
{
result.ErrorMessage =
$"Status: {exc.Response.StatusCode} ({(int)exc.Response.StatusCode})\r\n" +
$"Response: {exc.Response.Content}\r\n" +
$"RequestId: {exc.Response.Headers["RequestId"].FirstOrDefault()}";
}
catch (Exception exc)
{
result.ErrorMessage = exc.ToString();
}
return result;
}
The closest to "upgrade guide" is the announcement in Power BI blog. It looks like your code is using v2 (e.g. reportId is string, while in v3 it should be Guid).
Here is a brief summary of the changes:
What you should know about v3
Here are the key changes with this version update:
Namespaces renaming:
Microsoft.PowerBI.Api.V2 was changed to Microsoft.PowerBI.Api
Microsoft.PowerBI.Api.Extensions.V2 was changed to Microsoft.PowerBI.Api.Extensions
Microsoft.PowerBI.Api.V1 namespace was removed.
SetAllConnections and SetAllConnectionsInGroup operations are deprecated and marked as obsolete. You should use UpdateDatasources or UpdateParameters APIs instead.
PowerBI artifacts IDs typing was changed* from string to Guid, we recommend to work with Guid when possible.
*Dataset ID is an exception and it’s typing will remain string.
ODataResponse[List[Object]] types was changed to Objects, thus returning an objects collection on responses. For example, a response of ODataResponse[List[Report]] type will now return Reports collection as the return type.
New credentials classes allow easier build of credentialDetails. The new classes include: BasicCredentials, WindowsCredentials, OAuth2Credentials, and more.
Read Configure credentials article to learn more.
New encryption helper classes for easier encryption when creating CredentialDetails.
For example, using AsymmetricKeyEncryptor class with a gateway public key:
GatewayPublicKey publicKey = new GatewayPublicKey
{
Exponent = "...",
Modulus = "..."
};
CredentialsBase credentials = new BasicCredentials("<USER>", "<PASSWORD>");
var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey);
var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.None, EncryptedConnection.Encrypted, credentialsEncryptor);
Read Configure credentials article to learn more.
Consistency on field names.
For example, reportKey, datasetKey, dashboardKey and tileKey was changed to reportId, datasetId, dashboardId and tileId.
Consistency on operations names.
For example, use GetDataset instead of GetDatasetById. The effected opertation names are imports, datasets, gateways and datasources.
Use enum class instead of string for enumerated types.
For example, In the generateTokenRequest, we recommend to use TokenAccessLevel.View, and not explicitly use “view” as value.
Required fields was marked – some fields was changed to required fields are not nullable anymore.
Examples
Change in Get Reports call if WorkspaceId is a string:
var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);
var reports = await client.Reports.GetReportsInGroupAsync(new Guid( WorkspaceId ) );
Change in response handling if a string is expected:
report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
report = reports.Value.FirstOrDefault(r => r.Id .ToString() .Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
Change in Generate token:
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync( new Guid( WorkspaceId ), report.Id, generateTokenRequestParameters);
Change in Generate token response handling if a string is expected:
m_embedConfig.Id = report.Id;
m_embedConfig.Id = report.Id .ToString() ;
Required fields are not nullable, i.e. Expiration is not nullable and the Value property should be removed:
var minutesToExpiration = EmbedToken.Expiration .Value – DateTime.UtcNow;
var minutesToExpiration = EmbedToken.Expiration – DateTime.UtcNow;
Consistency on operations names, i.e. use GetDataset instead of GetDatasetById:
var datasets = await client.Datasets.GetDataset ById InGroupAsync(WorkspaceId, report.DatasetId);
var datasets = await client.Datasets.GetDatasetInGroupAsync(new Guid(WorkspaceId), report.DatasetId);
I am using SolrNet to do query on my default search field and not on any specific field. How can I use Boost on a specific field in that case? Below is the code snippet.
List filter = BuildQuerySingleLine(arrParams);
var customer = solr.Query(parameters.SingleLineSearch, new QueryOptions
{
FilterQueries = filter,
SpellCheck = new SpellCheckingParameters { Collate = true },
OrderBy = new[] { new SortOrder("score", Order.DESC), SortOrder.Parse("score DESC") },
StartOrCursor = new StartOrCursor.Start(parameters.StartIndex),
Rows = parameters.NumberOfRows
});
At last I found the solution to this problem. For this I have used dismax request handler and passed the qf param value through SOLRNET.
With this you can pass the dynamic boost value to the SOLR query, on different fields.
var extraParams = new Dictionary<string, string> { { "qt", "dismax" }, { "qf", "fieldName^1 FieldName^0.6" } };
var customer = solr.Query(parameters.SingleLineSearch, new QueryOptions
{
StartOrCursor = new StartOrCursor.Start(parameters.StartIndex),
Rows = parameters.NumberOfRows,
},
ExtraParams = extraParams
});
According to this document: Querying and The DisMax Query Parser
var extraParams = new List<KeyValuePair<string, string>>();
extraParams.Add(new KeyValuePair<string, string>("bq", "SomeQuery^10"));
extraParams.Add(new KeyValuePair<string, string>("bq", "SomeOtherQuery^10"));
var options new new QueryOptions();
options.ExtraParams = extraParams; //Since my List implements the right interface
solr.Query(myQuery, options)
the bq parameter should be used to boost the Query. #Abhijit Guha has an excellent answer, to use the same idea on the Field: qf (Query fields with optional boosts)
QueryOptions options = new QueryOptions
{
ExtraParams = new KeyValuePair<string, string>[]
{
new KeyValuePair<string,string>("qt", "dismax"),
new KeyValuePair<string,string>("qf", "title^1")
},
Rows = 10,
Start = 0
};
Thank You!