Sharepoint: How to upload files with metadata including Taxonomy fields through web services - sharepoint

Being very new to SharePoint coding I have been assigned the task to create a prototype code to upload a file and setting the field values for that file that will show up when opening the sharepoint page with the file.
This has to be done from a remote machine and not the Sharepoint server itself so using the .Net objects for Sharepoint is out the question.
I quickly found out how to upload a file through the Sharepoint Web Service Copy.asmx:
void UploadTestFile() {
var file = #"C:\Temp\TestFile.doc";
string destinationUrl = "http://mysharepointserver/Documents/"
+ Path.GetFileName(file);
string[] destinationUrls = { destinationUrl };
var CopyWS = new Copy.Copy();
CopyWS.UseDefaultCredentials = true;
CopyWS.Url = "http://mysharepointserver/_vti_bin/copy.asmx";
CopyResult[] result;
byte[] data = File.ReadAllBytes(file);
FieldInformation mf1 = new FieldInformation {
DisplayName = "title",
InternalName = "title",
Type = FieldType.Text,
Value = "Dummy text"
};
FieldInformation mf2 = new FieldInformation {
DisplayName = "MyTermSet",
InternalName = "MyTermSet",
Type = FieldType.Note,
Value = "Test; Unit;"
};
CopyWS.CopyIntoItems(
"+",
destinationUrls,
new FieldInformation[] { mf1, mf2 },
data,
out result);
}
This code easily uploads any file to the target site but only fills the "title" field with info. The field MyTermSet in which I have added 3 terms allready - Test, Unit and Page - will not update with the values "Test;" and "Unit;".
Being very new to Sharepoint and me not grasping all the basics googling has told me that updating "File", "Computed" or "Lookup" fields does not work with the CopyIntoItems method, and MyTermSet being a Taxonomy field is - if I am correct - a Lookup field.
So how do I get MyTermSet updated with the values "Test;" and "Unit;" ?
I would really prefer If someone has a sample code on this. I have followed several hint-links but I am none the wiser. I have found no sample-code on this at all.
Have anyone made one single method that wraps it all? Or another method that takes in the destinationUrl from the file upload and updates the Term Set/Taxonomy field.

