Read/Write SharePoint User Field [Word 2010 VSTO] - c#

I've been experimenting with reading SharePoint 2013 Site Column metadata from within a Word 2010 Application-level C# VSTO.
For testing I've set-up Site Columns for every type that SharePoint uses, then created a Document Content Type that ties to them all -- thus all these columns are embedded into the Word document (looks to be stored within customXml within the document file).
By reading from the _Document.ContentTypeProperties property within the VSTO's code, I can access most types, but I'm having difficulty accessing a 'Person or Group' Site Column's data -- I'm getting COM Exceptions attempting to read or write to an item's .Value property.
By looking at the XSD schema in customXml, I can see a single-value User column is made up of three values: DisplayName (type string), AccountType (type string) and AccountId (type UserId) -- however I don't see a way to read/write from/to this within the VSTO? Multi-value User columns appear to be completely different, and are made up of two string values: an ID (appears to be the SharePoint user's ID) and a string-based ID (or at least that's what I think the i:0#.w|domain\userid is, anyway).
Word itself can edit both single- and multi-valued User column data via the Document Panel, but only if Word is currently connected to SharePoint -- otherwise the functionality is disabled. I'd assume the same would be true for the VSTO, if I could access the values at all...
My two questions are:
Is there a way to read/write single- and multi-value User fields from within VSTO code (even if it's not via the _Document.ContentTypeProperties property)?
Is there a way to do Q1 when if not connected to SharePoint (if, say, the values are known to the code)?
(I've been somewhat overly verbose in case my workings so far are useful to someone else even if I get no answers; there doesn't seem to be a great amount of information about this anywhere)

With some provisos, I believe you can do read/update these fields using VSTO - although I haven't actually created a working example using VSTO, the same objects as I'd use in Word VBA are available - the code snippets below are VBA.
The person/group values that are displayed in the DIP are stored in a Custom XML Part, even when the SharePoint server is unavailable. So the problem is not modifying the values - it's a CRUD operation, in essence - but knowing what values you can use, particularly in the multi-valued case. If you know how to construct valid values (let's say you have an independent list of email addresses) then you can make the modifications locally. Personally, I don't know how I would construct a valid value for the multi-valued case so I'd basically have to contact the server.
So assuming you have the data you need to update locally...
When SharePoint serves a Word Document, it inserts/updates several Custom XML Parts. One contains a set of schemas (as you have discovered). Another contains the data. All you really need to do is access the correct Custom XML Part, find the XML Element corresponding to your SharePoint user/group column, then it's a CRUD operation on the subElements of that Element.
You can find the correct Custom XML Part using the appropriate namespace name, e.g.
Const metaPropDataUri as String = _
"http://schemas.microsoft.com/office/2006/metadata/properties"
Dim theDoc as Word.Document
Dim cxp as Office.CustomXMLPart
Dim cxps as Office.CustomXMLParts
Set theDoc = ActiveDocument
Set cxps = theDoc.CustomXMLParts.SelectByNamespace(metaPropDataUri)
If there is more than one part associate with that Namespace, I don't know for sure how to choose the correct one. AFAIK Word/Sharepoint only ever creates one, and experiments suggest that if there is another one, SharePoint works with the first one. So I use
Set cxp = cxps(1)
At this point you need to know the XML Element name of the person/group column. It may be the same as the external name (the one you can see in the SharePoint list), but if for example someone called the Sharepoint column "person group", the Element name will be "person_x0020_group". If the name isn't going to vary, you can get it from the schema XML as a one-off task. Or it may be easy to generate the correct element name from any given SharePoint name. Otherwise, you can get it dynamically from the Schema XML, which you can get (as a string) using
theDoc.ContentTypeProperties.SchemaXML
What you need to do then is find the element with attribute ma:displayName="the external name" and get the value of the name attribute. I would imagine that's quite straightforward using c#, a suitable XML object, and a bit of XPath, say
//xsd:element[#ma:displayName='person group'][1]/#name
which should return 'person_x0020_group'
You can then get the Element node for your data, e.g. something along the lines of
Dim cxn As Office.CustomXMLNode
Set cxn = cxp.SelectSingleNode("//*[name()='person_x0020_group'][1]")
Or you may find it's preferable to get the namespace Uri of the Elements in this Custom XML Part and use that to help you locate the correct node. The name is a long hex string assigned by SharePoint. You can get it from the Schema XML using, e.g.
//xsd:schema[1]/#targetNamespace
Once you have your node, you would use the known structures (i.e. the ones you have found in the Schemas) to get/modify/create child nodes as required.

of course you can. You should use the SharePoint Client-side Object model (CSOM) to manipulate SharePoint data from a location away from the server. The only thing you will need is the URL of your SharePoint site.
You can then connect through CSOM like this:
ClientContext context = new ClientContext("SITEURL");
Site site = context.Site;
Web web = context.Web;
context.Load(site);
context.Load(web);
context.ExecuteQuery();
See here an example to set a single user field:
First get the ID of the user through ensuring the username
u = context.Web.EnsureUser(UserOrGroupName);
context.Load(u);
context.ExecuteQuery();
To set the value, you can use this string format:
userid;#userloginname;#
To set the field use this:
item[myusercolumn] = "userid;#userloginname;#";
item.Update();
context.ExecuteQuery();
To set a multi user field, you can use the same code, just use ;# to concat the different usernames, such as:
item[myusercolumn] = "userid1;#userloginname1;#userid2;#userloginname2;#userid3;#userloginname3;#";
item.Update();
context.ExecuteQuery();
Hope this helps

Related

Save RichTextBox content containing both images and custom token elements

Struggling with how to successfully save and load my System.Windows.Controls.RichTextBox content containing all of the following: formatted text, images, custom type-defined token elements, custom dynamic token elements.
By token elements I mean my custom classes inheriting from System.Windows.Documents.Run where type-defined is such that does not need to remember any dynamically set property values (since action is taken based on the type which needs to be remembered after loading) and dynamic ones are such that need to also retain dynamically set properties (action is taken not only based on type, but also based on these set values).
I know of the following 3 methods to save/load, neither of which is sufficient:
1)
string xamlStream = System.Windows.Markup.XamlWriter.Save(myRichTxtBx.Document);
and then saving the string
2)
TextRange content = new TextRange(myRichTxtBx.Document.ContentStart, myRichTxtBx.Document.ContentEnd);
content.Save(myFileStream, DataFormats.XamlPackage, true);
3)
TextRange content = new TextRange(myRichTxtBx.Document.ContentStart, myRichTxtBx.Document.ContentEnd);
content.Save(myFileStream, DataFormats.Xaml, true);
These are the problems with those:
1) unable to load image after restarting the application (but remembers properties)
2) does not remember the properties (but is able to load image after restarting the app)
3) won't load image not even in the same instance of the app and also does not remember the property values
I could only find answers resolving image saving issues (2) or property issues (1), but never both.
The goal is to have a tokenizable RichTextBox, where tokens are either replaced by values from database based on provided ORM object (= type-defined token) or by dynamically set values by user based again on a provided ORM object.
I have solved the issue by a very ugly workaround:
To save the document I use the method (1) described above. Before this, I traverse the FlowDocument by a custom walker and replace each image element with a custom inline token element (much like the other tokens). A hash ID is assigned as a property to this substitute element and the image itself is saved having the hash as its file name (serves to identify token with the image file). Images, along with the main document (saved by method (1)), are packaged into a single file.
When loading everything back, package is unpacked, document loaded keeping the tokens with their properties and substitute image elements are replaced by the actual images from the files saved in the package using once again the before-mentioned custom walker and the established hash token-file relation.

