programatically register an item to the portal

2510
9
Jump to solution
08-26-2016 01:31 PM
Highlighted
Occasional Contributor II

Hi All,is it possible to register an item to the portal programatically? I researched both the Javascript portal API and portalpy, and they don't seem to provide ways to do that. Are there any ways to programtically add an item to the portal?

Thanks!

Reply
0 Kudos
1 Solution

Accepted Solutions
Highlighted
New Contributor II

Yes it is possible. Do you want to add an item and then register it? I have implemented this in C# but the basic flow would be the same using the javascript API.

To add an item

Add an item 

To register an item

Register an Item 

Hope that helps

View solution in original post

9 Replies
Highlighted
New Contributor II

Yes it is possible. Do you want to add an item and then register it? I have implemented this in C# but the basic flow would be the same using the javascript API.

To add an item

Add an item 

To register an item

Register an Item 

Hope that helps

View solution in original post

Highlighted
Occasional Contributor II

Thank Grant for your replies! I want to add items (.json files and images) to the portal so they can be searchable and shared with others in portal. For this purpose, do I have to register them?

Reply
0 Kudos
Highlighted
New Contributor II

Hi Alex

No, you don't need to register them, you only need to push them in to the portal\or AGOL. You can also programmatically share new items with groups, as by default they will be private. The functions for that are here. The only time you would really need to register an item would be if it were an application and you were wanting to user AGOL\Portal for authentication, in which case you would to ensure that you had the correct urls for the OAuth redirects.

Cheers

Highlighted
Occasional Contributor II

Thanks Grant. Very useful info. One last question, I have looked at the sample usage from the link you sent, but not sure how to call the addItem via rest? Do I need construct an object for that?

http://www.arcgis.com/sharing/rest/content/users/jsmith/addItem URL=http://www.mymappingapplication.com title=My Mapping Application type=Web Mapping Application tags=web, mapping, application
Reply
0 Kudos
Highlighted
New Contributor II

Hi Alex.

You need to do a post request in order to get this to work. Below is an example of this in javascript (not really a python guy sorry), i've tested this and it worked ok for me. The only thing is that you will probably need a token to add an item. I have added the code for that further down for the sake of completeness.

//You may need to append a token to the request in order to add it in, see the code further down
var url = "http://www.arcgis.com/sharing/rest/content/users/grantcarroll_isovist/addItem/"+'?token=' + token;
   esriRequest(
   {
      url: url,

//edit the below to add in any properties to the item that you are adding. The properties are those listed in the addItem help link in the original reply
      content: {
         f: "json",
         URL: "http://www.mymappingapplication.com",
         title: "My Mapping Application",
          type: "Web Mapping Application",
          tags: "web, mapping, application"
     },
    handleAs: "json",
   },
   {
      usePost: true,
      //set this if you are using a proxy
      useProxy: false
   }

).then(lang.hitch(this, function (response) {
   //The response.id is the id of your item in AGOL
   console.log("success", response.id)
}), lang.hitch(this, function (error) {
   console.log("Error", error);
}));

Generate a token

 var token = ""
//need to ensure you use https to encrypt the request
var url = "https://www.arcgis.com/sharing/rest/generateToken"
esriRequest(
   {
      url: url,
      content: {
         f: "json",
         username: "<username>",
         password: "<password>",
         client: "referer",
         referer: "<the url you are calling from>"
      },
      handleAs: "json",
   },
   {
      usePost: true,
      //set this if you are using a proxy
      useProxy: false
   }

).then(lang.hitch(this, function (response) {
   //The response.token is your token
   token = response.token;
    //You can use the token in subsequent request against secured items

   console.log("success", response.token)
  }), lang.hitch(this, function (error) {
   console.log("Error", error);
}));

Hope all that helps.

Cheers

Reply
0 Kudos
Highlighted
Occasional Contributor II

Wonderful! Thanks, Grant.

Reply
0 Kudos
Highlighted
New Contributor II

Thanks, Grant! Is it possible to share your C# version of adding/registering items? I am sucked with one problem in my codes....

Reply
0 Kudos
Highlighted
New Contributor II

Hi see the code below, this should have everything you need, or at least get you moving in the right direction.

Cheers

[HttpPost]
[ActionName("PostInstall")]
public HttpResponseMessage PostInstall(PostInstall installDetails)
{

var token = GetUserToken(installDetails.username, installDetails.password, installDetails.portalUrl);
var errors = new List<string>();

//Get the details of the current user. Only admins should be allowed to perform the post install.
var url = "http://www.arcgis.com/sharing/rest/community/self" + "?f=pjson&token=" + token;
var portalUser = JsonConvert.DeserializeObject<Model.WebAppBuilder.Self>(AGOLHelper.DoGetRequest(url));

if (portalUser.role != "org_admin")
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(@"Only ArcGIS Portal\Online administrators can perform the post install task") };
}
UpdateSettingValue("Viewer File Location", installDetails.viewerFilePath);
//Create the user content url
var userContentUrl = GetSecurePortal(installDetails.portalUrl) + "/sharing/rest/content/users/" + installDetails.username;