Puzzling together what I have found so far, I am now able to do as I wanted. But I would really like to be able to get the Taxonomy field GUIDs dynamically and NOT having to explicitly set them myself:
void UploadTestFile(string FileName, string DocLib, Dictionary<string, string> Fields = null) {
//Upload the file to the target Sharepoint doc lib
string destinationUrl = DocLib + Path.GetFileName(FileName);
string[] destinationUrls = { destinationUrl };
var CopyWS = new Copy.Copy();
CopyWS.UseDefaultCredentials = true;
CopyWS.Url = new Uri(new Uri(DocLib), "/_vti_bin/copy.asmx").ToString();
CopyResult[] result;
var data = File.ReadAllBytes(FileName);
CopyWS.CopyIntoItems(
"+",
destinationUrls,
new FieldInformation[0],
data,
out result);
if (Fields == null) return; //Done uploading
//Get the ID and metadata information of the fields
var list = new ListsWS.Lists();
list.UseDefaultCredentials = true;
var localpath = new Uri(DocLib).LocalPath.TrimEnd('/');
var site = localpath.Substring(0, localpath.LastIndexOf("/")); //Get the site of the URL
list.Url = new Uri(new Uri(DocLib), site + "/_vti_bin/lists.asmx").ToString(); //Lists on the right site
FieldInformation[] fiOut;
byte[] filedata;
var get = CopyWS.GetItem(destinationUrl, out fiOut, out filedata);
if (data.Length != filedata.Length) throw new Exception("Failed on uploading the document.");
//Dictionary on name and display name
var fieldInfos = fiOut.ToDictionary(x => x.InternalName, x => x);
var fieldInfosByName = new Dictionary<string, FieldInformation>();
foreach (var item in fiOut) {
if (!fieldInfosByName.ContainsKey(item.DisplayName)) {
fieldInfosByName.Add(item.DisplayName, item);
}
}
//Update the document with fielddata - this one can be extended for more than Text and Note fields.
if (!fieldInfos.ContainsKey("ID")) throw new Exception("Could not get the ID of the upload.");
var ID = fieldInfos["ID"].Value; //The ID of the document we just uploaded
XDocument doc = new XDocument(); //Creating XML with updates we need
doc.Add(XElement.Parse("<Batch OnError='Continue' ListVersion='1' ViewName=''/>"));
doc.Element("Batch").Add(XElement.Parse("<Method ID='1' Cmd='Update'/>"));
var methNode = doc.Element("Batch").Element("Method");
//Add ID
var fNode = new XElement("Field");
fNode.SetAttributeValue("Name", "ID");
fNode.Value = ID;
methNode.Add(fNode);
//Loop each field and add each Field
foreach (var field in Fields) {
//Get the field object from name or display name
FieldInformation fi = null;
if (fieldInfos.ContainsKey(field.Key)) {
fi = fieldInfos[field.Key];
}
else if (fieldInfosByName.ContainsKey(field.Key)) {
fi = fieldInfosByName[field.Key];
}
if (fi != null) {
//Fix for taxonomy fields - find the correct field to update
if (fi.Type == FieldType.Invalid && fieldInfos.ContainsKey(field.Key + "TaxHTField0")) {
fi = fieldInfos[field.Key + "TaxHTField0"];
}
else if (fi.Type == FieldType.Invalid && fieldInfosByName.ContainsKey(field.Key + "_0")) {
fi = fieldInfosByName[field.Key + "_0"];
}
fNode = new XElement("Field");
fNode.SetAttributeValue("Name", fi.InternalName);
switch (fi.Type) {
case FieldType.Lookup:
fNode.Value = "-1;#" + field.Value;
break;
case FieldType.Choice:
case FieldType.Text:
fNode.Value = field.Value;
break;
case FieldType.Note: //TermSet's
var termsetval = "";
var terms = field.Value.Split(';');
foreach (var term in terms) {
termsetval += "-1;#" + term + ";";
}
fNode.Value = termsetval.TrimEnd(';');
break;
default:
//..Unhandled type. Implement if needed.
break;
}
methNode.Add(fNode); //Adds the field to the XML
}
else {
//Field does not exist. No use in uploading.
}
}
//Gets the listname (not sure if it is the full path or just the folder name)
var listname = new Uri(DocLib).LocalPath;
var listcol = list.GetListCollection(); //Get the lists of the site
listname = (from XmlNode x
in listcol.ChildNodes
where x.Attributes["DefaultViewUrl"].InnerText.StartsWith(listname, StringComparison.InvariantCultureIgnoreCase)
select x.Attributes["ID"].InnerText).DefaultIfEmpty(listname).First();
//Convert the XML to XmlNode and upload the data
var xmldoc = new XmlDocument();
xmldoc.LoadXml(doc.ToString());
list.UpdateListItems(listname, xmldoc.DocumentElement);
}
Then I call it like this:
var fields = new Dictionary<string, string>();
fields.Add("Test", "Dummy Text");
fields.Add("MrTermSet", "Page|a4ba29c1-3ed5-47e9-b43f-36bc59c0ea5c;Unit|4237dfbe-22a2-4d90-bd08-09f4a8dd0ada");
UploadTestFile(#"C:\Temp\TestFile2.doc", #"http://mysharepointserver/Documents/", fields);
I would however prefer to call it like this:
var fields = new Dictionary<string, string>();
fields.Add("Test", "Dummy Text");
fields.Add("MrTermSet", "Page;Unit");
UploadTestFile(#"C:\Temp\TestFile2.doc", #"http://mysharepointserver/Documents/", fields);

Related

Create Folder and Update Title and Custom Field in Sharepoint Online

I try to create folder in sharepoint online, based on some of tutorial. the problem comes since creating folder is not given "Title" column value.
I want to create folder and also update column "Title".
here is the code for create folder
public string CreateDocumentLibrary(string siteUrl, string relativePath)
{
//bool responseResult = false;
string resultUpdate = string.Empty;
string responseResult = string.Empty;
if (siteUrl != _siteUrl)
{
_siteUrl = siteUrl;
Uri spSite = new Uri(siteUrl);
_spo = SpoAuthUtility.Create(spSite, _username, WebUtility.HtmlEncode(_password), false);
}
string odataQuery = "_api/web/folders";
byte[] content = ASCIIEncoding.ASCII.GetBytes(#"{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '" + relativePath + "'}");
string digest = _spo.GetRequestDigest();
Uri url = new Uri(String.Format("{0}/{1}", _spo.SiteUrl, odataQuery));
// Set X-RequestDigest
var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Headers.Add("X-RequestDigest", digest);
// Send a json odata request to SPO rest services to fetch all list items for the list.
byte[] result = HttpHelper.SendODataJsonRequest(
url,
"POST", // reading data from SP through the rest api usually uses the GET verb
content,
webRequest,
_spo // pass in the helper object that allows us to make authenticated calls to SPO rest services
);
string response = Encoding.UTF8.GetString(result, 0, result.Length);
if (response != null)
{
//responseResult = true;
responseResult = response;
}
return responseResult;
}
I already tried to use CAML, but, the problem is, the list of sharepoint is big, so got the error prohibited access related to limit tresshold.
Please help.
Refer below code to update folder name.
function renameFolder(webUrl,listTitle,itemId,name)
{
var itemUrl = webUrl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items(" + itemId + ")";
var itemPayload = {};
itemPayload['__metadata'] = {'type': getItemTypeForListName(listTitle)};
itemPayload['Title'] = name;
itemPayload['FileLeafRef'] = name;
var additionalHeaders = {};
additionalHeaders["X-HTTP-Method"] = "MERGE";
additionalHeaders["If-Match"] = "*";
return executeJson(itemUrl,"POST",additionalHeaders,itemPayload);
}
function getItemTypeForListName(name) {
return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}

Update/Change custom TaxonomyFieldValue in document library list in sharepoint using C# CSOM

list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}

NetSuite SuiteTalk API - Get Inventory Details

I'm using the SuiteTalk (API) service for NetSuite to retrieve a list of Assemblies. I need to load the InventoryDetails fields on the results to view the serial/lot numbers assigned to the items. This is the current code that I'm using, but the results still show those fields to come back as NULL, although I can see the other fields for the AssemblyBuild object. How do I get the inventory details (serials/lot#'s) to return on a transaction search?
public static List<AssemblyBuildResult> Get()
{
var listAssemblyBuilds = new List<AssemblyBuildResult>();
var service = Service.Context();
var ts = new TransactionSearch();
var tsb = new TransactionSearchBasic();
var sfType = new SearchEnumMultiSelectField
{
#operator = SearchEnumMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new string[] { "_assemblyBuild" }
};
tsb.type = sfType;
ts.basic = tsb;
ts.inventoryDetailJoin = new InventoryDetailSearchBasic();
// perform the search
var response = service.search(ts);
response.pageSizeSpecified = true;
// Process response
if (response.status.isSuccess)
{
// Process the records returned in the response
// Get more records with pagination
if (response.totalRecords > 0)
{
for (var x = 1; x <= response.totalPages; x++)
{
var records = response.recordList;
foreach (var t in records)
{
var ab = (AssemblyBuild) t;
listAssemblyBuilds.Add(GetAssemblyBuildsResult(ab));
}
if (response.pageIndex < response.totalPages)
{
response = service.searchMoreWithId(response.searchId, x + 1);
}
}
}
}
// Parse and return NetSuite WorkOrder into assembly WorkOrderResult list
return listAssemblyBuilds;
}
After much pain and suffering, I was able to solve this problem with the following code:
/// <summary>
/// Returns List of AssemblyBuilds from NetSuite
/// </summary>
/// <returns></returns>
public static List<AssemblyBuildResult> Get(string id = "", bool getDetails = false)
{
// Object to populate and return results
var listAssemblyBuilds = new List<AssemblyBuildResult>();
// Initiate Service and SavedSearch (TransactionSearchAdvanced)
var service = Service.Context();
var tsa = new TransactionSearchAdvanced
{
savedSearchScriptId = "customsearch_web_assemblysearchmainlist"
};
// Filter by ID if specified
if (id != "")
{
tsa.criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
internalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new[] {
new RecordRef() {
type = RecordType.assemblyBuild,
typeSpecified = true,
internalId = id
}
}
}
}
};
}
// Construct custom columns to return
var tsr = new TransactionSearchRow();
var tsrb = new TransactionSearchRowBasic();
var orderIdCols = new SearchColumnSelectField[1];
var orderIdCol = new SearchColumnSelectField();
orderIdCols[0] = orderIdCol;
tsrb.internalId = orderIdCols;
var tranDateCols = new SearchColumnDateField[1];
var tranDateCol = new SearchColumnDateField();
tranDateCols[0] = tranDateCol;
tsrb.tranDate = tranDateCols;
var serialNumberCols = new SearchColumnStringField[1];
var serialNumberCol = new SearchColumnStringField();
serialNumberCols[0] = serialNumberCol;
tsrb.serialNumbers = serialNumberCols;
// Perform the Search
tsr.basic = tsrb;
tsa.columns = tsr;
var response = service.search(tsa);
// Process response
if (response.status.isSuccess)
{
var searchRows = response.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
foreach (SearchRow t in searchRows)
{
var transactionRow = (TransactionSearchRow)t;
listAssemblyBuilds.Add(GetAssemblyBuildsResult(transactionRow, getDetails));
}
}
}
// Parse and return NetSuite WorkOrder into assembly WorkOrderResult list
return listAssemblyBuilds;
}
private static string GetAssemblyBuildLotNumbers(string id)
{
var service = Service.Context();
var serialNumbers = "";
var tsa = new TransactionSearchAdvanced
{
savedSearchScriptId = "customsearch_web_assemblysearchlineitems"
};
service.searchPreferences = new SearchPreferences { bodyFieldsOnly = false };
tsa.criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
internalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new[] {
new RecordRef() {
type = RecordType.assemblyBuild,
typeSpecified = true,
internalId = id
}
}
}
}
};
// Construct custom columns to return
var tsr = new TransactionSearchRow();
var tsrb = new TransactionSearchRowBasic();
var orderIdCols = new SearchColumnSelectField[1];
var orderIdCol = new SearchColumnSelectField();
orderIdCols[0] = orderIdCol;
tsrb.internalId = orderIdCols;
var serialNumberCols = new SearchColumnStringField[1];
var serialNumberCol = new SearchColumnStringField();
serialNumberCols[0] = serialNumberCol;
tsrb.serialNumbers = serialNumberCols;
tsr.basic = tsrb;
tsa.columns = tsr;
var response = service.search(tsa);
if (response.status.isSuccess)
{
var searchRows = response.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
foreach (SearchRow t in searchRows)
{
var transactionRow = (TransactionSearchRow)t;
if (transactionRow.basic.serialNumbers != null)
{
return transactionRow.basic.serialNumbers[0].searchValue;
}
}
}
}
return serialNumbers;
}
private static AssemblyBuildResult GetAssemblyBuildsResult(TransactionSearchRow tsr, bool getDetails)
{
if (tsr != null)
{
var assemblyInfo = new AssemblyBuildResult
{
NetSuiteId = tsr.basic.internalId[0].searchValue.internalId,
ManufacturedDate = tsr.basic.tranDate[0].searchValue,
SerialNumbers = tsr.basic.serialNumbers[0].searchValue
};
// If selected, this will do additional NetSuite queries to get detailed data (slower)
if (getDetails)
{
// Look up Lot Number
assemblyInfo.LotNumber = GetAssemblyBuildLotNumbers(tsr.basic.internalId[0].searchValue.internalId);
}
return assemblyInfo;
}
return null;
}
What I learned about pulling data from NetSuite:
Using SavedSearches is the best method to pull data that doesn't automatically come through in the API objects
It is barely supported
Don't specify an ID on the SavedSearch, specify a criteria in the TransactionSearch to get one record
You will need to specify which columns to actually pull down. NetSuite doesn't just send you the data from a SavedSearch automatically
You cannot view data in a SavedSearch that contains a Grouping
In the Saved Search, use the Criteria Main Line = true/false to read data from the main record (top of UI screen), and line items (bottom of screen)

