Dialogs OData Set name? - dynamics-crm-2011

Ok in crm 2011 using Odata Query - if a workflows Odata Set name is AsyncOperationSet What is the equivalent for a dialog?
I have tried to figure this out with no luck
Please help
Thank you
P.s I need to get the dialogs id from its name

When searching for a dialog to launch via javascript:
Category = 1 (Dialog)
Type = 1 (Definition) - This is important if trying to call a dialog from javascript!
Solution:
triggerDialog = function (name, entityName, recordId) {
var dialogId = "";
var request = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet?$select=Name,WorkflowId&$filter=Type/Value eq 1 and Category/Value eq 1 and Name eq '"+name+"'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
dialogId = data.d.results[0].WorkflowId;
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
/*Error Occurred*/
}
});
var serverUrl = Xrm.Page.context.getServerUrl();
window.showModalDialog(
serverUrl + "/cs/dialog/rundialog.aspx?DialogId=" + encodeURIComponent(dialogId) + "&EntityName=" + encodeURIComponent(entityName) + "&ObjectId=" + encodeURIComponent(recordId), null, "dialogHeight:600px;dialogWidth:800px;center:yes; resizable:1;maximize:1;minimize:1;status:no;scroll:no");
Hope this helps

Just for your information. AsyncOperation is not instances of workflows only. It could be anything that is executed asynchronously (async plugins, calculating of matchcodes for dupdetection rules and many other).
Not sure what exactly do you want to get from Odata. What exactly do you need to get? If you need an instance of dialog - you will need to use AsyncOperation as well.

Related

How to pass date variable in uri for Microsoft graph request?

I'm trying to get back a list of calendar events with Microsoft Graph API but having problems with passing date variable in the query parameters.
If I hardcode the uri value to:
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `'2018-12-10T19:30:34.654Z'`,
then the request works. But if I try to pass the date variable with toISOString, I get an error. I've tried with or without backticks, and calling toISOString in the uri value and in the nextMonday function. Still doesn't work. Anyone have any ideas? Thanks!
function nextMonday(date){
var monday = new Date(date);
monday.setDate(monday.getDate() + (1 + 7 - monday.getDay()) % 7);
return monday.toISOString();
}
let date = new Date();
let m = nextMonday(date);
const options = {
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `m`,
auth: {
bearer: token,
},
headers: {
'content-type': 'application/json'
},
json: true // Automatically parses the JSON string in the response
};
You need to (1) use ${m} to add the value and (2) wrap it in single quotes.
uri: https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge '${m}',

Creating a cascading dropdown in sharepoint

