CRM 2011 call to mscrmsevices prompting for credentials - javascript

I am reconfiguring an application that we had running in CRM 4.0 to run in CRM 2011. It was previously called from a toolbar button using javascript.
I have transferred the javascript to a web resource and reconfigured the ribbon to hold the button and call the required function within the library.
When testing this however, I am being prompted for username and password which when entered 3 or so times returns the error "'null' is null or not an object".
I am not sure why I am getting prompted for credentials when this did not happen in CRM 4.0.
Any ideas what may be causing this?
The javascript is below:
try
{
var ADD_LETTER='1';
var SAVE_DOC_IN_CRM='1';
var STORE_TO_PRINT='1';
var SEND_EMAIL='1';
var SHOW_PARAGRAPHS='1';
var xml = '' +'<?xml version=\'1.0\' encoding=\'utf-8\'?>' +'<soap:Envelope xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'>'+GenerateAuthenticationHeader() +' <soap:Body>' +' <RetrieveMultiple xmlns=\'http://schemas.microsoft.com/crm/2007/WebServices\'>' +' <query xmlns:q1=\'http://schemas.microsoft.com/crm/2006/Query\' xsi:type=\'q1:QueryExpression\'>' +' <q1:EntityName>systemuser</q1:EntityName>' +' <q1:ColumnSet xsi:type=\'q1:ColumnSet\'>' +' <q1:Attributes>' +' <q1:Attribute>systemuserid</q1:Attribute>' +' </q1:Attributes>' +' </q1:ColumnSet>' +' <q1:Distinct>false</q1:Distinct>' +' <q1:Criteria>' +' <q1:FilterOperator>And</q1:FilterOperator>' +' <q1:Conditions>' +' <q1:Condition>' +' <q1:AttributeName>systemuserid</q1:AttributeName>' +' <q1:Operator>EqualUserId</q1:Operator>' +' </q1:Condition>' +' </q1:Conditions>' +' </q1:Criteria>' +' </query>' +' </RetrieveMultiple>' +' </soap:Body>' +'</soap:Envelope>' +'';
var xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
xmlHttpRequest.Open('POST', '/mscrmservices/2007/CrmService.asmx', false);
xmlHttpRequest.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple');
xmlHttpRequest.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xmlHttpRequest.setRequestHeader('Content-Length', xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode('//RetrieveMultipleResult/BusinessEntities/BusinessEntity');
var useridNode = entityNode.selectSingleNode('q1:systemuserid');
var sUserId = (useridNode == null) ? '' : useridNode.text;
var sGUID = crmForm.ObjectId;
var sEntity = crmForm.ObjectTypeName;
var sURL = '/ISV/Mergedabc/Mergedabc.aspx?org=' + ORG_UNIQUE_NAME + '&guid=' + sGUID + '&ety=' + sEntity + '&userid=' + sUserId + '&indid=' + sGUID + '&indtype=' + crmForm.ObjectTypeCode + '&indtypename=' + sEntity + '&addletter=' + ADD_LETTER + '&docincrm=' + SAVE_DOC_IN_CRM + '&storetoprint=' + STORE_TO_PRINT + '&emaildoc=' + SEND_EMAIL + '&showparas=' + SHOW_PARAGRAPHS;
var objRet = window.showModalDialog(prependOrgName(sURL));
if(objRet != null)
{
if (objRet.length > 0)
{
var o = objRet[0];
if (o.ret == true)
{
alert('Merge Completed.');
}
else {
alert('Unable to merge document.');
}
}
else
{
alert('No merge information returned.');
}
}
}
catch (e)
{
alert(e.message);
}
It looks as though this is happening when it tries to call the CrmService and is causing a 401 error.
Any suggestions on how to fix this will be appreciated,
Thanks!!

Fixed – the issue was the XML-isation of all the %amp; %lt; %gt; instead of %, < and > in the SOAP call.

Related

getting XMLHttpRequest cannot load (URL) Response for preflight is invalid (redirect)

here am trying to get reccurring events from calendar list for sharepoint Online app and there am using code as like
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
function GetListData() {
var webUrl = hostWebUrl;// = "http://server/sitewhereyourlistexists";
var listGuid = "{2000da75-8663-42d9-9999-ad855c54b4e0}"
// An XMLHttpRequest object is used to access the web service
var xhr = new XMLHttpRequest();
var url = webUrl + "/_vti_bin/Lists.asmx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
// The message body consists of an XML document
// with SOAP elements corresponding to the GetListItems method parameters
// i.e. listName, query, and queryOptions
var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>" + listGuid + "</listName>" +
"<query>" +
"<Query><Where>" +
"<DateRangesOverlap>" +
"<FieldRef Name=\"EventDate\"/>" +
"<FieldRef Name=\"EndDate\"/>" +
"<FieldRef Name=\"RecurrenceID\"/>" +
"<Value Type=\"DateTime\"><Today/></Value>" +
"</DateRangesOverlap>" +
"</Where></Query>" +
"</query>" +
"<queryOptions>" +
"<QueryOptions>" +
"<ExpandRecurrence>TRUE</ExpandRecurrence>" +
"</QueryOptions>" +
"</queryOptions>" +
"</GetListItems>" +
"</soap:Body>" +
"</soap:Envelope>";
// Here we define what code we want to run upon successfully getting the results
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var doc = xhr.responseXML;
// grab all the "row" elements from the XML results
var rows = doc.getElementsByTagName("z:row");
var results = "Today's Schedule (" + rows.length + "):\n\n";
var events = {};
for (var i = 0, len = rows.length; i < len; i++) {
var id = rows[i].getAttribute("ows_FSObjType"); // prevent duplicates from appearing in results
if (!events[id]) {
events[id] = true;
var allDay = rows[i].getAttribute("ows_fAllDayEvent"),
title = rows[i].getAttribute("ows_Title"),
start = rows[i].getAttribute("ows_EventDate");
var index = start.indexOf(" ");
var date = start.substring(5, index) + "-" + start.substring(2, 4); // get the date in MM-dd-yyyy format
start = start.substring(index, index + 6); // get the start time in hh:mm format
var end = rows[i].getAttribute("ows_EndDate");
index = end.indexOf(" "); end = end.substring(index, index + 6); // get the end time in hh:mm format
results += date + " " + (allDay == "1" ? "All Day\t" : start + " to " + end) + " \t " + title + "\n";
}
}
alert(results);
} else {
alert("Error " + xhr.status);
}
}
};
// Finally, we actually kick off the query
xhr.send(data);
}
after calling this function in decument. ready section it is not retrieving any data but there is ine error which i can see in console of browser that is as below
You will click on the correct request in the left hand side panel, then select "Inspectors" in the right hand side top panel. Then choose between the different request and response options.

