CRM OData OrganizationData.svc does not work by IP - javascript

I have been working on CRM autoupdate filed and i got it working by
var lookUpObjectValue = Xrm.Page.getAttribute("new_kdid").getValue();
if ((lookUpObjectValue != null))
{
var lookupid = lookUpObjectValue[0].id;
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "new_kdSet?";
var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName +
"$select=new_City" +
"&$filter=new_kdId eq (guid'" + lookupid + "')" +
"&$top=1";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) {XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest){
Xrm.Page.getAttribute("address1_city").setValue(data.d.results[0].new_City);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
And it works fine until I connect to CRM by IP.
Like http://193.92.1.4/CRMTest/main.aspx# instead of
crm-server01/CRMTest/main.aspx
then i get the error OData Select Failed:/*Some url that start with crm-server01/ ... */ and when i run it it get the right data?

This is down to cross site scripting. You will find this happens to a lot of different JavaScript doing requests on CRM.
I would recommend only connecting to CRM using your server name.

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

Windows Translator: "ArgumentOutOfRangeException: 'to' must be a valid language

Im trying to use Bing Translator...
Already Have a token (I think), but when try to get the translation, the same Error is always poping:
"ArgumentOutOfRangeException: 'to' must be a valid language\u000d\u000aParameter name: to : ID=5217.V2_Json.Translate.5FEAF805"
The next is the url that i am using, and I dont see where the error is...
https://api.microsofttranslator.com/V2/Ajax.svc/Translate?
&appId=Bearer%20http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=TranslateHelper000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1439307776&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=xGQ7LMehBDHJLY2Xq7jN8PXOhRCYqs%2boUb2V4Ic4XLI%3d
&from=en
&to=pt
&text=Home
&oncomplete=mycallback
(pt is defined as language in translator... it doesn't work either with to=en...
My question are, if you could help me on this:
1. Is that a normal Token?
2. Is it is normal, what is wrong with code? (I dont have any more hair to take off...)
This is the code I use to send the url (mycallback isn't being called either):
$.ajax({
type: "POST",
url: 'getTranslatorToken',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (token) {
var languageFrom = "en";
var languageTo = "pt";
var textToTranslate = "Home";
var strToken = token["access_token"];
var s = document.createElement("script");
//s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=Bearer " + token + "&from=" + languageFrom + "&to=" + languageTo + "&text=" + $('#txtMsg').val();
s.src = "https://api.microsofttranslator.com/V2/Ajax.svc/Translate?&appId=Bearer " + strToken +
"&from=" + encodeURIComponent(languageFrom) +
"&to=" + encodeURIComponent(languageTo) +
"&text=" + encodeURIComponent(textToTranslate) +
"&oncomplete=mycallback";
document.getElementsByTagName("head")[0].appendChild(s);
console.log(s)
}).fail(function (xhr, ajaxOptions, thrownError) {
alert("Error:"+xhr.responseText);
console.log(xhr.responseText);
//$("#msg").text('Error');
});
Thank
This question is answered here (in C#):
How to translate specific content in website
Working example here (PHP): http://www.johndimm.com/FunWithSpeech/BingTranslator/

Updating record via REST does not trigger workflow, CRM 2011

I have a workflow that wait three days and check a boolean field. If the boolean is yes do something, else finish as completed. That boolean field is default no and change to yes with an update via javascript.
I don't know why the workflow always do something even when the boolean field is no.
Javascript updates are not recognized by Dynamics CRM?
Code I'm using to update:
var obj = new Object();
obj.BooleanField= true;
var jsonEntity = window.JSON.stringify(obj);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/CustomEntity";
var ODataPath = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "(guid'" + CustomEntityId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});

getting an error Object doesn't support property or method 'setSrc' in web Resource in CRM 2011

I have used the WebResource on the Page and I am getting an error Object doesn't support property or method 'setSrc' in Javascript
Can you Please help me
My actual code is like this
function getImage()
{
var entityId = Xrm.Page.data.entity.getId();
var profilePictureElement = Xrm.Page.getControl("WebResource_ProfilePicture");
if (entityId) {
var oDataQuery = getServerUrl() + "/XRMServices/2011/OrganizationData.svc" +
"/AnnotationSet?$top=1&$select=AnnotationId,DocumentBody,MimeType&" +
"$orderby=ModifiedOn desc&$filter=ObjectId/Id eq guid'" + entityId +
"' and IsDocument eq true and Subject eq 'Profile Picture'" +
" and startswith(MimeType,'image/') ";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataQuery,
beforeSend: function (request) { request.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, request) {
if (data.d.results.length > 0) {
var mimeType = data.d.results[0].MimeType;
var body = data.d.results[0].DocumentBody;
// set src attribute of default profile picture web resource.
// here we use DataURI schema which has 32kb limit in IE8 and doesn't support IE <= 7.
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
}
},
error: function (request, status, exception) { }
});
}
}
function getServerUrl()
{
var serverUrl = Xrm.Page.context.getServerUrl();
// trim trailing forward slash in url
return serverUrl.replace(/\/*$/, "");
}
you can refer the whole article from here http://blogs.msdn.com/b/crm/archive/2011/09/28/displaying-a-contact-s-facebook-picture-in-microsoft-dynamics-crm-2011.aspx?CommentPosted=true#commentmessage
Looks like that now the methods getSrc and setSrc can be used against a Web Resource only when refer to an HTML content.
If the Web Resource is an image, the crm will use an img tag to display the picture.
If you want to make that code working you need to retrieve the img element and assign the src property manually:
instead of
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
you need to write
var profilePicture = document.getElementById("WebResource_ProfilePicture");
profilePicture.setAttribute("src","data:" + mimeType + ";base64," + body);
note: this is an unsupported customization

How to update or delete Sender and Receiver of an existing phonecall / email record using MS Dynamics CRM REST Endpoint

I am working on the application where I need to create and later update phonecall / email records in MS Dynamics CRM 2011 using REST API. Using Soap API is not an option.
I have figured out how to create the phonecall / email record (which is well documented here
or here).
Updating the existing phonecall / email record itself is not a problem either.
My question is: HOW do I update the Receiver and Sender fields (To and From) of an existing phonecall / email record?
I have tried different approaches described below with no luck so far.
I get Error processing request stream. Deep updates are not supported in PUT operations. error if I try to update phonecall_activity_parties relationship - see code below
var callLogEntity = {
"Subject": "My call", "Description": "Call comments go here" };
var activityParties = [];
activityParties.push({
"PartyId": {"Id":"4A9FD17D-5890-4BF0-94AA-D68285C46039", "LogicalName":"contact"},
"ParticipationTypeMask": { "Value": 1 }
}); // sender is a contact
activityParties.push({
"PartyId": { "Id": Xrm.Page.context.getUserId(), "LogicalName": "systemuser" },
"ParticipationTypeMask": { "Value": 2 }
}); // receiver is a current user
callLogEntity.phonecall_activity_parties = activityParties;
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"PhoneCallSet(guid'" + callLogId + "')";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: JSON.stringify(callLogEntity),
url: restQueryUrl,
beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest)
{
console.log("Success");
},
error: function (XmlHttpRequest, textStatus, errorObject)
{
console.warn("Request FAILED: " + XmlHttpRequest.responseText);
}
});
I get An activityparty cannot be disassociated from an activity error if I try to disassociate an activity using the disassociateRecords method from this SDK Example - see code below
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"PhoneCallSet(guid'" + callLogId + "')/$links/" +
"phonecall_activity_parties(guid'" + activityPartyId + "')";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: restQueryUrl,
beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest)
{
console.log("Success");
},
error: function (XmlHttpRequest, textStatus, errorObject)
{
console.warn("Request FAILED: " + XmlHttpRequest.responseText);
}
});
I get Forbidden error when I try to delete one of the ActivityParty found in the phonecall_activity_parties directly from ActivityPartySet.
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"ActivityPartySet(guid'" + activityPartyId + "')";
// then do an AJAX POST request with "X-HTTP-Method": "DELETE" header
Updating each ActivityParty from that list individually has no effect on the phonecall record (i.e. the MERGE request seems to be successful, but the ActivityParty still points to the old record)
var activityData = {
"PartyId":{"Id":"cc1cdb40-a844-e211-ab1a-000c297d9c06","LogicalName":"contact"},
"ParticipationTypeMask":{"Value":1}
};
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"ActivityPartySet(guid'" + activityPartyId + "')";
// then do an AJAX post request with "X-HTTP-Method": "MERGE" header
// and activityData as the message body
If anyone can shed some light on how to change (or delete, as in "clear the field") the Sender and Receiver of an EXISTING phonecall / email record I would greatly appreciate it.
Can you try this code. I hope this will be helpful.
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = "3D417D54-412C-440D-A390-33ED7398254D";
lookupValue[0].name = "UserName";
lookupValue[0].entityType = "systemuser";
lookupValue[1] = new Object();
lookupValue[1].id = "8BD96ECC-573D-E211-A12B-1CC1DE79B4CA";
lookupValue[1].name = "QueueName";
lookupValue[1].entityType = "queue";
createRecord(lookupValue, "EmailSet", _emailCreateSuccess, _error);
//Xrm.Page.getAttribute("to").setValue(lookupValue);

Categories

Resources