//Create Item and add to AGOL\Portal

var itemDetails = new NameValueCollection();
var itemUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.LocalPath, "") + @"/" + this.GetApiRoot();
itemDetails["url"] = itemUrl;
itemDetails["token"] = token;
itemDetails["f"] = "pjson";
itemDetails["title"] = "LocalMaps";
itemDetails["type"] = "Web Mapping Application";
itemDetails["description"] = "LocalMaps Web Mapping Application. A colloborative application built by Eagle Technology, Isovist Ltd and GBS";
itemDetails["tags"] = "LocalMaps";
itemDetails["snippet"] = "LocalMaps";

var addItemUrl = userContentUrl + "/addItem";
var addItemResult = JsonConvert.DeserializeObject<AddItemResponse>(AGOLHelper.DoPostRequest(addItemUrl, itemDetails));

if (!addItemResult.success)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(@"Unable to add LocalMaps to AGOL\Portal") };
}


//Share Item
var shareDetails = new NameValueCollection();
shareDetails["token"] = token;
shareDetails["f"] = "pjson";
shareDetails["everyone"] = "true";
shareDetails["items"] = addItemResult.id;

var shareItemUrl = userContentUrl + "/shareItems";
var shareItemResult = JsonConvert.DeserializeObject<ShareItemResult>(AGOLHelper.DoPostRequest(shareItemUrl, shareDetails));

var shareLocalMapsResult = shareItemResult.results.Where(o => o.itemId == addItemResult.id).FirstOrDefault();
if (shareLocalMapsResult == null)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(@"Sharing LocalMaps Failed") };
}

if (!shareLocalMapsResult.success)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(@"Sharing LocalMaps Failed") };
}

//Register App
var uris = new List<string>() { itemUrl };
var registerAppUrl = <portalUrl> + "/sharing/rest/oauth2/registerApp"; //this needs to be https
var registerAppDetails = new NameValueCollection();
registerAppDetails["token"] = token;
registerAppDetails["f"] = "pjson";
registerAppDetails["itemId"] = addItemResult.id;
registerAppDetails["appType"] = "browser";
registerAppDetails["redirect_uris"] = JsonConvert.SerializeObject(uris);


var registerAppResult = JsonConvert.DeserializeObject<RegisterAppResult>(AGOLHelper.DoPostRequest(registerAppUrl, registerAppDetails));
//registerAppResult will have the details you need about client_id etc

return new HttpResponseMessage(HttpStatusCode.OK);
}

public static class AGOLHelper
{


public static string DoGetRequest(string url)
{
//make the request to the server

HttpWebResponse httpResponse = HttpWebGetRequest(url, "");

//check for errors
if (httpResponse == null)
return null;

//get the JSON representation from the response
return DeserializeResponse(httpResponse.GetResponseStream());
}

public static string DoPostRequest(string url,NameValueCollection data)
{

string responseData;
var webClient = new WebClient();
var response = webClient.UploadValues(url, data);
responseData = System.Text.Encoding.UTF8.GetString(response);
return responseData;
}


public static HttpWebResponse HttpWebGetRequest(string url, string referer)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
if (referer != string.Empty)
httpWebRequest.Referer = referer;
try
{
return (HttpWebResponse)httpWebRequest.GetResponse();
}
catch(Exception ex) {
return null;
}
}

public static string DeserializeResponse(System.IO.Stream stream)
{
string JSON = string.Empty;

using (StreamReader reader = new StreamReader(stream))
JSON = reader.ReadToEnd();

return JSON;
}

private static byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}

}


public class RegisterAppResult
{
public string itemId { get; set; }

public string client_id { get; set; }

public string client_secret { get; set; }

public string appType { get; set; }

public List<string> redirect_uris { get; set; }

public string registered { get; set; }

public string modified { get; set; }

}

public class ShareItemResult
{
public List<ShareResult> results { get; set; }

}

public class ShareResult
{
public string itemId { get; set; }

public bool success { get; set; }

public string[] notSharedWith { get; set; }

public AgolError error { get; set; }

}

public class AgolError
{
public int code { get; set; }

public string message { get; set; }

}

public class AddItemResponse
{
public bool success { get; set; }
public string id { get; set; }
public string folder { get; set; }

}

Reply
0 Kudos
Highlighted
New Contributor II

Thanks so much! It is really helpful!

Reply
0 Kudos