How do I go about creating a cascading drop-down within a list in Office 365 SharePoint?
For instance, if you have a country drop-down and you select United States, you get the 50 states listed. Then if you select Maryland, you get the cities within that state.
You can use Info Path form which make very easy for cascading and if you do not want to use Infopath you have to use Jquery CSOM or REST API in the form where you want to use cascading.
Please go through below link for more information :
http://www.markrackley.net/2014/05/20/cascading-drop-down-lists-in-sharepoint-office-365-using-rest/
https://spservices.codeplex.com/wikipage?title=%24%28%29.SPServices.SPCascadeDropdowns
You can use REST API to implement Cascading Drop down in SharePoint. Step by step article link: Cascading drop down in SharePoint using REST API
//Function to filter the values of Drink Types
function loadDrinkTypes(selectedDrink) {
var drinkTypeListName = "Drink Type";
var drinkTypeListURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + drinkTypeListName + "')/items?$select=Title,Drink/Title,Drink/Id&$expand=Drink&$filter=Drink/Title eq '" + selectedDrink + "'";
getReqData(drinkTypeListURL, function (data) {
var items = data.d.results;
if (items.length > 0) {
var optionsAsString = '<option value=""></option>';
for (var i = 0; i < items.length; i++) {
optionsAsString += "<option value='" + items[i].Title + "'>" + items[i].Title + "</option>";
}
$('select[title="Drink Type"]').html(optionsAsString);
}
},
function (data) {
//alert("Some error occurred in getting Drink Types");
});
}
//JQuery AJAX to access REST API JSON data
function getReqData(reqUrl, success, failure) {
$.ajax({
url: reqUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}

EndlessScroll using KendoUI Mobile + Azure Mobile Services + SQL Azure

I have been struggling for the past few days with Endless Scrolling on a mobile listview. I have set up my datasource and listview as the demo suggests. I have not been able to successfully get it to work (or 'press to load more' for that matter) on server-side data. The local data works as expected. I have used many different KendoUI core builds and the results are pretty much the same.
One difference I did notice though, is the type: "odata" part in the demo that refuses to work for me (500 Internal Server Error). I therefore tried a normal "GET" type on the datasource. The "GET" was odata-style (https://myserviceapi.azure-mobile.net/tables/EventTypes?$filter=businessID%20eq%2053) which is supported out of the box on Azure Tables, but endless scrolling did not work. I also tried a normal "GET" of an Azure Mobile Services api method that is basically a RESTful method that returns the same data as the odata table query in SQL Azure. None of the things I have tried work. The following code is what I have and tested with many Kendo UI Core builds.
App JavaScript:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: 'https://myserviceapi.azure-mobile.net/tables/EventTypes?$filter=businessID%20eq%20' + busID,
dataType: "json"
}
},
serverPaging: true,
pageSize: 12
});
$("#photoHolder").kendoMobileListView({
dataSource: dataSource,
template: "<p>#: eventName #</p>",
endlessScrolling: true,
filterable:{
field: "eventName",
operator: "contains",
ignoreCase: true,
placeholder: "search products..."
}
});
HTML:
<ul id="photoHolder" data-role="listview">
</ul>
Azure JavaScript:
exports.get = function(request, response) {
var mssql = request.service.mssql;
var cnt = request.query.pageSize;
var pnm = request.query.page;
var sql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY zOrder) AS RowNum, * FROM myschema.EventTypes where (businessID = " + request.query.busID + ") and active = 1) AS E " +
"WHERE RowNum BETWEEN ((" + pnm + " - 1) * cnt + 1) AND (" + pnm + " * " + cnt + ") ORDER BY zOrder";
mssql.query(sql, {
success: function(results) {
response.send(200, results);
},
error: function(err) {
console.log(err);
response.send(530, { error: err });
}
});
};
I found the answer to this when I was playing around on my own "pet" app. I just had to make sure that there were enough items in the list to actually give that endless scroll experience. In the Kendo UI forums, they suggest a pageSize of at least 30. {http://docs.telerik.com/kendo-ui/mobile/listview/endless-scrolling}

SharePoint Hosted App - Creating cascaded drop down on hosted web lists

I have created a SharePoint Hosted App(Javascript Object Model) that creates lists on the host web.
I need to put some javascript into new and edit forms in order to create the cascaded drop down effect on 2 lookup fields.
Here is how I create the lists and the fields for it:
// Create a new list on host web
var createList = function (listTitle, onSuccess, onFieldsReady) {
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(listTitle);
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
var lists = hostWeb.get_lists();
var newList = lists.add(listCreationInfo);
currentContext.load(newList);
currentContext.executeQueryAsync(onSuccess(newList, onFieldsReady), onListCreationFail);
}
// Create a new field on a list
var createField = function (list, fieldType, fieldName, fieldDisplayName, fieldRequired, onSuccess) {
var fields = list.get_fields();
var fieldXml = "<Field Type='" + fieldType + "' Required='" + fieldRequired + "' DisplayName='" + fieldDisplayName + "' Name='" + fieldName + "'></Field>";
var createdField = fields.addFieldAsXml(fieldXml, true, SP.AddFieldOptions.addFieldInternalNameHint | SP.AddFieldOptions.addFieldToDefaultView);
currentContext.load(createdField);
currentContext.executeQueryAsync(onSuccess, onProvisionFieldFail);
}
Can you please give me some advise?
Regards,
Marian
You should consider ditching the idea of using NewForm and Editform.aspx. Just write your own form and use the JSOM or WebApi to add/edit list items.
Sample code for adding item to a list:
jQuery.ajax({
url: "http://<site url>/_api/web/lists/GetByTitle('Test')",
type: "POST",
data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }),
headers: {
"X-HTTP-Method":"MERGE",
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"content-length": <length of post body>,
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: doSuccess,
error: doError
});
Reference: http://msdn.microsoft.com/en-us/library/office/jj164022(v=office.15).aspx
Try this.
var clientContext = new SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('ListName');
if(list) {
var fldCollection = list.get_fields();
var fieldLookup1 = clientContext.castTo(
fldCollection.addFieldAsXml('<Field Name="FieldName1" Type="Lookup" DisplayName="My Lookup Field 1" List="Lists/MyLookupList" ShowField="Title" />', true, SP.AddFieldOptions.addToDefaultContentType),
SP.FieldLookup
);
fieldLookup1.set_title("MyLookupField1");
fieldLookup1.set_description("Lookup field 1 description");
fieldLookup1.update();
list.update();
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
Please let me know if it works ;)
Have a nice day!

CRM 2011 - setting a default value with JScript

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:
function SetDefaultCountryCode(countryFieldId) {
var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
On the form OnLoad I invoke the function like that:
// set Country fields to Canada if not set
SetDefaultCountryCode('cga_address1country');
We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.
I have two questions here:
Is it possible to export / import entity data preserving the GUIDs ?
If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?
Thank you in advance for any help / feedback.
It's very bad practice to hard code your GUIDs and you discovered the problems of it.
As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.
In order to retireve information from client-side (or Entity Form):
We will use/consume REST Endpoint (testing in browser).
Upload jQuery lib.
Upload Json2 lib.
Use the AJAX function from the jQuery library.
Define your entity, columns and criteria.
Lets, look for querying REST Endpoint.
http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'
Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.
After seeing your your results, we are going to call this URL using an AJAX call.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
// now we have the GUID of Canada, now I can continue my process
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
But before you copy the code to your form, you have to download the jQuery lib from here
Then upload it as a Web resource, add this web resource to the Form load libs.
Here is the complete code to be put in the form load event handler:
var context = GetGlobalContext();
// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;
//Retrieve the server url, which differs on-premise from on-line and
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT;
function SetDefaultCountryCode(countryFieldId, odataUri) {
odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
}
One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.
EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.
For more information about the REST Endpoint.
It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.
The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

Resources