Error parsing HTTP request header only when on server, works fine on local host

I am trying to get some data and present it as an Excel download. I do this through the following code:
"ajax": {
url: $('#url').val(),
type: "POST",
data: function (d) {
//("in data function");
if( $('#filter0').val() !=''){
d.columns[0]['search']['regex'] = true;
d.columns[0]['search']['value'] = $('#filter0').val();
$('#pageHeaderL2').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + "'>" + $('#filter0').val() + "</button>");
//("set default facility");
}
if( $('#filter1').val() !=''){
d.columns[1]['search']['regex'] = true;
d.columns[1]['search']['value'] = $('#filter1').val();
$('#pageHeaderL5').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + ":" + $('#filter1').val() + "'>" + $('#filter0').val() + ":" + $('#filter1').val() + "</button>");
//("set default module");
}
if($('#searchValueIn').val() != "")// depending on if you module search or global search the search string is stored in a different location, this saves the search val in a string
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var dd = $.extend({}, d, {
"originalSearchValue": searchVal
//"useDefaultFacility": $('#filter0').val() !='' ? true : false,
//"useDefaultModule": $('#filter1').val() !='' ? true : false,
});
currentTableMeta = dd;
return dd;
},
dataSrc: function(json) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
if($('#searchValueIn').val() != "")
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var hrefExcel= $('#excelurl').val() +'?searchValue='+ searchVal +'&' + $.param(currentTableMeta) ;
// debugger;
if($('#tableExcel').length < 1) {
$('#partTable_filter').css({left: 10, position:'absolute'});
$('#partTable_filter').prepend($('<a id="tableExcel" href="' + hrefExcel + '" class="btn" style="float:right; margin-left: 5px;"><i class="icon-table"></i> Excel</a>'));
/* $('#tableExcel').on("click",function(e) {
//var abc = $(currentTableMeta).serialize();
var abc = $.param(currentTableMeta);
debugger; }); */
// alert("in the IF");
$('#partTable_processing').before("<br /><br />");
}else{
$("#tableExcel").attr('href',hrefExcel);
//alert("in the else");
alert("After the Click");
}
tableSortRowObj = $("#sortRowState");
//("this current sort:" + tableSortRowObj);
updateFilterFields(json);
//("to isnert:" + newRowOfFilters);
return json.data;
}
},
This completely works when if I run it on my local tomcat server using Chrome or firefox, but once I deploy the code to my test server it doesn't work using chrome or IE. Firefox can download the excel but it doesn't download with a file extension. This is the error I get from the server:
Aug 16, 2016 12:16:20 PM org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
On my local host I get the following error from trying to run using IE.
org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