SalesForce - Get all the fields of an object using .Net SDK or Api

We have our system from where we want to push the records (e.g. Contact, Account, Opportunity, etc.) to SalesForce.
To achieve this, we have used ForceToolKit for .Net. We are able to insert\update the records successfully using the ForceToolKit functions.
Example:
dynamic contact = new ExpandoObject();
contact.FirstName = "FirstName";
contact.LastName = "Last";
contact.Email = "test#test.com";
contact.MobilePhone = "1234567890";
var successResponse = await forceClient.CreateAsync("Contact", contactList);
The Issue we are facing is as mentioned below.
In our source system, we have few custom fields which are not standard field in SalesForce and it can be different for different users.
So, first we have to map the custom fields between our source system and the SalesForce.
We want to fetch all the fields of SalesForce object in order to map the fields.
We are unable to find any function in ForceToolkitForNet.
As described here, we have tried QueryById function by using the dynamic return type, but it is throwing an exception.
var contactFields = await forceClient.QueryByIdAsync<dynamic>("Contact", successResponse.Id);
Exception: "SELECT FROM Contact where Id = '{contactId}' Incorrect syntax near FROM".
What are the ways to get the fields of any object of SalesForce.
Can anyone help us on getting the fields of an object using SalesForceToolkit or SalesForceApi?
SOQL doesn't have a SELECT * FROM Account concept, you need to learn the fields beforehand. You have few options here.
You can use "describe" calls. I've recently answered similar question but it was about REST API: https://stackoverflow.com/a/48436870/313628, I think your solution is SOAP-based.
If you'd be doing this by hand...
Start here: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_list_describe.htm
List of all objects visible to your user: describeGlobal()
Get details (incl field names) for one object: describeSobject() or more: describeSobjects()
As you're using the toolkit - there's a chance these methods already are in there somewhere. Experiment a bit. Between the C# examples under the links I gave you and the library you should be able to figure something out.
I mean I'm naive but just searching the repo for "describe" looks promising: https://github.com/developerforce/Force.com-Toolkit-for-NET/search?utf8=%E2%9C%93&q=describe&type=, maybe this example
There's also a way to not learn this info at runtime but consume a WSDL file generated out of Salesforce with all fields & generate C# code out of it. The downside is that you'd need to regenerate it every time you want to support new object/field in your app. Read about "Enterprise WSDL" to get started.
Last but not least - there are more or less friendly tools that dump the Salesforce metadata. i'm a fan of https://www.datasert.com/products/realforce/ but just have a look around. Hell, even exporting some records with DataLoader will give you all field names if that's all you need.