Retrieving documents from sharepoint 2010 document library

I am uploading a document to Document library. Along with this I am creating a field called 'FieldID' by combining 2 values. However I am unable to see this field in the document library and hence unable to query the document with this field.How can I see this field or how can I retrieve documents using this 'FieldID'. This is the code.
if (UploadFile.PostedFile != null || (UploadFile.PostedFile.ToString() != string.Empty))
{
String fileName = UploadFile.PostedFile.FileName.ToString();
string userLogin = SPContext.Current.Web.CurrentUser.LoginName;
Guid siteID = SPContext.Current.Site.ID;
SPDocumentLibrary exposureLibrary = null;
SPList listDoc = null;
SPFolder myLibrary = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(siteID))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
// exposureLibrary
try
{
// Check if the document library already exists
exposureLibrary = (oWeb.Lists[SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME] as SPDocumentLibrary);
exposureLibrary.ContentTypesEnabled = false;
exposureLibrary.EnableAttachments = false;
exposureLibrary.EnableFolderCreation = false;
exposureLibrary.EnableVersioning = true;
exposureLibrary.NoCrawl = true;
exposureLibrary.OnQuickLaunch = false;
/* create a Text field for ID */
SPFieldText field = (exposureLibrary.Fields["FILEID"] as SPFieldText);
// Check if the field is available
if (field == null)
{
SPFieldText fldID = (SPFieldText)exposureLibrary.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
exposureLibrary.Fields.Add(fldID);
}
//exposureLibrary.Update();
myLibrary = exposureLibrary.RootFolder;
}
catch
{
// Determine the GUID of the document library
Guid ExposureDocumentLibraryId = oWeb.Lists.Add(SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME, SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_DESCRIPTION, SPListTemplateType.DocumentLibrary);
listDoc = oWeb.Lists[ExposureDocumentLibraryId];
/* create a Text field for ID */
SPFieldText fldID = (SPFieldText)listDoc.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
listDoc.Fields.Add(fldID);
// Set properties of the document library
listDoc.ContentTypesEnabled = false;
listDoc.EnableAttachments = false;
listDoc.EnableFolderCreation = false;
listDoc.EnableVersioning = true;
listDoc.NoCrawl = true;
listDoc.OnQuickLaunch = false;
listDoc.Update();
myLibrary = listDoc.RootFolder;
}
// Prepare to upload
Boolean replaceExistingFiles = true;
// Upload document
SPFile spfile = myLibrary.Files.Add(UploadFile.FileName + "(" + ViewState[UIConstants.CUSTOMERID].ToString() + " - "+ViewState[UIConstants.MondiPlantID].ToString()+ ")", UploadFile.FileContent, replaceExistingFiles);
//spfile.Item["FILEID"]= ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
//myLibrary.Item["ID"] = ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
spfile.Item.Update();
oWeb.AllowUnsafeUpdates = false;`enter code here`
// Commit
myLibrary.Update();
// Update the document library
oWeb.Update();
}
}
});
}
exposureLibrary.Fields.Add(fldID); //after this step
//exposureLibrary.Update();
you need to uncomment this, because after a field is created in try block, list/library is not being updated

