Moodle get course information + all lessons through Api - moodle

I am trying to collect all information related to Moodle course (course + lessons) Using Moodle Api I got the course information, but gets only some basic information, I want course details and its lessons (created under course)
Eg : var domainname = 'http://<server URL>/moodle';
var token = 'df337369637c692303d903f8cacf1eb0';
var functionname = 'core_course_get_courses';
var serverurl = domainname + '/webservice/rest/server.php' ;
var data = {
wstoken: token,
wsfunction: functionname,
moodlewsrestformat: 'json'
} var response = $.ajax(
{ type: 'GET',
data: data,
url: serverurl
}
);
And the output looks like
{"id":2,"shortname":"IV Support Queries","categoryid":1,"categorysortorder":10001,"fullname":"IV Support Queries","displayname":"IV Support Queries","idnumber":"","summary":"<p>IV Support Queries Desc<br \/><\/p>","summaryformat":1,"format":"topics","showgrades":1,"newsitems":5,"startdate":1479168000,"numsections":5,"maxbytes":0,"showreports":0,"visible":1,"hiddensections":1,"groupmode":0,"groupmodeforce":0,"defaultgroupingid":0,"timecreated":1479127227,"timemodified":1479198758,"enablecompletion":0,"completionnotify":0,"lang":"","forcetheme":"","courseformatoptions":[{"name":"numsections","value":5},{"name":"hiddensections","value":1},{"name":"coursedisplay","value":1}]}
I want the lesson details created under course .How can i get the information through Api . Thanks

Using function
"core_course_get_contents"
getting all the informations related with course.
var domainname = 'http://<server URL>/moodle';
var token = 'df337369637c692303d903f8cacf1eb0';
var functionname = 'core_course_get_contents';
var serverurl = domainname + '/webservice/rest/server.php' ;
var data = {
wstoken: token,
wsfunction: functionname,
moodlewsrestformat: 'json' ,
courseid: 2 //Retrieve results based on course Id 2
}
var response = $.ajax(
{ type: 'GET',
data: data,
url: serverurl
}
);
Thanks

Related

how to post attachments using Upload Collection - pending

I am trying to use the same code wrt official upload collection pending
and in controller where upload is called :
onStartUpload: function(oEvent) {
var oUploadCollection = this.byId("UploadCollection");
var cFiles = oUploadCollection.getItems().length;
var uploadInfo = cFiles + " file(s)";
if (cFiles > 0) {
oUploadCollection.upload();
MessageBox.information("Uploaded " + uploadInfo);
}
},
I have set all required header parameters in onChange as:
onChange: function(oEvent) {
var oUploadCollection = oEvent.getSource();
// Header Token
var oCustomerHeaderEmailToken = new UploadCollectionParameter({
name: "xxxx",
value: xxxxx
});
// Header Token
var oCustomerHeaderAuthToken = new UploadCollectionParameter({
name: "xxxx",
value: "xxxx"
});
oUploadCollection.addHeaderParameter(oCustomerHeaderEmailToken);
oUploadCollection.addHeaderParameter(oCustomerHeaderAuthToken);
},
When i tried uploading in BE it gave me error as :
current request is not a multipart request
Then I tried adding to onChange :
var oCustomerHeaderContentType = new UploadCollectionParameter({
name: "Content-Type",
value: "multipart/form-data; boundary=----WebKitFormBoundarycXEQN6de4OdX0FBe"
});
oUploadCollection.addHeaderParameter(oCustomerHeaderContentType);
It didn't work even though the error is gone ,
The API works fine and tested in postman but why not with upload collection ? May i know the request sent is a multipart form-data ? Do I need to add any extra parameters ?
How does a simple back end API (if JAVA/Python) would be to collect files from when upload collection is used ? as there is no name to refer in server side like fileuploader and if the request is a multipart in upload collection
hope the experts help me out with this ... thanks :)

.net core 2.0 external login - extra profile information

