Create user programmatically

Hi,

I'm looking to programatically create a user in the Syncfusion Dashboard database. Is there an API to allow me to do that?

Context : I want to automate account creation using an external application as the source, using the fields ; Username,Email,Fullname,Password(Needed only for Automatic account activation mode). One idea : Is there a way for me to programmatically call the method that is behind the *.CSV import routine, on the Syncfusion Dashboard Server User Import button ? 

Any tips would be greatly appreciated.

Best,

Noël Joinson

7 Replies

BM Bowthra Mani Syncfusion Team December 7, 2017 01:13 PM UTC

Hi Noel, 
 
We have exposed Web APIs in the Syncfusion Dashboard Server to handle this. The below APIs will be helpful for your scenario. 
 
API 
Details 
Creates a new user with the provided below details 
First Name 
Last Name 
Email 
Username 
Creates a new user with the provided below details 
First Name 
Last Name 
Email 
Username 
Password 
Import the bulk users with the provided details 
CsvFileContent – Byte content of the csv file. 
 
For more details on the available APIs follow the below links. 
Version 
Released with Dashboard Server version 
 
Follow the below instructions to consume the above APIs. 
1.      Authenticate the request 
2.      Create a new user 
3.      Create bulk users from a csv file 
 
API detail and its endpoint 
Code Snippet 
Authentication – We have used the token based authentication to restrict the anonymous user access, please check the below code snippet to get access from Syncfusion Dashboard Server. 
public static Token GenerateToken() 
        { 
            var syncfusionDashboardServerUrl = "http://localhost:8090"; // Refers to the URL in  which syncfusion dashboard server hosted. 
            var userName = "admin"; //Refers to the admin userName 
            var password = "Admin@123"; // Refers to the admin credentials 
            string tokenurl = "/api/token"; 
            using (var client = new HttpClient()) 
            { 
                client.BaseAddress = new Uri(syncfusionDashboardServerUrl); 
                client.DefaultRequestHeaders.Accept.Clear(); 
 
                var content = new FormUrlEncodedContent(new[] 
                { 
                    new KeyValuePair<string, string>("grant_type", "password"), 
                    new KeyValuePair<string, string>("username", userName), 
                    new KeyValuePair<string, string>("password", password) 
                }); 
                var result = client.PostAsync(tokenurl, content).Result; 
                string resultContent = result.Content.ReadAsStringAsync().Result; 
 
                return JsonConvert.DeserializeObject<Token>(resultContent); 
            } 
        } 
Create a new user – It creates a new single user into the Dashboard with the provided details. 
 
Generated token has to be used in the highlighted area in the code snippet. 
 
Note: You can add the additional property ‘Password’ in the below endpoint to add the user with password into the Dashboard server. 
 
EndPoint: syncfusionDashboardServerUrl + "/api/v2.0/users" 
public static ApiResponse AddUser() 
        { 
            var syncfusionDashboardServerUrl = "http://localhost:8090"; 
            var token = GenerateToken();// Refer the above Generate Token API 
            var request = new ApiUserAdd 
            { 
                Username = "test", 
                Email = "[email protected]", 
                FirstName = "test", 
                Lastname = string.Empty 
            }; 
            using (var proxy = new CustomWebClient()) 
            { 
                var ser = new DataContractJsonSerializer(typeof(ApiUserAdd)); 
                var mem = new MemoryStream(); 
                ser.WriteObject(mem, request); 
                proxy.Headers["Content-type"] = "application/json"; 
                proxy.Headers["Authorization"] = token.token_type + " " + token.access_token; 
                proxy.Encoding = Encoding.UTF8; 
                try 
                { 
                    var data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length); 
                    var rdata = proxy.UploadString(new Uri(syncfusionDashboardServerUrl + "/api/v1.0/users"), "POST", data); 
                    var result = JsonConvert.DeserializeObject<ApiResponse>(rdata); 
 
                    return result; 
                } 
                catch (WebException ex) 
                { 
                    if (ex.Response is HttpWebResponse) 
                    { 
                        var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); 
                        dynamic obj = JsonConvert.DeserializeObject(resp); 
                        Console.WriteLine(obj); 
                    } 
                } 
                return null; 
            } 
        } 
 