Need Help: Account Name on Contact Phone Call

I am new to CRM and have been able to figure out everything up to now. I have read so many post and internet post and tried them. I have watched some many videos. It seems it should be easy. The contact record has the ParentCustomerID, and ParentCustomerName that holds the account if there is one associated. Now I am just totally confused on the required steps.
Requirement: - I need Account Name to be displayed on the contact level phone call form and saved in phone call table so that it can be visible in the phone call view.
I have in Phone Call N:1 Relationship field str_companyid (lookup) primary Entity is Account with Referential behavior.
I tried a Phone Call N:1 Relationship field new_companystring (lookup) primary Entity is Contact with Referential behavior. I came to the conclusion that this is not a valid approach. Let me know if incorrect.
Do I need a N:N instead?
I have added the str_companyid field to the form. I went to the "Create a phone call for a contact" workflow process. On the "Create PhoneCall" step I have added the dynamic field {Company(Contact)}. After save and publishes; I created a phone call and it isn't populated.
I have tried different Web Resource JS. I have added the JS in the onload of the form properties.
Why doesn't something as easy as this work? I can't seem to get the retrieveRecord to work. I have also tried the xmlHttpObject object but it returns 0.
Can someone help assist me on what I am missing? What are the complete steps to accomplish this?
![I have screenshots below and the code I was running][1]
function PopulateCompanyName()
{
//get group GUID
if (Xrm.Page.getAttribute("to").getValue()[0].id != null) {
var lookup = Xrm.Page.getAttribute("to").getValue();
alert(lookup[0].id);
alert(lookup[0].typename);
alert(lookup[0].name);
alert(lookup);
SDK.JQuery.retrieveRecord(lookup[0].id,
lookup[0].typename,
"ParentCustomerID",
null,
function (lookup) {
Xrm.Page.getAttribute("Company").setValue(lookup[0].str_companyid);
});
}
else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
function GetCompany()
///Get lookup ID
{
alert("I am Here");
var lookupfield = Xrm.Page.getAttribute("to").getValue();
if (lookupfield != null && lookupfield [0] != null)
{
var householdlookupvalue = lookupfield [0].id;
}
else
{
var householdlookupvalue = " ";
}
alert("I am here2");
alert(householdlookupvalue);
}
// Prepare variables for a contact to retrieve.
var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
// Prepare the SOAP message.
var xml = ""+
""+
authenticationHeader+
""+
""+
"contact"+
""+lookupfield [0].id+""+
""+
""+
"parentcustomerid"+
""+
""+
""+
""+
"";
alert(xml );
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;
alert("at results");
var errorCount = resultXml.selectNodes('//error').length;
alert("errorCount " + errorCount); ////////////////////////////////////returns 0; it shouldn't
alert("After the result XML "+resultXml .toString() + " ::::");
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
}
// Display the retrieved value.
else
{
//Create an array to set as the DataValue for the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = resultXml.selectSingleNode("//q1:parentcustomerid").nodeTypedValue;
lookupItem.entityType = 'account';
lookupItem.name = resultXml.selectSingleNode("//q1:parentcustomerid").getAttribute("name");
// Add the object to the array.
lookupData[0] = lookupItem;
alert(lookupitem.name)
// Set the value of the lookup field to the value of the array.
Xrm.Page.getAttribute("str_companyid").setValue(lookupData);
}
var contact = new Array();
contact = Xrm.Page.getAttribute("to").getValue();
alert("I am here");
alert(contact);
if (contact == null || contact[0].entityType != "contact" || contact.length > 1) {
return;
}
alert("inside if")
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ParentCustomerId&$filter=ContactId eq guid'" + contact[0].id + "'";
var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", oDataSelect, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
retrieveReq.onreadystatechange = function () {
GetContactData(this);
};
retrieveReq.send();
}
I replied in the other forum but I post here as reference and with more technical details.
The to attribute of phonecall entity is a partylist type, this means that it can handle several records from different entities. In your case you want to get the Parent Account (field parentcustomerid) if a contact is inside the to field.
Your first code contains same typo and use the msdn Retrieve example, the second code uses CRM 4.0 endpoints, they are still supported inside CRM 2011, but it's better to avoid them so you can use the REST endpoint instead of the SOAP one.
a working code in your case can be:
function setToParentAccount() {
// set only if to Field (Recipient) has 1 record and is a contact
if (Xrm.Page.getAttribute("to").getValue() != null) {
var recipient = Xrm.Page.getAttribute("to").getValue();
if (recipient.length == 1 && recipient[0].entityType == "contact") {
var contactId = recipient[0].id;
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var contactRequest = new XMLHttpRequest();
contactRequest.open("GET", ODataPath + "/ContactSet(guid'" + contactId + "')", false);
contactRequest.setRequestHeader("Accept", "application/json");
contactRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
contactRequest.send();
if (contactRequest.status === 200) {
var retrievedContact = JSON.parse(contactRequest.responseText).d;
var parentAccount = retrievedContact.ParentCustomerId;
if (parentAccount.Id != null && parentAccount.LogicalName == "account") {
var newParentAccount = new Array();
newParentAccount[0] = new Object();
newParentAccount[0].id = parentAccount.Id;
newParentAccount[0].name = parentAccount.Name;
newParentAccount[0].entityType = parentAccount.LogicalName;
Xrm.Page.getAttribute("str_companyid").setValue(newParentAccount);
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
} else {
alert("error");
}
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
}
to be called inside OnLoad event and OnChange event of the to field.

Resources