Values seems changing straight after Initial Save in Dynamics CRM Opportunity - dynamics-crm-2011

I'm doing a Service Call to retrieve the Account details (currency, discount associated with the account) on the Selection of the Account lookup on the Opportunity form (form type == 1 // Create) using Web API in CRM 2016 On-Premise. Everything is working fine but when the opportunity is saved initially it's straight away coming up with unsaved changes next to the Save button after the initial save which is forcing me to do another save(abnormal behaviour).I'm not so sure what value is changing straightaway after initial save.
The Service Call is Synchronous and is being triggered on the change of the Account Lookup, well before the initial save. Any Help Appreciated!.
function SetOpportunityCurrencyAndDiscount(){
var accountId = (GetValue("vm_accountid"))[0].id;
var result = RetrieveRecord("account", null, accountId.slice(1,-1));
var accountDiscount = result["vm_accountdiscount"];
var transactionCurrencyId = result["_transactioncurrencyid_value"];
var currencyName = result["_transactioncurrencyid_value#OData.Community.Display.V1.FormattedValue"];
SetValue("vm_discount", accountDiscount);
Xrm.Page.getAttribute("transactioncurrencyid").setValue([{ id: transactionCurrencyId, name: currencyName, entityType: "transactioncurrency"}]); }
function RetrieveRecord(recordType, alternateKey, accountId){
var result = null;
var entityType = recordType;
var query = null;
if(alternateKey != null && agencyId == null)
query = "/api/data/v8.0/accounts(emailaddress1='"+alternateKey+"')?$select=name,accountid,_transactioncurrencyid_value,vm_agencydiscount";
else
query = "/api/data/v8.0/accounts("+agencyId+")?$select=name,accountid,_transactioncurrencyid_value,vm_agencydiscount";
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + query, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
result = JSON.parse(this.response);
}
else {
alert(this.statusText);
}
}
};
req.send();
return result;
}

After you save your record and the form is dirty again, open dev tools and paste this into the console. It will show you which fields are dirty.
function showDirtyFields() {
var Xrm = Array.prototype.slice.call(document.querySelectorAll('iframe')).filter(function(d) {
return d.style.visibility !== 'hidden';
})[0].contentWindow.Xrm;
var message='The following fields are dirty: \n';
Xrm.Page.data.entity.attributes.forEach(function(attribute,index){
if(attribute.getIsDirty()==true){message+="\u2219 "+attribute.getName()+"\n";}
});
Xrm.Utility.alertDialog(message);
}
showDirtyFields();
Another way of accomplishing the same thing is to turn on auditing for the entity. The audit log will show you which fields were submitted.

Related

How to configure the user_token of Damn Vulnerable Web Application within CSRF field while Script based authentication using ZAP?

