CRM 2011 FetchXML returning invalid XML - dynamics-crm-2011

I am trying to retrieve an account but the fetchXML is returning invalid XML:
function SelectLoadOutTransactionCurrency(id)
{
debugger;
var _oService = new FetchUtil(_sOrgName, _sServerUrl);
var sFetch = "<fetch mapping='logical'>" +
"<entity name='salesorder'>"+
"<attribute name='transactioncurrencyid' />" +
"<filter type='and'>" +
"<condition attribute = 'salesorderid' operator='eq' value='" + id + "'/>" +
"</filter>" +
"</entity>" +
"</fetch>";
var fetchResult =_oService.Fetch(sFetch, null);
return fetchResult.results[0].attributes["transactioncurrencyid"].guid;
}
function GetSuppliers(){
debugger;
_oService = new FetchUtil(_sOrgName, _sServerUrl);
var sFetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='account'>" +
"<attribute name='name' />" +
"<attribute name='accountid' />" +
"<order attribute='name' descending='false'/>" +
"<filter type='and'>" +
"<condition attribute='new_accounttype' operator='eq' value='100000001'/>" +
"</filter>" +
"</entity>" +
"</fetch>";
var fetchResult =_oService.Fetch(sFetch, null);
return fetchResult;
}
function addOption(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
The name attribute has an invalid character (').. Is there a way to escape this character or is there an update rollup in place?

Related

Use client side rendering(js link) for dynamically created Sharepoint document library

I want to use client side rendering(js link) for document library, the challenge for me is Sharepoint document library will be created dynamically when the remote event receiver triggers.
I know we need to pass js link reference in elements.xml file, but in my case list will be created later, so how can I achieve it?
Thanks in advance.
You can add script (JSLink) programmatically, after your condition event receiver:
C#:
using (SPSite site = new SPSite("http://sp/sites/test"))
{
SPWeb web = site.RootWeb;
SPFile page = web.GetFile("SitePages/Test.aspx");
page.CheckOut();
using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
XmlElement p = new XmlDocument().CreateElement("p");
p.InnerText = "<script type='text/javascript'>alert('Hello World');</script>";
ContentEditorWebPart cewp = new ContentEditorWebPart
{
Content = p
};
wpmgr.AddWebPart(cewp, "Header", 0);
}
page.CheckIn(String.Empty);
}
JS:
var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';
function addWebPart() {
var clientContext = new SP.ClientContext(siteUrl);
var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);
var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
'<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' +
' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' +
' xmlns=\"http://schemas.microsoft.com/WebPart/v2\">' +
'<Title>My Web Part</Title><FrameType>Default</FrameType>' +
'<Description>Use for formatted text, tables, and images.</Description>' +
'<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' +
'<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' +
'<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' +
'<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' +
'<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' +
'<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' +
'<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' +
'<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' +
'<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' +
'PublicKeyToken=94de0004b6e3fcc5</Assembly>' +
'<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' +
'<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + '/sites/SiteAssets/Test.js</ContentLink>' +
'<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' +
'<![CDATA[This is a first paragraph!<DIV> </DIV>And this is a second paragraph.]]></Content>' +
'<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';
var oWebPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
this.oWebPart = oWebPartDefinition.get_webPart();
limitedWebPartManager.addWebPart(oWebPart, 'Left', 1);
clientContext.load(oWebPart);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
alert('Web Part added: ' + oWebPart.get_title());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

How to validate if SharePoint list item update was successfull

I am trying to update a SharePoint list through an InfoPath form. A starting date SelectedDAM is input, and the code then calculates 6 dates. Newly calculated dates have to be updated in the original SP list.
The code below raises no exception in debug mode, and even in production. I checked that 'jobs' gets populated with data, and that le list names are as per their SharePoint name. Saddly, when I look to the SharePoint list afterward, items were not updated.
public void SetDAMButton_Clicked(object sender, ClickedEventArgs e)
{
string SelectedCEC = nav.SelectSingleNode("/my:mesChamps/my:DAMSection/my:CEC", this.NamespaceManager).Value;
string SelectedDAM = nav.SelectSingleNode("/my:mesChamps/my:DAMSection/my:DAM", this.NamespaceManager).Value;
//Query all jobs and dates from SharePoint List
XmlDocument xmlDoc = new XmlDocument();
XmlNode query = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode viewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
query.InnerXml = "<Where>" +
"<Contains><FieldRef Name='CEC'/>" +
"<Value Type='Text'>" + SelectedCEC.Trim() + "</Value></Contains>" +
"</Where>";
viewFields.InnerXml = "<FieldRef Name='ID' />" +
"<FieldRef Name='JRS_x0020_Avant' />"+ "<FieldRef Name='JRS_x0020_Pr_x00e9_vus' />"+
"<FieldRef Name='JRS_x0020_Prevus_x0020_2' />"+ "<FieldRef Name='JRS_x0020_Avant_x0020_2' />"+
"<FieldRef Name='JRS_x0020_Pr_x00e9_vus_x0020_3' />" + "<FieldRef Name='JRS_x0020_Avant_x0020_3' />";
XmlNode listItems = sp.getListService().GetListItems(SPJobsListGlobal, null, query, viewFields, "10000000", null, null);
//Extract jobs data to an internal list
List<string[]> jobs = new List<string[]>();
for (int i = 1; i != listItems.ChildNodes[1].ChildNodes.Count; i += 2)
{
string jobId = listItems.ChildNodes[1].ChildNodes[i].Attributes[0].InnerXml;
string JRSAvant = listItems.ChildNodes[1].ChildNodes[i].Attributes[1].InnerXml;
string JRSPrevus = listItems.ChildNodes[1].ChildNodes[i].Attributes[2].InnerXml;
string JRSPrevus2 = listItems.ChildNodes[1].ChildNodes[i].Attributes[3].InnerXml;
string JRSAvant2 = listItems.ChildNodes[1].ChildNodes[i].Attributes[4].InnerXml;
string JRSPrevus3 = listItems.ChildNodes[1].ChildNodes[i].Attributes[5].InnerXml;
string JRSAvant3 = listItems.ChildNodes[1].ChildNodes[i].Attributes[6].InnerXml;
jobs.Add(new string[] { jobId.Trim(), JRSAvant.Trim(), JRSPrevus.Trim(),JRSAvant2.Trim(), JRSPrevus2.Trim(), JRSAvant3.Trim(), JRSPrevus3.Trim() });
}
jobs.RemoveAt(jobs.Count - 1);
//Update each item of SharePoint list with dates calculated from new DAM
for(int i = 0; i != jobs.Count; i++)
{
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
batch.InnerXml = "<Method ID='1' Cmd='Update'>" +
"<Field Name='ID'>" + SecurityElement.Escape(jobs[i][0]) + "</Field>" +
"<Field Name='DateDebut'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][1])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='DateFin'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][1])).AddDays(validateJRS(jobs[i][2])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_D_x00e9_but_x0020_2'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][3])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_Fin_x0020_2'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][3])).AddDays(validateJRS(jobs[i][4])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_D_x00e9_but_x0020_3'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][5])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_Fin_x0020_3'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][5])).AddDays(validateJRS(jobs[i][6])).ToString("yyyy-MM-dd")) + "</Field>" +
"</Method>";
sp.UpdateListItems(SPJobsListGlobal, batch);
}
Why is it not working ? Is there any additionnal line I could add to confirm update.
To confirm the update you can check the return value of Lists.UpdateListItems, which is an XmlNode that contains the status of the update.
From MSDN:
Return value
An XMLDATA fragment in the following form that shows the status of each method block posted through the updates parameter and that can be assigned to a System.Xml.XmlNode object. For items successfully updated, a row fragment is returned with the updated row values.

Update ProjectedField with JOIN in Sharepoint using Javascript client object model

Suppose I have 2 Lists: Teams and Employees. Each team has a number of employees:
Teams
ID
Name
Employees
ID
Name
TeamID (foreign key of Teams)
If I created a Join query of Employees LEFT JOIN Teams, could I then set_item and update the Name field in Teams?
var ctx = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('Employees');
var queryText =
"<View>" +
"<Query></Query>" +
"<ProjectedFields>" +
"<Field Name='TeamName' Type='Lookup' List='Team' ShowField='Name' />" +
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='INNER' ListAlias='Team'>" +
"<Eq>" +
"<FieldRef Name='TeamID' RefType='Id'/>" +
"<FieldRef List='Team' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"<ViewFields>" +
"<FieldRef Name='TeamName'/>" +
"</ViewFields>" +
"</View>";
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(queryText);
var listItemsCollection = list.getItems(camlQuery);
ctx.executeQueryAsync(onSuccess, onError);
And then, update the TeamName field:
var first = listItemsCollection.get_data()[0];
first.set_item("TeamName", "something");
first.update();
ctx.executeQueryAsync(onSuccess, onError);
Is this supported? (I currently have not way of trying this)
If not, what could be the alternative?
No, only those fields that contains list item could be updated. But you could consider the following approach for updating projected fields.
Since projected fields are returned as lookup values, you could retrieve projected list item and update it's properties as demonstrated below:
var listTitle = 'Employees';
var joinListTitle = 'Teams'
var joinFieldName = 'TeamID';
var projectedFields = ['Name'];
getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,
function(items){
var item = items.get_data()[0]; //get first item
var itemId = item.get_item('TeamsName').get_lookupId(); //get projected list item id
var propertiesToUpdate = {'Name': 'New Team Name'};
updateListItem(joinListTitle,itemId,propertiesToUpdate,function(item){
console.log('List Item has been updated');
},
logError);
},
logError);
where
function createJoinQuery(joinListTitle,joinFieldName,projectedFields,joinType)
{
var queryText =
"<View>" +
"<Query/>" +
"<ProjectedFields>";
for(var idx in projectedFields) {
queryText += String.format("<Field Name='{0}{1}' Type='Lookup' List='{0}' ShowField='{1}' />",joinListTitle,projectedFields[idx]);
}
queryText +=
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='{2}' ListAlias='{0}'>" +
"<Eq>" +
"<FieldRef Name='{1}' RefType='Id'/>" +
"<FieldRef List='{0}' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"</View>";
var qry = new SP.CamlQuery();
qry.set_viewXml(String.format(queryText,joinListTitle,joinFieldName,joinType));
return qry;
}
function getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var items = list.getItems(createJoinQuery(joinListTitle,joinFieldName,projectedFields,'INNER'));
ctx.load(items);
ctx.executeQueryAsync(
function() {
success(items);
},
error
);
}
function updateListItem(listTitle,itemId, propertiesToUpdate,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var listItem = list.getItemById(itemId);
for(var name in propertiesToUpdate) {
listItem.set_item(name,propertiesToUpdate[name]);
}
listItem.update();
ctx.executeQueryAsync(function() {
success(listItem);
},error);
}

