Get Page owner contact email and display in SharePoint 2010 Masterpage - visual-studio-2010

I've built out a solution with multiple masterpages/page layouts as features for a set of SharePoint 2010 publishing site collections.
One consistent request is to be able to grab the page owner contact email and display it in the footer of the masterpage. If the page Contact Email isn't entered, then I need to grab the page owner data from the People Picker, and grab the contact email from that.
I don't want to have to add every single publishing page layout to my solution, and manually add the Contact Email column into a place holder, that seems crazy to me. I figure there has to be a way to grab the page owner data from within the masterpage, but I can't figure it out. I started looking at the jQuery SPServices library, but so far I haven't been able to figure it out there, either.
Does anyone have any experience in adding a contact email using the supplied page owner contact information in the Masterpage?

OK, in order to resolve this, you need jQuery 1.7.x+ and the SPServices jQuery library version 0.7.2 or greater installed on your site.
Use GetListItems as the operation from SPServices.
I'm searching for pages within the Pages directory, so listName is "Pages".
The CAML View Fields are basically the columns for PublishingContactEmail and PublishingContact. I found those using u2u's CAML builder version 4.0.0.0
The ows_ variables can be found in the xml view of the POST object in firebug.
The ows_PublishingContact returns a long nasty string of the contact's information. Fortunately the email address is surrounded by ,#, which made splitting it into an array and then searching for an email # easy, but that's why that's there.
function get_page_contact_email() {
var thisPageID = _spPageContextInfo.pageItemId;
var e;
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Pages",
CAMLViewFields: "<ViewFields><FieldRef Name='PublishingContactEmail' /><FieldRef Name='PublishingContact' /></ViewFields>",
CAMLQueryOptions: "<QueryOptions><ExpandUserField>True</ExpandUserField></QueryOptions>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function () {
if (thisPageID == $(this).attr("ows_ID")) {
if ($(this).attr("ows_PublishingContactEmail")) { // if page email is set
e = $(this).attr("ows_PublishingContactEmail");
} else if ($(this).attr("ows_PublishingContact")) { //otherwise use contact info
var contact = $(this).attr("ows_PublishingContact").split(",#");
for (var c = 0; c < contact.length; c++) {
if (contact[c].indexOf("#") != -1) {
e = contact[c];
}
}
} else { //or nothing is set.
e = false;
}
}
});
}
});
return e;
}

Related

How to automatically update the UI after user updates a userProperty in Google Apps Script Workspace Add-ons for Google Sheets?

I want to automagically update the UI with a new user setting after the user updates that setting by submitting a user input from.
Currently, I am attempting to use the updateCard() method from the CardService as shown in the below code. The docs are here but they do not contain any example code.
I expect that after the user provides the input and submits it, the current card will be replaced by an updated card that will contain the new setting.
However, what’s actually happening is that the card I expect to update is not updating automatically. To see the change, the user has to manually refresh the app homepage. After, and only after, a manual refresh, does the homepage card update with the new setting.
How do I update the homepage automatically without requiring a manual refresh?
Code.gs
const changedProperty = PropertiesService.getUserProperties().getProperty( MY_SETTING );
const newNavigation = CardService.newNavigation();
const cardPoppedToRoot = newNavigation.popToRoot();
const homepageCard = getCardFromUiConfig( HOMEPAGE_UI_CONFIG, );
const updatedCard = cardPoppedToRoot.updateCard( homepageCard, );
return updatedCard;
I also tried the following code per this answer and the results are exactly the same as with the above code.
Code.gs
return CardService.newActionResponseBuilder()
.setNavigation(
CardService.newNavigation()
.popToRoot()
.updateCard( homepageCard, )
).build();
When I try to configure my appsscript.json file as shown in the answer as follows:
appsscript.json
"homepageTrigger": {
"runFunction": "onHomepage"
},
"contextualTriggers":[
{
"unconditional":{},
"onTriggerFunction": "onHomepage"
}
]
I get the following error:
"appsscript.json" has errors: Invalid manifest: unknown fields: [addOns.common.contextualTriggers]
I think that that is only possible for Gmail add-ons.
contextualTriggers can't be child of common.
From https://developers.google.com/apps-script/manifest/addons#common (links not included):
Common
The manifest configuration for parameters that are common for every host application. Some values defined here are used as a default when specific values for a particular host are omitted.
{
"homepageTrigger": {
object (HomepageTrigger)
},
"layoutProperties": {
object (LayoutProperties)
},
"logoUrl": string,
"name": string,
"openLinkUrlPrefixes": [
string
],
"universalActions": [
{
object (UniversalAction)
}
],
"useLocaleFromApp": boolean
}
AFAIK contextualTriggers can only be used with Gmail add-ons. From https://developers.google.com/apps-script/manifest/gmail-addons (links not included):
Gmail
The Google Workspace add-on manifest configuration for Gmail extensions. See Extending Gmail with Google Workspace add-ons for more information.
{
"authorizationCheckFunction": string,
"composeTrigger": {
object (ComposeTrigger)
},
"contextualTriggers": [
{
object (ContextualTrigger)
}
],
"homepageTrigger": {
object (HomepageTrigger)
}
}
Related
How to fully refresh Google Addon Card (Google Sheets) which includes a drop down menu populated using sheet data when data changes?