Import bulk users using csv file – It imports the bulk of users from the csv file. 
public static ApiCsvUserImportResponse CsvUserImport() 
        { 
            var syncfusionDashboardServerUrl = "http://localhost:8090"; // Refers to the URL in  which syncfusion dashboard server hosted. 
            var token = GenerateToken();// Refer the above Generate Token API 
            if (!File.Exists("C:/Users/bowthra.mani/Desktop/Template.csv")) // Provide the CSV template file location. 
            { 
                return new ApiCsvUserImportResponse(); 
            } 
 
            var request = new ApiCsvUserImportRequest 
            { 
                CsvFileContent = File.ReadAllBytes("C:/Users/bowthra.mani/Desktop/Template.csv") // send the csv template file as in byte content. 
           }; 
 
            using (var proxy = new CustomWebClient()) 
            { 
                var ser = new DataContractJsonSerializer(typeof(ApiCsvUserImportRequest)); 
                var mem = new MemoryStream(); 
                ser.WriteObject(mem, request); 
                proxy.Headers["Content-type"] = "application/json"; 
                proxy.Headers["Authorization"] = token.token_type + " " + token.access_token; // assign token to "Authorization" header for validate the token and establish the api connection 
                proxy.Encoding = Encoding.UTF8; 
                var data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length); 
                try 
                { 
                    var rdata = proxy.UploadString(new Uri(syncfusionDashboardServerUrl+ "/api/v2.0/csv-users"), "POST", data); 
                    var result = JsonConvert.DeserializeObject<ApiCsvUserImportResponse>(rdata); 
                    if (result.CsvErrorContent != null)  // we get the csv file (with errors) in "CsvErrorContent" property. If any of the users having error in the csv files. 
                    { 
                        File.Delete("C:/Users/bowthra.mani/Desktop/Error.csv"); 
                        File.WriteAllBytes("C:/Users/bowthra.mani/Desktop/Error.csv", result.CsvErrorContent); 
                    } 
 
                    return result; // Provides the response of the API. 
                } 
                catch (WebException ex) 
                { 
                    if (ex.Response is HttpWebResponse) 
                    { 
                        var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); 
 
                        dynamic obj = JsonConvert.DeserializeObject(resp); 
                        Console.WriteLine(obj);//can get the error details from the server. 
                    } 
                } 
 
                return null; 
            } 
        } 
  
Regards, 
M. Bowthra


NJ Noel J December 7, 2017 01:40 PM UTC

Many thanks.

I will look at these immediately :-)


BM Bowthra Mani Syncfusion Team December 8, 2017 02:59 PM UTC

Hi Noel, 
 
Thanks for your response. 
 
We will wait to hear from you. 
 
Regards, 
M. Bowthra


NJ Noel J December 8, 2017 03:10 PM UTC

Hi,

I still would still really appreciate samples in C# for :
i) creating users
ii)  authenticating users

Many thanks,

Noël JOINSON


BM Bowthra Mani Syncfusion Team December 11, 2017 12:44 PM UTC

Hi Noel, 
 
Thanks for your patience. 
 
As per the incident, we have provided the samples in appropriate languages 
 
                          QUERIES 
                                                                           RESPONSES 
Authenticate with Dashboard Server from within an external app. written in ExtJS (JavaScript)  
Please find the code snippet to generate token and to create new user with password using ExtJs (Java script framework). 
 
<html> 
<head> 
<script type = "text/javascript"   src= "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> 
<script> 
Ext.onReady(function(){ 
var syncfusionDashboardServerURL = "http://172.16.203.238:8090"; // Please provide the Syncfusion dashboard server hosted URL 
var tokenDetails = ""; 
Ext.Ajax.useDefaultXhrHeader = false; 
var apiRequest = new Object();//provide the admin credentials to authenticate the user 
                 apiRequest.password = "Admin@123"; 
                 apiRequest.userid = "admin" ; 
          Ext.Ajax.request({ 
            method: "POST", 
            url: syncfusionDashboardServerURL + "/api/get-user-key",  
            params: apiRequest, 
            success: function (response) { 
                var result = Ext.util.JSON.decode(response.responseText); 
                tokenDetails = JSON.parse(result.Token); 
                createUser(tokenDetails["access_token"]); // Calling a createUser() function to add new users. 
                }             
         }); 
 
//To add new user to Syncfusion Dashboard Server 
function createUser(token){ 
var userDetails = new Object();//provide the user details to add new user 
userDetails.UserName = "test";//provide the user username 
userDetails.FirstName = "test";//provide the user firstname 
userDetails.Password ="Test@123";//provide the user password 
userDetails.LastName = "";//optional 
userDetails.Email = "[email protected]";//provide the user email-id 
Ext.Ajax.request({ 
            method: "POST", 
            headers : { 'Authorization': 'Bearer ' + token }, 
            url: syncfusionDashboardServerURL + "/api/v2.0/users",  
            params: userDetails, 
            success: function (response) { 
                var result = Ext.util.JSON.decode(response.responseText); 
                Ext.MessageBox.alert("status",result.StatusMessage); 
                }, 
            failure: function(response){ 
                var result = Ext.util.JSON.decode(response.responseText); 
                Ext.MessageBox.alert("status",result.Message); 
                } 
              }); 
} 
 
}); 
 
</script> 
</head> 
</html> 
 
Please provide the appropriate input for the highlighted items in the above source code. 
 
Programmatically create a new user/password from within a C# WebService ? 
  1. Please download the zip file  from the below link and extract it.
  2. http://www.syncfusion.com/downloads/support/directtrac/194190/ze/ApiSample-1451476101
  3. Extract the zip file which you have downloaded.
  4. Open the solution “DashboardDesignerSample.sln” file in Visual studio.
  5. Provide the Syncfusion Dashboard Server URL and its credentials to authenticate the user.
  6. Provide the user details which you want to add into the Syncfusion dashboard server and run the solution file.
 
 
Regards, 
M. Bowthra 



NJ Noel J December 11, 2017 05:00 PM UTC

Thank-you very much

I was able to integrate the C# and ExtJs code without any problems at all.

Best regards,

Noël JOINSON


AB Arasuraja Balakrishnan Syncfusion Team December 12, 2017 01:42 PM UTC

Hi Noel, 
 
Thanks for the response. We are happy to hear this from you 
 
Please let us know if you need further assistance on this. 
 
Thanks, 
Arasuraja B. 


Loader.
Up arrow icon