when parsing json data throwing error

I am adding Json data to html div and parsing.it is working fine in local.but it is throwing error when we are running file from server .the error is "unexpected token o".
var data = $.parseJSON($("#json-data").html());
//console.log(data);
var now = new Date();
var events = [];
if (data != undefined && data.results.assets.length > 0) {
var dayevents = [];
$.each(data.results.assets, function(i, entry) {
var d = entry.metadata.EventDate;
$('#calender-list').append('<div class="events-list-main"><div class="events-list"><div class="event-title">' + entry.metadata.EventName + '</div><div class="event-addr">' + (entry.metadata.EventDate) + '-' + (entry.metadata.EventEndDate). + ' ' + (entry.metadata.EventEndDate). + '<br/>' + entry.metadata.EventAddress + '</div><div class="event-desc">' + entry.metadata.EventDesc + '</div>SEE EVENT WEBSITE<em class="icon-go"></em></div></div>');
});
}
fiddle
There are .+ at (entry.metadata.EventEndDate). +.
They should be something like (entry.metadata.EventEndDate) + '<br/>'
fiddle

ContextMenuItem context function is not executing

I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.

Add <option> in IE 6 unwards

I've the code below written in JavaScript to add a new option to the select list from the opener window:
function updateSelectList()
{
var field = opener.document.objectdata.ticketPersonId;
if (true && opener && field)
{
var val = document.createElement('option');
var title = document.objectdata.titleId.options[document.objectdata.titleId.selectedIndex].text;
val.text = title + ' ' + document.objectdata.firstName.value + ' ' + document.objectdata.lastName.value + ':' + document.objectdata.username.value;
val.value = null;
val.selected = true;
field.add(val, null);
}
}
works all fine in Firefox, Google Chrome etc but not IE 6 :-(
please advise how I can make this work in IE 6 aswell.
Here's my snippet:
if (oldopt!=null || !horus.brokenDOM)
select.add(newopt, oldopt);
else
newopt=options[options.length]=new Option(newopt.text, newopt.value, false, false);
The definition of horus.brokenDOM is left to the reader :)
IIRC, I had some difficulty with using pre-defined Option objects (generally pulled out of another selectbox) in this context with IE, hence the in-place object creation.
function updateSelectList()
{
var field = opener.<%= updatelist %>;
if (<%= called %> && opener && field)
{
var val = opener.document.createElement('option');
var title = document.objectdata.titleId.options[document.objectdata.titleId.selectedIndex].text;
val.text = title + ' ' + document.objectdata.firstName.value + ' ' + document.objectdata.lastName.value + ':' + document.objectdata.username.value;
val.value = <%= thePerson != null ? thePerson.getId() : null %>;
val.selected = true;
try
{
field.add(val, null);
}
catch(error)
{
field.add(val, 0);
}
}
}
this seams to work. What a mission!

Categories