i want display list in sharepoint 2013 uses js

Following is my code:
retrieveListItems('https://sustec29-public.sharepoint.com');
function retrieveListItems(siteUrl) {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit></View>'
);
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\ngroup: ' + oListItem.get_item('group') +
'\ndisc: ' + oListItem.get_item('disc');
}
$('#message').text(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
`
but browser views error -
The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
if i write
'\ntitle: ' + oListItem.get_item('title') + '\nbody: ' + oListItem.get_item('body');
and rename field table`s - all ok.
But i want add own field..
Try to add ViewFields section to your caml query:
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name="ID"/>' +
'<Value Type="Number">1</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit><ViewFields><FieldRef Name="group" /><FieldRef Name="disk" /></ViewFields></View>'
EDIT:
Another way you can try to achieve this is to add Include string to your load method call:
clientContext.load(collListItem, 'Include(Id, disk, group)');

Display sharepoint list data to dynamic html table using jQuery

I am having a scenario where i need to get the list data to be shown in dynamic html table using jQuery to display in site with content editor webpart. Please help me out with this regards thanks in advance...
You can use SharePoint Client Context REST API to get the data and display it in a table. Add reference to these three scripts:
1. /_layouts/15/SP.Runtime.js
2./_layouts/15/SP.js
3. //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
And use below example:
<script type="text/javascript">
$(document).ready(function () {
fnGetData();
});
function fnGetData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
var list = web.get_lists().getByTitle('Users');
var myquery = new SP.CamlQuery();
myquery.set_viewXml("<View><Query>" +
"<Where>" +
"<IsNotNull>" +
"<FieldRef Name='Title' />" +
"</IsNotNull>" +
"</Where>" +
"</Query></View>");
myquery.set_datesInUtc(false);
myItems = list.getItems(myquery);
context.load(myItems);
context.executeQueryAsync(Function.createDelegate(this, function () { fnGetDataSuccess(); }), Function.createDelegate(this, this.fnGetDataFailed));
}
function fnGetDataSuccess() {
var txtHTML = "";
var ListEnumeratorAcc = this.myItems.getEnumerator();
while (ListEnumeratorAcc.moveNext()) {
var currentItem = ListEnumeratorAcc.get_current();
txtHTML = txtHTML + "<tr>";
txtHTML = txtHTML + "<td>";
if (currentItem.get_item('Title') != null) {
txtHTML = txtHTML + currentItem.get_item('Title');
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (currentItem.get_item('Owner') != null) {
txtHTML = txtHTML + currentItem.get_item('Owner').get_lookupValue();
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "</tr>";
}
$("#tblCustomListData").append(txtHTML);
}
function fnGetDataFailed(sender, args) {
alert("Error Message:\n" + "URL: " + sender.get_url() + ". \n\Error Description:" + args.get_message());
}
</script>
<table id="tblCustomListData" border="1">
<thead>
<tr>
<th>Title
</th>
<th>Owner
</th>
</tr>
</thead>
</table>
You can either use SharepointPlus or SPServices to retrieve the list data. Then it's easy to use jQuery to insert the data into the HTML page.

Resources