Umbraco multilanguage with URL change

I am working with Umbraco v7.x. I have few static pages and they need to be added in two languages(en/da).
I know there are two ways to translate
1- Copy folder and assign different culture and hostname and add fields data according to language.
2 - Use dictionary items.
But my problem is customer wants to have custom fields on all pages so he can change static page data without having the need to ask developer. So if I use first method to change language that would also change URL which is not required for this solution.
Second I use dictionary than how can customer can change field data because he had to go to dictionary items and make any change there. This is not a problem but text needs to be formatted and this is not possible if I use dictionary items.
Any work around to this problem.
Thanks
I recommend using Vorto if you want a 1:1 translated site (meaning each piece of content has a translation for each language. Use dictionary items for text that was hard-coded into your template but Vorto will wrap your property editors so that you can edit each language in the same node. You can then use HasVortoValue() and GetVortoValue() instead of HasValue() and GetPropertyValue() methods that come with Umbraco. This will return the correct value based on the culture of the request. You will also need to configure Umbraco to load the multilingual content by setting a host name and associate that with a culture. You do that by selecting "Culture and Hostnames" in the contextual menu for the home node and and click "Add Domain" (you will need to have first added the language in the Settings section):
Alternatively, if you want to use a subfolder for each language instead of a differeent domain (e.g. sitename.com/english instead of english.sitename.com) you can create a custom Content Finder. I have written a couple blog posts on how to do that here and here.

How do I use an enum with custom values for a Sharepoint Web part?

I'm trying to design a Web Part that has a drop-down list for the user to choose from. Eventually, these values will be automatically generated based on some kind of outside data source, so they're going to have somewhat arbitrary numeric values associated with them. This is the code I have now:
public enum filterChoice
{
All=0,
BOCC=12,
Sustainability=15,
Clerk=4,
DA=13,
Emergency=7,
Highlights=3,
POS=6,
PR=1,
PH=5,
SHPR=2,
Test=8,
Transportation=14,
Volunteer=16
};
These are different categories I want the user to choose from. When I choose one and save the settings for my Web Part, Sharepoint is only saving the values in numeric order; that is, All=0, BOCC=1, Sustainability=3 [...] so my Web Part then thinks the user chose the value with the corresponding number (PR when they chose BOCC, Highlights when they chose Sustainability, etc.) How can I make Sharepoint honor my custom values?
Guess you could put only strings in your enumeration and do the translation to the associated numeric values in the code of your webpart using a Dictionary<> or something?

XML tag name being overwritten with a type defined

We are communicating with a 3rd party service using via an XML file based on standards that this 3rd party developed. They give us an XML template for each "transaction" and we read it into a DataSet using System.Data.DataSet.ReadXML, set the proper values in the DataSet, and then write the XML back using System.Data.DataSet.WriteXML. This process has worked for several different files. However, I am now adding an additional file which requires that an integer data type be set on one of the fields. Here is a scaled down version:
<EngineDocList>
<DocVersion>1.0</DocVersion>
<EngineDoc>
<MyData>
<FieldA></FieldA>
<FieldB></FieldB>
<ClientID DataType="S32"></ClientID>
</MyData>
</EngineDoc>
</EngineDocList>
When I look at the DataSet created by my call to ReadXML to this file, the MyData table has columns of FieldA, FieldB, and MyData_ID. If I then set the value of MyData_ID and then make the call to WriteXML, the export XML has no value for ClientID. Once again, if I take a way the DataType, then I do have a ClientID column, I can set it properly, and the exported XML has the proper value. However, the third party requires that this data type be defined.
Any thoughts on why the ReadXML would be renaming this tag or how I could otherwise get this process to work? Alternatively, I could revamp the way we are reading and writing the XML, but would obviously rather not go down this path although these suggestions would also be welcome. Thanks.
I would not do this with a DataSet. It has a specific focus on simulating a relational model. Much XML will not follow that model. When the DataSet sees things that don't match it's idea of the world, it either ignores them or changes them. In neither case is it a good thing.
I'd use an XmlDocument for this.

Categories