I have a .net core 2.0 app and am implementing external login providers like google, twitter, and facebook. I have the requirement to get the user's display name and profile picture, and can't find any documentaion of how to achieve this in .net core 2.0.
I add the authentication like this post: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/
Here are my twitter login and callback functions...
[HttpGet]
[Route("/api/security/login/type/socialmedia/twitter")]
public IActionResult GetTwitterLogin(string redirect_uri)
{
ClientCallback = redirect_uri;
string redirectUrl = "/api/security/login/type/socialmedia/twittercallback";
var properties = SignInManager.ConfigureExternalAuthenticationProperties("Twitter", redirectUrl);
return Challenge(properties, "Twitter");
}
[HttpGet]
[Route("/api/security/login/type/socialmedia/twittercallback")]
public async Task<HttpResponseMessage> GetTwitterCallBackAsync()
{
var info = await SignInManager.GetExternalLoginInfoAsync();
var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
}
else
{
}
Response.StatusCode = (int)HttpStatusCode.OK;
return null;
}
It looks like you can get some items from info.Principal.Claims, but nothing for the user's display name or profile picture.
How do you get the display name or profile picture for the various login providers?
I finally figured this out...you need to add claims when you configure the authentication. These claims look at the resulting json response and pulls items from it. The pertinent lines are the ClaimActions items.
services.AddAuthentication()
.AddTwitter(twitterOptions =>
{
twitterOptions.ConsumerKey = cfg.SystemConfig["TwitterConsumerKey"];
twitterOptions.ConsumerSecret = cfg.SystemConfig["TwitterConsumerSecret"];
twitterOptions.SaveTokens = true;
twitterOptions.RetrieveUserDetails = true;
twitterOptions.ClaimActions.MapJsonKey("display-name", "name");
twitterOptions.ClaimActions.MapJsonKey("profile-image-url", "profile_image_url_https");
})
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = cfg.SystemConfig["FacebookClientId"];
facebookOptions.AppSecret = cfg.SystemConfig["FacebookClientSecret"];
facebookOptions.SaveTokens = true;
facebookOptions.ClaimActions.MapJsonKey("display-name", "name");
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = cfg.SystemConfig["GoogleClientId"];
googleOptions.ClientSecret = cfg.SystemConfig["GoogleClientSecret"];
googleOptions.SaveTokens = true;
googleOptions.ClaimActions.MapJsonSubKey("profile-image-url", "image", "url");
googleOptions.ClaimActions.MapJsonKey("display-name", "displayName" );
});
After getting the login information in your callback using
var info = await SignInManager.GetExternalLoginInfoAsync();
If populated successfully you can query the claims and find the values
var profileImageClaim = info.Principal.Claims.Where(x => x.Type == "profile-image-url").FirstOrDefault();
Facebook images are different from google and twitter and can be found using...
var claim = info.Principal.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").FirstOrDefault();
var url = "http://graph.facebook.com/" + claim.Value + "/picture";
In ASP.NET Core 2.0, FacebookOptions uses extension methods on ClaimActions to map the profile data returned by UserInformationEndpoint.
ClaimActions.MapJsonKey(ClaimTypes.DateOfBirth, "birthday");
In the mapping above, "birthday" is a top-level property in the Facebook Graph API response that's mapped to the value represented by the claim ClaimTypes.DateOfBirth.
To grab the profile picture you would do the same thing, but since the picture in the Graph API response is a nested JSON object, you would have to use MapCustomJson()
services.AddAuthentication()
.AddFacebook(options =>
{
// ...other options omitted
options.Fields.Add("picture");
options.ClaimActions.MapCustomJson("urn:facebook:picture",
claim => (string)claim.SelectToken("picture.data.url"));
})
Here, claim is a NewtonSoft JObject that uses JPath syntax to select the nested property value and cast it to a string.
The profile picture URL will now appear in your Claims list.

Change filename of existing file on SharePoint Document library using REST API

