REST Service Create User C# Example [Moodle 2.3.1]

Re: REST Service Enrol User C# Example [Moodle 2.3.1]

by Nhan Nguyen -
Number of replies: 0

Hey guys,


Giving back to the community since Daryl's initial piece of code helped me to get further.

The attach shows how to enroll a user into a course.  Note that you will be get a NULL response when it is successful versus an error response.  Not very intuitive, but hey.



using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;

using System.Runtime.Serialization.Json;

using System.Web.Script.Serialization;

using System.Web;


namespace MoodleTest

{

    class Program

    {

        static void Main(string[] args)

        {

            String token = "token goes here";


            MoodleUser user = new MoodleUser();

            user.username = HttpUtility.UrlEncode("nhan1@blah.com");

            user.password = HttpUtility.UrlEncode("blah!");

            user.firstname = HttpUtility.UrlEncode("Nhan1");

            user.lastname = HttpUtility.UrlEncode("Nguyen1");

            user.email = HttpUtility.UrlEncode("nhan1@blah.com");


            MoodleEnrollment enrollment = new MoodleEnrollment()

            {

                roleId = 5, // student role id 

                courseId = 12, // course id

                userId = 2453 // username

            };


            //List<MoodleUser> userList = new List<MoodleUser>();

            //userList.Add(user);


            //List<MoodleEnrollment> enrolList = new List<MoodleEnrollment>();

            //enrolList.Add(enrollment);


            //Array arrEnrollments = enrolList.ToArray();

            //Array arrUsers = userList.ToArray();


            String userData = String.Format("users[0][username]={0}&users[0][password]={1}&users[0][firstname]={2}&users[0][lastname]={3}&users[0][email]={4}", user.username, user.password, user.firstname, user.lastname, user.email);


            String enrolData = String.Format("enrolments[0][roleid]={0}&enrolments[0][userid]={1}&enrolments[0][courseid]={2}", enrollment.roleId, enrollment.userId, enrollment.courseId);


            //string createRequest = string.Format("[baseaddress]/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsrestformat=json", token, "core_user_create_users");

            string createRequest =   string.Format("[baseaddress]/webservice/rest/server.php?wstoken={0}&wsfunction={1}&moodlewsrestformat=json", token, "enrol_manual_enrol_users");


            // Call Moodle REST Service

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(createRequest);

            req.Method = "POST";

            req.ContentType = "application/x-www-form-urlencoded";


            // Encode the parameters as form data:

            byte[] formData =

                UTF8Encoding.UTF8.GetBytes(enrolData);  //or use "userData"

            req.ContentLength = formData.Length;


            // Write out the form Data to the request:

            using (Stream post = req.GetRequestStream())

            {

                post.Write(formData, 0, (int)req.ContentLength);

            }



            // Get the Response

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream resStream = resp.GetResponseStream();

            StreamReader reader = new StreamReader(resStream);

            string contents = reader.ReadToEnd();



            // Deserialize

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            if (contents.Contains("exception"))

            {

                // Error

                MoodleException moodleError = serializer.Deserialize<MoodleException>(contents);

            }

            else

            {

                // Good

                List<MoodleCreateUserResponse> newUsers = serializer.Deserialize<List<MoodleCreateUserResponse>>(contents);

            }


        }


        public class MoodleUser

        {

            public string username { get; set; }

            public string password { get; set; }

            public string firstname { get; set; }

            public string lastname { get; set; }

            public string email { get; set; }

        }


        public class MoodleEnrollment

        {

            public int roleId { get; set; }

            public int userId { get; set; }

            public int courseId { get; set; }

        }

        public class MoodleException

        {

            public string exception { get; set; }

            public string errorcode { get; set; }

            public string message { get; set; }

            public string debuginfo { get; set; }

        }


        public class MoodleCreateUserResponse

        {

            public string id { get; set; }

            public string username { get; set; }

        }

    }

}


Average of ratings: Useful (1)