I had been following the documentation of Script Based Authentication for Damn Vulnerable Web Application using ZAP. I have navigated to http://localhost/dvwa/login.php through Manual Explore which opens up the DVWA application on my localhost as follows:
and adds the URL to the Default Context.
I've also created the dvwa script with the following configuration:
and modified the dvwa script:
Now when I try Configure Context Authentication, dvwa script does gets loaded but the CSRF field doesn't shows up.
Additionally, POST Data doesn't even shows up but Extra POST Data is shown.
Am I missing something in the steps? Can someone help me out?
The modified script within the documentation of Script Based Authentication section for Damn Vulnerable Web Application using ZAP
seems incomplete.
The complete script is available at Setting up ZAP to Test Damn Vulnerable Web App (DVWA) which is as follows:
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("Login URL");
var csrfTokenName = paramsValues.get("CSRF Field");
var csrfTokenValue = extractInputFieldValue(getPageContent(helper, loginUrl), csrfTokenName);
var postData = paramsValues.get("POST Data");
postData = postData.replace('{%username%}', encodeURIComponent(credentials.getParam("Username")));
postData = postData.replace('{%password%}', encodeURIComponent(credentials.getParam("Password")));
postData = postData.replace('{%' + csrfTokenName + '%}', encodeURIComponent(csrfTokenValue));
var msg = sendAndReceive(helper, loginUrl, postData);
return msg;
}
function getRequiredParamsNames() {
return [ "Login URL", "CSRF Field", "POST Data" ];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return [ "Username", "Password" ];
}
function getPageContent(helper, url) {
var msg = sendAndReceive(helper, url);
return msg.getResponseBody().toString();
}
function sendAndReceive(helper, url, postData) {
var msg = helper.prepareMessage();
var method = "GET";
if (postData) {
method = "POST";
msg.setRequestBody(postData);
}
var requestUri = new org.apache.commons.httpclient.URI(url, true);
var requestHeader = new org.parosproxy.paros.network.HttpRequestHeader(method, requestUri, "HTTP/1.0");
msg.setRequestHeader(requestHeader);
helper.sendAndReceive(msg);
return msg;
}
function extractInputFieldValue(page, fieldName) {
// Rhino:
var src = new net.htmlparser.jericho.Source(page);
// Nashorn:
// var Source = Java.type("net.htmlparser.jericho.Source");
// var src = new Source(page);
var it = src.getAllElements('input').iterator();
while (it.hasNext()) {
var element = it.next();
if (element.getAttributeValue('name') == fieldName) {
return element.getAttributeValue('value');
}
}
return '';
}
Using this script, CSRF Field and POST Data field shows up just perfect.

NetSuite Record Type for [Web Service Operations] Saved Search

I have a Saved Search based on Web Services Operations. I'm trying to access the data through a RESTlet and I have a working script deployment. This thing I can't figure out is the correct search type. I've tried a whole load of combinations but still get this error:
[code] => INVALID_RCRD_TYPE
[message] => The record type [WEBSERVICESOPERATIONS] is invalid.
Does anyone know the correct datatype I need to use. Perhaps there is a way of listing them all? Here is my RESTlet:
function getRESTlet(dataIn) {
var message = "";
var status = "OK";
var data = {};
var savedSearch = nlapiLoadSearch('WebServicesOperations', 'customsearch_mysearch');
var resultset = savedSearch.runSearch();
var returnSearchResults = [];
var searchid = 0;
do {
var resultslice = resultset.getResults(searchid, searchid + 1000);
for ( var rs in resultslice) {
returnSearchResults.push(resultslice[rs]);
searchid++;
}
} while (resultslice.length >= 1000);
return returnSearchResults;
} // Close function
Valid Scriptable/Searchable record types would be found in the Records Browser. Not all Record Types are available to be scripted or searched via scripting.
Web Services Operations does not appear to be supported in scripting.

Application breaks while View Redirect to Azure login

I have a mvc application , Which have a Home view , in the Home View I have Button to see the report , Which is loading two partial view one is get the ajax call and load the external api data from table ,another one partial view is for load powerbi.
while click the button, i have load different api and get the datas in 1 partial view and while loading the second partial view for PowerBi , which redirect to azure login and breaks the application.
public ActionResult Index(){
var #params = new NameValueCollection
{
{"response_type", "code"},
{"client_id", Properties.Settings.Default.ClientID},
{"resource", "https://analysis.windows.net/powerbi/api"},
{"redirect_uri", "http://localhost:13526/Redirect"}
};
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString.Add(#params);
string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
var authUri = String.Format("{0}?{1}", authorityUri, queryString);
Response.Redirect(authUri);
}
After Authentication ,Azure issues the token and load the powerbi.
EmbedPowerBi
public async Task<ActionResult> EmbedPowerBi ()
{
AuthenticationResult authResult;
authResult = (AuthenticationResult)Session["authResult"];
var token = authResult.AccessToken;
ViewBag.Token = token;
var tokenCredentials = new TokenCredentials(token, "Bearer");
// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
// Get a list of dashboards.
var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);
// Get the first report in the group.
var dashboard = dashboards.Value.FirstOrDefault();
//var dashboard = dashboards.Value.Where(w => w.Id == "DashboardId");
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(GroupId, dashboard.Id, generateTokenRequestParameters);
if (tokenResponse == null)
{
return View(new EmbedConfig()
{
ErrorMessage = "Failed to generate embed token."
});
}
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = dashboard.EmbedUrl,
Id = dashboard.Id
};
return View(embedConfig);
}
}
Problem I have faced beacuse of redirection other partial view gets affected the current application.
In the Home View i am loading partial view.
#Html.Partial("loadProduct");
#Html.Partial("_EmbedPowerBi");
Have you tried referring to the existing 'Developer Samples'?
https://github.com/Microsoft/PowerBI-Developer-Samples
https://github.com/Microsoft/PowerBI-Developer-Samples/blob/master/App%20Owns%20Data/PowerBIEmbedded_AppOwnsData/Controllers/HomeController.cs#L133
It seems the redirection problem is causing a ViewModel binding to you EmbedConfig