I have a question on how to change an existing file on SharePoint document library using REST API. I have a couple of files in the location http://site url/<RootFolder>/<SubFolder>/File.docx. I have a UI where it lists all the files from this subfloder location. When the user clicks on edit i am enabling the file name as textbox where the user can change the name of the file.
After doing some research i found that Constructing an endpoint that looks like this: https://<site url>/_api/web/lists/getbytitle('Documents')/items(<item id>) we can edit the file metadata properties. But i could not able to figure out the best way to update the filename of existing document that resides on SharePoint Doc library.
Could someone please help me with the REST API query to fetch the file and the approach to update the filename?
You could consider at least two options:
Option 1. Rename file name
You could update the name of the existing list item as demonstrated below
Example
function rename(webUrl,listTitle,itemId,fileName){
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")";
return executeJson(endpointUrl)
.then(function(data){
var itemPayload = {};
itemPayload['__metadata'] = {'type': data.d['__metadata']['type']};
itemPayload['Title'] = fileName;
itemPayload['FileLeafRef'] = fileName;
var itemUrl = data.d['__metadata']['uri'];
var headers = {};
headers["X-HTTP-Method"] = "MERGE";
headers["If-Match"] = "*";
return executeJson(itemUrl,"POST",headers,itemPayload);
});
}
var webUrl = _spPageContextInfo.webAbsoluteUrl; // web url
var listTitle = "Documents"; //list title
var itemId = 1; //list item id
var fileName = "SP User Guide.docx"; //new file name
rename(webUrl,listTitle,itemId,fileName)
.done(function(item){
console.log('Renamed');
})
.fail(function(error){
console.log(error);
});
Option 2. Move file via MoveTo REST endpoint
Example
function moveTo(webUrl,sourceFileUrl,targetFileUrl){
var endpointUrl = webUrl + "/_api/web/getfilebyserverrelativeurl('" + sourceFileUrl + "')/moveto(newurl='" + targetFileUrl + "',flags=1)";
return executeJson(endpointUrl,"POST");
}
var webUrl = _spPageContextInfo.webAbsoluteUrl; // web url
var sourceFileUrl = "/Documents/SP2010.docx";
var targetFileUrl = "/Documents/SP2013.docx";
moveTo(webUrl,sourceFileUrl,targetFileUrl)
.done(function(item){
console.log('Done');
})
.fail(function(error){
console.log(error);
});
executeJson function:
function executeJson(url,method,headers,payload)
{
headers = headers || {};
method = method || 'GET';
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
You need to use the MoveTo Method to do this as described here in MSDN https://msdn.microsoft.com/en-us/library/office/dn450841.aspx#bk_FileMoveTo.
executor.executeAsync({
url: "<app web url>/_api/SP.AppContextSite(#target)/web
/getfilebyserverrelativeurl('/Shared Documents/filename.docx')
/moveto(newurl='/Other Folder/filename.docx',flags=1)
?#target='<host web url>'",
method: "POST",
success: successHandler,
error: errorHandler
});

Sending POST requests to a nested API endpoint URL using Ember Data

I see several questions on SO attempting to solve this problem of sending POST requests to nested API resource routes.
See:
- [Sending REST requests to a nested API endpoint URL using Ember Data(Sending REST requests to a nested API endpoint URL using Ember Data)
- Custom request URLs in Ember model
I've started overloading the createRecord, updateRecord, and deleteRecord methods on the RESTAdapter to attempt some sort of hackery solution to building the correct URL. Now, using a method similar to this is the route I've taken so far.
Here is the updateRecord method in their solution:
App.UserAdapter = DS.RESTAdapter.extend({
updateRecord: function(store, type, record) {
if(!record.get('parent') || null === record.get('parent')){
return this._super(store, type, record);
}
var data = {};
var serializer = store.serializerFor(type.typeKey);
var parent_type = record.get('parent');
var parent_id = record.get(parent_type).get('id');
var child_parts = Ember.String.decamelize(type.typeKey).split('_');
var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + Ember.String.pluralize(child_parts.pop());
serializer.serializeIntoHash(data, type, record);
var id = record.get('id');
return this.ajax(this.buildURL(path, id), "PUT", { data: data });
}
....
});
This method should work great in tandem with adding the parent type to the model and ensuring the related parent model id is also represented on the model. For PUT and DELETE requests, this shouldn't be a problem, as we already have the parent ID relation on the object in store.
Project model:
App.ProjectModel = DS.Model.extend({
name: DS.attr('string'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date'),
workspace : DS.belongsTo('workspace'),
parent: 'workspace',
....
});
Where this method appears to go awry for me is in creating new resources with a post. I've attempted it, but since the payload hasn't been returned from the API server with the related parent ID, I actually don't have access to it.
Here's my crappy first attempt, that doesn't work. The workspace id always returns null.
createRecord: function(store, type, record) {
if (!record.get('parent') || null === record.get('parent')){
return this._super(store, type, record);
}
var data = {};
var serializer = store.serializerFor(type.typeKey);
var parent_type = record.get('parent');
var parent_id = record.get(parent_type).get('id');
var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this._buildURL(path, null), "POST", { data: data });
},
Got any thoughts on how I can get the parent ID, before I have a saved record?
I am the author of the solution you cited in your question.
What does your model hook look like in the route where you are creating the new ProjectModel?
Assuming your Workspace route looks something like:
App.WorkspaceRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('workspace', params.id);
}
});
Then your Workspace Project add/create route's model hook would need to be something like:
App.WorkspaceProjectAddRoute = Ember.Route.extend({
model: function () {
var workspace = this.modelFor('workspace');
return this.store.createRecord('project', {
workspace: workspace
});
}
}
I hope this makes some sense...

Facebook C# sdk batch request method return empty data array

I am creating Facebook application which get insights for user's page for multiple metric. Ex. for "page_active_users" and "page_active_users in one batch request.
I am using Facebook C# SDK. But not able to get data from Facebook insights (GraphAPI).
I used 5 different way to get the data but not succeed. By using Graph API method in browser shows data for a page but in batch request it returns empty array of data.
//type1
var para1 = new FacebookBatchParameter(HttpMethod.Get, "MyPageId/insights/")
{
Data = new { access_token = aToken, since = "2012-01-01", metric = "page_active_users" }
};
//type2
var para2 = new FacebookBatchParameter(HttpMethod.Get, "fql/", new
{
q = new[]{
"SELECT value,end_time FROM insights WHERE object_id=MyPageId AND metric='page_active_users' AND end_time=end_time_date('2012-01-01') AND period=86400"
}
}) { Data = new { access_token = aToken } };
//type 3
var para3 = new FacebookBatchParameter().Query(
"SELECT value,end_time FROM insights WHERE object_id=MyPageId AND metric='page_active_users' AND end_time=end_time_date('2012-01-01') AND period=86400");
//type 4
var para4 = new FacebookBatchParameter
{
Path = "MyPageId/insights/",
//Parameters = new {since = "2012-01-01"},
Data = new { access_token = aToken, since = "2012-01-01", metric = "page_active_users" },
HttpMethod = HttpMethod.Get
};
//type 5
var para5 = new FacebookBatchParameter
{
Path = "MyPageId/insights/page_active_users?since=2012-01-01",
//Parameters = new {since = "2012-01-01"},
Data = new { access_token = aToken },
HttpMethod = HttpMethod.Get
};
//Executed all above type by passing it to below method one by one.But always return empty data array while data is exists on Facebook which I tested using Grap API tool.
var result = client.Batch(para1-5);
Any help appreciated.
Thanks in advanced.
Dharmendra Mistry
I found solution on my own. Hope this will help someone. Here is the solution.
///I created an enum for list of metrics that facebook is providing
public enum FacebookMatricType
{
page_active_users,
page_active_users_locale
}
//Created a list of Facebook batch request for each metric using LINQ to Object and //concatenate string using string.format method.
var batchParameters = (from FacebookMatricType matricType in Enum.GetValues(typeof (FacebookMatricType))
select new object[]
{
pPageAccessToken,"insights",matricType.ToString(),pFromDate.Date.ToString("yyyy-MM-dd"),pPageId
}
into objectParamter
select new FacebookBatchParameter
{
HttpMethod = HttpMethod.Get,
Path =
string.Format(
"https://graph.facebook.com/{0}/{1}/{2}?since={3}&access_token={4}",
objectParamter)
}).ToList();
//Once I get the list of request I execute it using facebook web client using C# SDK.
var facebookClient = new FacebookClient(pProfileAccessToken);
var results = facebookClient.Batch(batchParameters.ToArray());
//Results are ready to deserialize.
Thank you. ;)
Dharmendra Mistry