How to get query sys_id of current.sys_id Service Portal (ServiceNow)

I have a question regarding a small issue that I'm having. I've created a widget that will live on the Service Portal to allow an admin to Accept or Reject requests.
The data for the widget is pulling from the Approvals (approval_approver) table. Under my GlideRecord, I have a query that checks for the state as requested. (Ex. addQuery('state', 'requested'))
To narrow down the search, I tried entering addQuery('sys_id', current.sys_id). When I use this query, my script breaks and I get an error on the Service Portal end.
Here's a sample of the GlideRecord script I've written to Accept.
[//Accept Request
if(input && input.action=="acceptApproval") {
var inRec1 = new GlideRecord('sysapproval_approver');
inRec1.addQuery('state', 'requested');
//inRec1.get('sys_id', current.sys_id);
inRec1.query();
if(inRec1.next()) {
inRec1.setValue('state', 'Approved');
inRec1.setValue('approver', gs.getUserID());
gs.addInfoMessage("Accept Approval Processed");
inRec1.update();
}
}][1]
I've research the web, tried using $sp.getParameter() as a work-around and no change.
I would really appreciate any help or insight on what I can do different to get script to work and filter the right records.
If I understand your question correctly, you are asking how to get the sysId of the sysapproval_approver record from the client-side in a widget.
Unless you have defined current elsewhere in your server script, current is undefined. Secondly, $sp.getParameter() is used to retrieve URL parameters. So unless you've included the sysId as a URL parameter, that will not get you what you are looking for.
One pattern that I've used is to pass an object to the client after the initial query that gets the list of requests.
When you're ready to send input to the server from the client, you can add relevant information to the input object. See the simplified example below. For the sake of brevity, the code below does not include error handling.
// Client-side function
approveRequest = function(sysId) {
$scope.server.get({
action: "requestApproval",
sysId: sysId
})
.then(function(response) {
console.log("Request approved");
});
};
// Server-side
var requestGr = new GlideRecord();
requestGr.addQuery("SOME_QUERY");
requestGr.query(); // Retrieve initial list of requests to display in the template
data.requests = []; // Add array of requests to data object to be passed to the client via the controller
while(requestsGr.next()) {
data.requests.push({
"number": requestsGr.getValue("number");
"state" : requestsGr.getValue("state");
"sysId" : requestsGr.getValue("sys_id");
});
}
if(input && input.action=="acceptApproval") {
var sysapprovalGr = new GlideRecord('sysapproval_approver');
if(sysapprovalGr.get(input.sysId)) {
sysapprovalGr.setValue('state', 'Approved');
sysapprovalGr.setValue('approver', gs.getUserID());
sysapprovalGr.update();
gs.addInfoMessage("Accept Approval Processed");
}
...

Add a note using the OOB dialog from a webresource

Im working with Microsoft Dynamics CRM. The client is requesting to be able to add notes from a webresources.
I thought that something like this will do the trick:
Xrm.Utility.openEntityForm("annotation", null, parameters);
or even the classic
/main.aspx?etn=annotation&pagetype=entityrecord#
But I receive a "Query Builder Error: The specified record type does not exist in Microsoft Dynamics CRM"
It seems like notes is not something we can open in that way but I cannot found the right way (if even exists!)
Any help?
Maybe this can help someone in the future: This will open a dialog with the Regarding field filled, the textboxs for title and description and the attachments field.
function createNote() {
var EntityID = Xrm.Page.data.entity.getId(); // to get entity id
var ServicerURL = Xrm.Page.context.getClientUrl(); // to get server url
var etc =Xrm.Page.context.getQueryStringParameters().etc; // to get entity type code, make sure not to hard code it, because it could changed in another deployment
var NotesURL = ServicerURL + "/notes/edit.aspx?pId=" + EntityID + "&pType=" + etc;
var features = "copyhistory=no,top=110,left=280,width=600,height=400";
window.open(NotesURL, "", features);
}

Google+ insert moment using google-api-dotnet-client

I am trying to write an activity in Google+ using the dotnet-client. The issue is that I can't seem to get the configuration of my client app correctly. According to the Google+ Sign-In configuration and this SO question we need to add the requestvisibleactions parameter. I did that but it did not work. I am using the scope https://www.googleapis.com/auth/plus.login and I even added the scope https://www.googleapis.com/auth/plus.moments.write but the insert still did not work.
This is what my request url looks like:
https://accounts.google.com/ServiceLogin?service=lso&passive=1209600&continue=https://accounts.google.com/o/oauth2/auth?scope%3Dhttps://www.googleapis.com/auth/plus.login%2Bhttps://www.googleapis.com/auth/plus.moments.write%26response_type%3Dcode%26redirect_uri%3Dhttp://localhost/%26state%3D%26requestvisibleactions%3Dhttp://schemas.google.com/AddActivity%26client_id%3D000.apps.googleusercontent.com%26request_visible_actions%3Dhttp://schemas.google.com/AddActivity%26hl%3Den%26from_login%3D1%26as%3D-1fbe06f1c6120f4d&ltmpl=popup&shdf=Cm4LEhF0aGlyZFBhcnR5TG9nb1VybBoADAsSFXRoaXJkUGFydHlEaXNwbGF5TmFtZRoHQ2hpa3V0bwwLEgZkb21haW4aB0NoaWt1dG8MCxIVdGhpcmRQYXJ0eURpc3BsYXlUeXBlGgdERUZBVUxUDBIDbHNvIhTeWybcoJ9pXSeN2t-k8A4SUbfhsygBMhQivAmfNSs_LkjXXZ7bPxilXgjMsQ&scc=1
As you can see from there that there is a request_visible_actions and I even added one that has no underscore in case I got the parameter wrong (requestvisibleactions).
Let me say that my app is being authenticated successfully by the API. I can get the user's profile after being authenticated and it is on the "insert moment" part that my app fails. My insert code:
var body = new Moment();
var target = new ItemScope();
target.Id = referenceId;
target.Image = image;
target.Type = "http://schemas.google.com/AddActivity";
target.Description = description;
target.Name = caption;
body.Target = target;
body.Type = "http://schemas.google.com/AddActivity";
var insert =
new MomentsResource.InsertRequest(
// this is a valid service instance as I am using this to query the user's profile
_plusService,
body,
id,
MomentsResource.Collection.Vault);
Moment result = null;
try
{
result = insert.Fetch();
}
catch (ThreadAbortException)
{
// User was not yet authenticated and is being forwarded to the authorization page.
throw;
}
catch (Google.GoogleApiRequestException requestEx)
{
// here I get a 401 Unauthorized error
}
catch (Exception ex)
{
} `
For the OAuth flow, there are two issues with your request:
request_visible_actions is what is passed to the OAuth v2 server (don't pass requestvisibleactions)
plus.moments.write is a deprecated scope, you only need to pass in plus.login
Make sure your project references the latest version of the Google+ .NET client library from here:
https://developers.google.com/resources/api-libraries/download/stable/plus/v1/csharp
I have created a project on GitHub showing a full server-side flow here:
https://github.com/gguuss/gplus_csharp_ssflow
As Brettj said, you should be using the Google+ Sign-in Button as demonstrated in the latest Google+ samples from here:
https://github.com/googleplus/gplus-quickstart-csharp
First, ensure you are requesting all of the activity types you're writing. You will know this is working because the authorization dialog will show "Make your app activity available via Google, visible to you and: [...]" below the text that starts with "This app would like to". I know you checked this but I'm 90% sure this is why you are getting the 401 error code. The following markup shows how to render the Google+ Sign-In button requesting access to Add activities.
<div id="gConnect">
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-clientId="YOUR_CLIENT_ID"
data-accesstype="offline"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
Assuming you have a PlusService object with the correct activity type set in data-requestvisibleactions, the following code, which you should be able to copy/paste to see it work, concisely demonstrates writing moments using the .NET client and has been tested to work:
Moment body = new Moment();
ItemScope target = new ItemScope();
target.Id = "replacewithuniqueforaddtarget";
target.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
target.Type = "";
target.Description = "The description for the activity";
target.Name = "An example of add activity";
body.Target = target;
body.Type = "http://schemas.google.com/AddActivity";
MomentsResource.InsertRequest insert =
new MomentsResource.InsertRequest(
_plusService,
body,
"me",
MomentsResource.Collection.Vault);
Moment wrote = insert.Fetch();
Note, I'm including Google.Apis.Plus.v1.Data for convenience.
Ah it's that simple! Maybe not? I am answering my own question and consequently accept it as the answer (after a few days of course) so others having the same issue may be guided. But I will definitely up-vote Gus' answer for it led me to the fix for my code.
So according to #class answer written above and as explained on his blog the key to successfully creating a moment is adding the request_visible_actions parameter. I did that but my request still failed and it is because I was missing an important thing. You need to add one more parameter and that is the access_type and it should be set to offline. The OAuth request, at a minimum, should look like: https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/plus.login&response_type=code&redirect_uri=http://localhost/&request_visible_actions=http://schemas.google.com/AddActivity&access_type=offline.
For the complete and correct client code you can get Gus' example here or download the entire dotnet client library including the source and sample and add what I added below. The most important thing that you should remember is modifying your AuthorizationServerDescription for the Google API. Here's my version of the authenticator:
public static OAuth2Authenticator<WebServerClient> CreateAuthenticator(
string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException("clientId cannot be empty");
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException("clientSecret cannot be empty");
var description = GoogleAuthenticationServer.Description;
var uri = description.AuthorizationEndpoint.AbsoluteUri;
// This is the one that has been documented on Gus' blog site
// and over at Google's (https://developers.google.com/+/web/signin/)
// This is not in the dotnetclient sample by the way
// and you need to understand how OAuth and DNOA works.
// I had this already, see my original post,
// I thought it will make my day.
if (uri.IndexOf("request_visible_actions") < 1)
{
var param = (uri.IndexOf('?') > 0) ? "&" : "?";
description.AuthorizationEndpoint = new Uri(
uri + param +
"request_visible_actions=http://schemas.google.com/AddActivity");
}
// This is what I have been missing!
// They forgot to tell us about this or did I just miss this somewhere?
uri = description.AuthorizationEndpoint.AbsoluteUri;
if (uri.IndexOf("offline") < 1)
{
var param = (uri.IndexOf('?') > 0) ? "&" : "?";
description.AuthorizationEndpoint =
new Uri(uri + param + "access_type=offline");
}
// Register the authenticator.
var provider = new WebServerClient(description)
{
ClientIdentifier = clientId,
ClientSecret = clientSecret,
};
var authenticator =
new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization)
{ NoCaching = true };
return authenticator;
}
Without the access_type=offline my code never worked and it will never work. Now I wonder why? It would be good to have some explanation.

How to save a record and immediately use its GUID

I'm executing some javascript from a ribbon button and what I want to do is save the record that I am creating and then immediately use its GUID for some code a bit further on. Each time I try it the GUID is coming back null even though I'm requesting it after the record has been saved. If I try the button again after I've saved it then it works, but not as I'm saving it.
Is there a way to do this?
function RibbonButton_AddProduct()
{
//Save the Record
Xrm.Page.data.entity.save();
LoadProductCreate();
}
function LoadProductCreate()
{
var serverUrl;
var errorMessage = "Context to retrieve the Server URL is not available.";
if (typeof GetGlobalContext != "undefined"){
serverUrl = GetGlobalContext().getServerUrl();
} else {
if (typeof Xrm != "undefined"){
serverUrl = Xrm.Page.context.getServerUrl();
} else {
alert(errorMessage);
return;
}
}
if (serverUrl.match(/\/$/)){
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var recordId = Xrm.Page.data.entity.getId();
alert(recordId);
var url = serverUrl + "/main.aspx?etc=10030&extraqs=%3f_CreateFromId%3d%"+recordId
+"%257d%26_CreateFromType%3d10029%26etc%3d10030%26"
+"pagemode%3diframe%26preloadcache%3d1345465354543&pagetype=entityrecord";
window.open(url);
}
Here’s a different approach to solving this problem.
What you are trying to do is ‘working against the system’ - you are effectively making two save buttons. In the rest of Crm when the Id is required for a ribbon button the record must first be saved. E.g. you can’t use the dialog or workflow buttons on an unsaved record, you also can’t 'add new/existing' to an unsaved record.
So my solution would be to disable the button on unsaved forms, force the user to save the record manually and then allow them to use your button - this is the way Crm is meant to be used, and is the way the rest of Crm will work.
You should not work against the system, you should work with it, you have a product to customise and extend – not change.
If this doesn’t meet your requirement I would suggest uses Greg’s suggestion (1) of having flags, though it sounds a bit messy - but then this is a requirement that inherently is.
You could try one of two things:
Add a hidden boolean attribute to your form(e.g. "new_launchProductCreate"), set it in code prior to save and then read it onLoad.
Instead of setting the value prior to create (and therefore potentially commiting it to the database), you could create a plugin registered against the "Create" step of your record that injects a boolean value into the Entity.Attributes collection as the record is returned to the user. This would prevent the value persisting into the database and running every time your form loads.
You can instead use AJAX to reset the value as you launch your onLoad code so that it doesn't trigger on every form load
Assign the record guid manually, use AJAX to save your record, pop your new window using th enew guid and then reload your original form (so that the form is no longer in an "unsaved" state).
At the risk of being proven wrong as I cannot verify this right away... you will need to save and then reload the page.
The value stored in Xrm.Page.data.entity.getId() is set when the page is loaded/initialised and hence won't be updated when you access it after you have called Save().
It is also why it does work when you reload the page.
Perhaps you could call save and then reload the window adding a querystring variable of your own, to indicate that this event has just occurred?
e.g.
function DoSomething() {
//do your stuff
Xrm.Page.data.entity.save();
//something like - sure someone can do better!
window.location = window.location.href + '&foo=bar';
}
and then register something like this onFormLoad
function OnLoad() {
var queryStringParms = Xrm.Page.context.getQueryStringParameters();
//test to see if your query string param exists here
for (var i in queryStringParams) {
//if you find query string, do extra processing here
}
}

Resources