Using GP Web Service: How do I delete a SalesOrderLine from a SalesOrder? - microsoft-dynamics

Can someone help me delete a SalesOrderLine from a SalesOrder?
I'm using the GP WS Native Endpoint
My code executes without an error.
However, after updating the SalesOrder, the line I removed still remains.
var salesDocumentKeyObject = new SalesDocumentKey {Id = salesDocumentKey, CompanyKey = this.CompanyKey};
var salesOrder = this.DynamicsGpClient.GetSalesOrderByKey(salesDocumentKeyObject, this.Context);
var newLines = salesOrder.Lines.Where(l => l.Key.LineSequenceNumber != lineItemSequence).ToArray();
salesOrder.Lines = newLines;
var salesOrderUpdatePolicy = this.DynamicsGpClient.GetPolicyByOperation("UpdateSalesOrder", this.Context);
this.DynamicsGpClient.UpdateSalesOrder(salesOrder, this.Context, salesOrderUpdatePolicy);
Thank you for any help,
Karl

Microsoft Dynamics GP Web Service has poor documentation and examples.
Do delete a sales order line, you retrieve the order, locate the line to delete and set the sales order line property, DeleteOnUpdate to true, and then save the order.
Updated code below:
var salesDocumentKeyObject = new SalesDocumentKey {Id = salesDocumentKey, CompanyKey = this.CompanyKey};
var salesOrder = this.DynamicsGpClient.GetSalesOrderByKey(salesDocumentKeyObject, this.Context);
var target= salesOrder.Lines.FirstOrDefault(l => l.Key.LineSequenceNumber == lineItemSequence);
if (target != null) {
target.DeleteOnUpdate = true;
}
var salesOrderUpdatePolicy = this.DynamicsGpClient.GetPolicyByOperation("UpdateSalesOrder", this.Context);
this.DynamicsGpClient.UpdateSalesOrder(salesOrder, this.Context, salesOrderUpdatePolicy);

Related

SharePoint WebsInfo Description is always Null

I'm trying to get the Description of a Site but it's always null in WebsInfo! Can someone please help me understand this? I also tried using OpenWeb but that was messing up the URL that I passed in.
var site = new SPSite(currentWeb.Url);
string url = currentWeb.Url + #"/" + siteName;
var webObject = site.AllWebs;
foreach (var web in webObject.WebsInfo)
{
siteDescription = web.Description;
}
I guess there is a bug in the WebsInfo that has never been resolved!! I ended up using SPWebCollection.
//This will find the current URL and iterate through it's site Collection
var oSiteCollection = new SPSite(SPContext.Current.Web.Url);
//Gets all webs meaning sub webs and their webs.
var collWebsites = oSiteCollection.AllWebs;
foreach (SPWeb web in collWebsites)
{
if (web.ServerRelativeUrl.StartsWith(kpi.BusinessUnitUrl))
{
kpi.BusinessUnitDescription = web.Description;
kpi.SiteSpecificAreaDescription = web.Description;
var collLists = web.Lists;
IterateLists(collLists, false, ref kpi);
}
}

PowerBIClient does not have any value

I am trying to read powerbi report using powerbi SDk. I got correct access token (tested in postman). Same access token is passed for TokenCredentials. but not getting any value in _powerBIClient. it has no value. I'm using below code.
var functionCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_configuration[BotConfigurationEnum.FunctionClientId.GetDescription()], _configuration[BotConfigurationEnum.FunctionClientSecret.GetDescription()]);
var userAssertion = (!string.IsNullOrWhiteSpace(token)) ? new Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer") : null;
var context = new AuthenticationContext("https://login.microsoftonline.com/{tenentid}");
var res = await context.AcquireTokenAsync("https://analysis.windows.net/powerbi/api",
functionCred, userAssertion);
var tokenCredentials = new TokenCredentials(res.AccessToken, "Bearer");
var _powerBIClient = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials);
var pbiReport = _powerBIClient.Reports.GetReport(reportId);
there was small correction in my code.. I have removed '/' in new Uri and it worked. I know its silly..
var _powerBIClient = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials);

How to get current filters from PowerBi embedded export report

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);
}

Has anyone got a guide on how to upgrade from PowerBi Embeded v2 to v3? Or a tutorial for v3?

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);

CRM 2013: Passing Account Info into Webservice via Plugin

We are using CRM 2013. I'm trying to create a plugin that triggers when a CRM Account is created. Then the plugin will fires and sends an attribute 'AccountNumber' into an internal webservice. However the webservice does not seem to get called whatsoever now.
At first I thought I had to do a PostImage, but then decided not to use it anymore. Also at first I was using "EntityMoniker" as a plugin parameter but then corrected it to type "Target".
Here's my code:
Could someone please guide me in the right direction?
var targetEntity = context.GetParameterCollection<Entity>(context.InputParameters,
"Target");
if (targetEntity == null)
{throw new InvalidPluginExecutionException(OperationStatus.Failed,
"Target Entity cannot be null");}
// Make sure the new Account Id is available
if (!context.OutputParameters.Contains("id"))
{return;}
var accountID = new Guid(context.OutputParameters["id"].ToString());
//putting postImage here but not being used
var postImage = context.PostEntityImages["PostImage"];
if (postImage == null)
{throw new InvalidPluginExecutionException(OperationStatus.Failed,
"Post Image is required");}
var AccountNumber = context.OutputParameters["new_AccountNumber"].ToString();
var service = new ServiceClient("");
var newProp = new PropertySetup
{
_prop = new Property
{
_propertyNm = AccountNumber
}
};
service.CreateNewProperty(newProp);
service.Close();
To get the new_AccountNumber attribute change:
var AccountNumber = context.OutputParameters["new_AccountNumber"].ToString();
to
var AccountNumber = targetEntity.Attributes["new_AccountNumber"].ToString();