Documentdb Failed to deserialize stored procedure response or convert it to my defined type

My Stored Procedure: (I created it via Azure Script Explorer)
function GetAllResources() {
var collection = getContext().getCollection();
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM MultiLanguage as m',
function (err, docs, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!docs || !docs.length) getContext().getResponse().setBody('no docs found');
else getContext().getResponse().setBody(JSON.stringify(docs));
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The sproc can be executed successfully from script explorer.
My C# code to call the sproc:
public async Task<IHttpActionResult> GetReources() {
client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
var collectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
//var docs = await client.ReadDocumentFeedAsync(collectionLink, new FeedOptions { MaxItemCount = 10 });
//var docs = from d in client.CreateDocumentQuery<Models.Resource>(collectionLink)
// select d;
StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collectionLink).Where(c => c.Id == "GetAllResources").AsEnumerable().FirstOrDefault();
Models.Resource docs = await client.ExecuteStoredProcedureAsync<Models.Resource>(storedProcedure.SelfLink);
foreach (var d in docs) {
Models.Resource a = new Models.Resource();
a = docs;
//a.id = d.id;
//a.Scenario = d.Scenario;
//a.Translations = d.Translations;
//a.LastModified = d.LastModified;
//a.ModifiedBy = d.ModifiedBy;
//a.LastAccessed = d.LastAccessed;
resources.Add(a);
}
return Ok(resources);
}
First, there is an error for the "foreach..." like said
foreach cannot operate on variables of type Models.Resource because it
doesn't contain a public definition of GetEnumerator.
Then I tried to modify my sproc to only return 1 result and remove the foreach line, then I got error said
Failed to deserialize stored procedure response or convert it to type
'Models.Resource'
I just want to return the result of the stored procedure as my defined class (Models.Resource). How to do this?
It can be simpler to get sproc by name using CreateStoredProcedureUri, like this:
const string endpoint = "https://your.service.azure.com:443/";
const string authKey = "<your magic secret master key>==";
var client = new DocumentClient(new Uri(endpoint), authKey);
Uri sprocUri = UriFactory.CreateStoredProcedureUri("databaseName", "collectionName", "GetAllResources");
var result = await client.ExecuteStoredProcedureAsync<string>(sprocUri);
The stored procedure above serializes results of the query (docs array) to string, if you keep it this way, the result of sproc would be string, which I guess you would need to manually deserialize to objects. You can do this simpler, just return docs from sproc and have result as objects (like Models.Resource[]), serialization would happen automatically.
If you change the sproc to return just one doc (e.g. do __.response.setBody(docs[0]) and Models.Resource represent one item, then the call is correct:
Models.Resource doc = await client.ExecuteStoredProcedureAsync<Models.Resource>(sprocUri);
Also, to // Query documents and take 1st item, I wouldn't recommend to use script as script has overhead of running JavsScript engine. Scripts kick in when you have bulk operations (to optimize for network traffic) or have business logic which makes sense to run on the server. To take 1st item you can do query from client like this: SELECT TOP 1 * FROM c. Typically you would WHERE and ORDER BY clause to that.
There is a number of docdb samples on github, for instance, https://github.com/Azure/azure-documentdb-dotnet/tree/master/samples/code-samples/ServerSideScripts and https://github.com/Azure/azure-documentdb-dotnet/tree/master/samples/code-samples/Queries.
Thanks,
Michael
All right, let's make sure we are on the same page.
I am using the sproc same as above.
I am using client code like this:
class Models
{
// This would have more properties, I am just using id which all docs would have.
public class Resource
{
[JsonProperty("id")]
public string Id { get; set; }
}
}
public async Task<IHttpActionResult> GetResources()
{
const string endpoint = "https://myservice.azure.com:443/";
const string authKey = "my secret key==";
var client = new DocumentClient(new Uri(endpoint), authKey);
Uri sprocUri = UriFactory.CreateStoredProcedureUri("db", "c1", "GetAllResources");
var serializedDocs = await client.ExecuteStoredProcedureAsync<string>(sprocUri);
Models.Resource[] resources = JsonConvert.DeserializeObject<Models.Resource[]>(serializedDocs);
return Ok(resources);
}
It works fine. Is this what you are doing?

Office 365 'Create Event' Rest API is giving error

I am new user on stackoverflow as well as in office 365 development using node.js.
I am successfully getting User(my own office 365 account) mails,calendar events using this tutorial (https://dev.outlook.com/RestGettingStarted/Tutorial/node)
but when i am trying to Create an Event in my calender it gives me below error
"{"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}"
Please provide me suggestions on the same.
Below is the code for creating event which i copied from [https://msdn.microsoft.com/office/office365/APi/calendar-rest-operations#CreateEvents] here
function createEvent(response, request) {
var cookieName = 'node-tutorial-token';
var cookie = request.headers.cookie;
// if (cookie && cookie.indexOf(cookieName) !== -1) {
console.log("Cookie: ", cookie);
// Found our token, extract it from the cookie value
var start = cookie.indexOf(cookieName) + cookieName.length + 1;
var end = cookie.indexOf(';', start);
end = end === -1 ? cookie.length : end;
var token = cookie.substring(start, end);
console.log("Token found in cookie: " + token);
var event = new outlook.Microsoft.OutlookServices.Event();
event.subject = 'Your Subject';
event.start = new Date("October 30, 2014 11:13:00").toISOString();
event.end = new Date("October 30, 2014 12:13:00").toISOString();
// Body
event.body = new outlook.Microsoft.OutlookServices.ItemBody();
event.body.content = 'Body Content';
event.body.contentType = outlook.Microsoft.OutlookServices.BodyType.Text;
// Location
event.location = new outlook.Microsoft.OutlookServices.Location();
event.location.displayName = 'Location';
// Attendee
var attendee1 = new outlook.Microsoft.OutlookServices.Attendee();
var emailAddress1 = new outlook.Microsoft.OutlookServices.EmailAddress();
emailAddress1.name = "abc";
emailAddress1.address = "abc#abcdt.onmicrosoft.com";
attendee1.emailAddress = emailAddress1;
event.attendees.push(attendee1);
var outlookClient = new outlook.Microsoft.OutlookServices.Client('https://outlook.office365.com/api/v1.0',
authHelper.getAccessTokenFn(token));
outlookClient.me.calendar.events.addEvent(event)
.then(function (response) {
console.log(response._Id);
}, function (error) {
console.log(error);
});
}
Make sure your app has requested for calendar.readwrite permission and you need this to create new events. In the example you followed, your app registered for only Calendar.Read permissions (see below).
You should instead go to https://dev.outlook.com/AppRegistration to register an app with Calendar.ReadWrite permission which is required to create new events.

Resources