+ Start a Discussion
venturec3venturec3 

Metadata API returning the Profile zip file, but not the object Permissions being referenced

I have a C# app that is successfully returning and writing the zip file with the Profiles to a folder, but even thought I am setting the objects I would like to retrieve the permissions for, it is only returning the following:

 

<?xml version="1.0" encoding="UTF-8"?> <Profile xmlns="http://soap.sforce.com/2006/04/metadata">     <userLicense>Salesforce</userLicense> </Profile>

 

I should be seeing custom objects and the profile permissions related to these objects.

 

The reason I need to use the C# app is because in the Force.com IDE, only unmanaged objects can be retrieved, and then viewed in the Profile metadata. In the C# application, all objects, whether managed or unmanaged are returned. I've tested this out using the CustomObject and have returned all custom objects in a zip file.

 

So here is a portion my code. Please let me know if there are any questions. Would like to get this figured out. I'm not that Familiar with Java, but if you have some Java code as an example, that would also be very helpful.

 

       

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Windows.Forms;
using SalesforceMetaDataApplication.WebReference;
using SalesforceMetaDataApplication.SFMetadata;
using SForceOfficeToolkitLib4;


namespace SalesforceMetaDataApplication
{
    public partial class MetaInfo : Form
    {

        public const double API_VERSION = 23.0;

        private SalesforceMetaDataApplication.WebReference.SforceService sf { get; set; }
        private SalesforceMetaDataApplication.WebReference.LoginResult lr { get; set; }
        private GetUserInfoResult userInfo { get; set; }

        private MetadataService metaService { get; set; }
        private List<FileProperties> lstFp { get; set; }
        private RetrieveResult result { get; set; }

        private Dictionary<String, SalesforceMetaDataApplication.WebReference.Profile> dictProfile 
            = new Dictionary<String, SalesforceMetaDataApplication.WebReference.Profile>();
        private Dictionary<String, SalesforceMetaDataApplication.WebReference.User> dictUser
            = new Dictionary<String, SalesforceMetaDataApplication.WebReference.User>();

        private List<String> lstSObjects = new List<String>();
        private List<CustomField> lstFields = new List<CustomField>();

        // Initialize the class with parameters from SFLogin. Get the Profiles, Users, and all SObjects in the org.
        public MetaInfo(SforceService sfService, MetadataService ms, LoginResult lResult, GetUserInfoResult uInfo)
        {
            InitializeComponent();
            
            sf = new SalesforceMetaDataApplication.WebReference.SforceService();
            lr = new SalesforceMetaDataApplication.WebReference.LoginResult();
            metaService = new MetadataService();
            userInfo = new GetUserInfoResult();

            this.sf = sfService;
            this.lr = lResult;
            this.userInfo = uInfo;

            this.metaService = ms;

            getProfile();
            getUser();
            retrieveSObjects();
        }

        // Retrieve all SObjects
        private void retrieveSObjects()
        {
            try 
            {
                DescribeGlobalResult dgr = sf.describeGlobal();

                DescribeGlobalSObjectResult[] dgsr = dgr.sobjects;
                foreach (DescribeGlobalSObjectResult d in dgr.sobjects)
                {
                    lstSObjects.Add(d.name);
                }
            } 
            catch (Exception e)
            {
                MessageBox.Show("Could not retrieve the Sobjects from Salesforce. " + e.Message);
            }
        }

        // Package Types
        private void profileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String strFolder = "Profile";
            String pckgType = "Profile";

            List<ProfileObjectPermissions> lstProfObjPerm = new List<ProfileObjectPermissions>();
            List<PackageTypeMembers> lstPtm = new List<PackageTypeMembers>();
            foreach(String s in lstSObjects) 
            {
                SFMetadata.ProfileObjectPermissions profObjPerm = new SFMetadata.ProfileObjectPermissions();
                profObjPerm.@object = s;
                lstProfObjPerm.Add(profObjPerm);
                
                SFMetadata.PackageTypeMembers objPckTypMembers = new SFMetadata.PackageTypeMembers();
                List<String> lstMembers = new List<String>();
                lstMembers.Add(s);
                objPckTypMembers.members = lstMembers.ToArray();
                lstPtm.Add(objPckTypMembers);

            }

            Package pck = new Package();
            pck.types = lstPtm.ToArray();

            SFMetadata.Profile objProfile = new SFMetadata.Profile();

            objProfile.objectPermissions = lstProfObjPerm.ToArray();

            // Call the methods to retrieve the profiles and zip file
            String[] profileFiles = listPackages(strFolder, pckgType);
            retrievePackages(profileFiles, pckgType, pck);

            MessageBox.Show("Extraction Complete.");
        }


        private String[] listPackages(String strFolder, String strType) {
            // can't use wildcards with reports, so need to fetch the list
            // of ReportFolders first, then fetch all the reports in
            // each folder.
            ListMetadataQuery q = new ListMetadataQuery();
            q.type = strFolder;

            FileProperties[] fp = metaService.listMetadata(new ListMetadataQuery[] { q }, API_VERSION);

            if (fp == null)
            {
                Console.WriteLine("No profile folders returned");
                return new String[0];
            }

            List<String> packageFiles = new List<String>();
            q.type = strType;
            foreach (FileProperties p in fp)
            {
                q.folder = p.fullName;
                // listMetadata can take more than one item at a time
                // left as an exercise for the reader to batch up these calls.
                FileProperties[] rps = metaService.listMetadata(new ListMetadataQuery[] { q }, API_VERSION);
                if (fp == null) continue;
                foreach (FileProperties rp in rps)
                {
                    Console.WriteLine("{0}", rp.fileName);
                    packageFiles.Add(rp.fullName);
                }
            }
            return packageFiles.ToArray();
        }

        // Overload methods to retrieve the different package types and write them to disk.
        // TODO: compress these methods into more reusable methods.
        private void retrievePackages(String[] packageFiles, String strMetaName, Package objPackage) 
        {
            // build up an unpackaged retrieve request for the list of reports.
            RetrieveRequest r = new RetrieveRequest();
            r.apiVersion = API_VERSION;
            //r.unpackaged = new Package();
            r.unpackaged = objPackage;

            PackageTypeMembers m = new PackageTypeMembers();
            m.name = strMetaName;
            m.members = packageFiles;
            r.unpackaged.types = new PackageTypeMembers[] { m };

            // start the retrieve request
            AsyncResult ar = metaService.retrieve(r);

            // wait for it to complete, sleeping as necassary.
            while (!ar.done)
            {
                System.Threading.Thread.Sleep(1000);
                ar = metaService.checkStatus(new String[] { ar.id })[0];
            }

            // did it work ?
            if (ar.state == AsyncRequestState.Error)
                Console.WriteLine("{0} {1}", ar.statusCode, ar.message);
            else
            {
                // now actually go get the results 
                RetrieveResult rr = metaService.checkRetrieveStatus(ar.id);
                if (rr.messages != null)
                    foreach (RetrieveMessage rm in rr.messages)
                        Console.WriteLine("{0} : {1}", rm.fileName, rm.problem);

                // write the zipFile out to a disk file.
                using (System.IO.FileStream fs = new System.IO.FileStream("c:\\Temp\\" + strMetaName + ".zip", System.IO.FileMode.Create))
                    fs.Write(rr.zipFile, 0, rr.zipFile.Length);
            }
        }

        private void retrievePackages(String[] packageFiles, String strMetaName)
        {
            // build up an unpackaged retrieve request for the list of reports.
            RetrieveRequest r = new RetrieveRequest();
            r.apiVersion = API_VERSION;
            r.unpackaged = new Package();

            PackageTypeMembers m = new PackageTypeMembers();
            m.name = strMetaName;
            m.members = packageFiles;
            r.unpackaged.types = new PackageTypeMembers[] { m };

            // start the retrieve request
            AsyncResult ar = metaService.retrieve(r);

            // wait for it to complete, sleeping as necassary.
            while (!ar.done)
            {
                System.Threading.Thread.Sleep(1000);
                ar = metaService.checkStatus(new String[] { ar.id })[0];
            }

            // did it work ?
            if (ar.state == AsyncRequestState.Error)
                Console.WriteLine("{0} {1}", ar.statusCode, ar.message);
            else
            {
                // now actually go get the results 
                RetrieveResult rr = metaService.checkRetrieveStatus(ar.id);
                if (rr.messages != null)
                    foreach (RetrieveMessage rm in rr.messages)
                        Console.WriteLine("{0} : {1}", rm.fileName, rm.problem);

                // write the zipFile out to a disk file.
                using (System.IO.FileStream fs = new System.IO.FileStream("c:\\Temp\\" + strMetaName + ".zip", System.IO.FileMode.Create))
                    fs.Write(rr.zipFile, 0, rr.zipFile.Length);
            }
        }
    }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
venturec3venturec3

Figured it out. In my retrievePackages method I was resetting the RetrieveRequest unpackaged value.

 

I removed the portion of code that sets up the PackageTypeMembers and it now works.

 

Easy fix after all. End user error.

All Answers

venturec3venturec3

Figured it out. In my retrievePackages method I was resetting the RetrieveRequest unpackaged value.

 

I removed the portion of code that sets up the PackageTypeMembers and it now works.

 

Easy fix after all. End user error.

This was selected as the best answer
lammylammy

I am curious about your app. I am trying to do something similar, pull down all objects, standard, custom, and those from managed packages.

 

Now you said

"The reason I need to use the C# app is because in the Force.com IDE, only unmanaged objects can be retrieved, and then viewed in the Profile metadata. In the C# application, all objects, whether managed or unmanaged are returned. I've tested this out using the CustomObject and have returned all custom objects in a zip file." 

 

Can you point me to how you accomplished this?

Thanks!!!

 

 

sushanto_dodosushanto_dodo

Hello

I tried the same thing but only getting the XML namespace in the retrieved profiles files.  The same problem exists for me that the object permissions, visibilities and other information about the profiles is not returned after the retrieve call. Can you please show the portion of code i need to comment. I tried commenting the code where we set up the packagetypemembers but still the problem exists for me. Can u please post your corrected code here once so that i can check my error or you can let me know in the following code how to rectify it. This is the code that i am using.

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Web;
using WebApplication1.WebReference;
using WebApplication1.SFMetadata;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {

        public const double API_VERSION = 23.0;

        private WebApplication1.WebReference.SforceService sf { get; set; }
        private WebApplication1.WebReference.LoginResult lr { get; set; }
        private GetUserInfoResult userInfo { get; set; }

        private MetadataService metaService { get; set; }
        private List<FileProperties> lstFp { get; set; }
        private RetrieveResult result { get; set; }

        SforceService sfService = new SforceService();
        MetadataService ms = new MetadataService();
        LoginResult lResult = new LoginResult();
        GetUserInfoResult uInfo = new GetUserInfoResult();



        private List<String> lstSObjects = new List<String>();
        private List<CustomField> lstFields = new List<CustomField>();

      
        // Retrieve all SObjects
        private void retrieveSObjects()
        {
           try
            {
                DescribeGlobalResult dgr = sf.describeGlobal();

                DescribeGlobalSObjectResult[] dgsr = dgr.sobjects;
                foreach (DescribeGlobalSObjectResult d in dgr.sobjects)
                {
                    lstSObjects.Add(d.name);
                   // Response.Write("\n object name:" + d.name);
                }
            }
            catch (Exception e)
            {
                Response.Write("Could not retrieve the Sobjects from Salesforce. " + e.Message);
            }
            //check

            //check
        }








        protected void Button1_Click(object sender, EventArgs e)
        {
            
            

            sf = new WebApplication1.WebReference.SforceService();
            lr = new WebApplication1.WebReference.LoginResult();
            metaService = new MetadataService();
            userInfo = new GetUserInfoResult();
            lResult = sfService.login("sushanto.dodo@gmail.com", "sushanto14#VIUzS26hJL1egniayIorsWtc");
            sfService.Url = lResult.serverUrl;
          //  Response.Write("\n The URL is:" + sfService.Url + "\n");
            WebReference.SessionHeader hd = new WebReference.SessionHeader();
            hd.sessionId = lResult.sessionId;
            sfService.SessionHeaderValue = hd;
        //    Response.Write("\nSessionID"+hd.sessionId+"\n");

            this.sf = sfService;
            this.lr = lResult;
            this.userInfo = uInfo;
            this.metaService = ms;
        //    Response.Write("logged in");


            // getProfile();
            // getUser();
            retrieveSObjects();
            String strFolder = "Profile";
            String pckgType = "Profile";

       /*    List<ProfileObjectPermissions> lstProfObjPerm = new List<ProfileObjectPermissions>();
            List<PackageTypeMembers> lstPtm = new List<PackageTypeMembers>();
            int r=0;
           foreach (String s in lstSObjects)
            {
                SFMetadata.ProfileObjectPermissions profObjPerm = new SFMetadata.ProfileObjectPermissions();
                profObjPerm.@object = s;
                lstProfObjPerm.Add(profObjPerm);
                SFMetadata.PackageTypeMembers objPckTypMembers = new SFMetadata.PackageTypeMembers();
                List<String> lstMembers = new List<String>();
                lstMembers.Add(s);
               // Response.Write(" listing :"+r+" "+s);
                r++;
                objPckTypMembers.members = lstMembers.ToArray();
                lstPtm.Add(objPckTypMembers);

            }

            Package pck = new Package();
            pck.types = lstPtm.ToArray();
            

            SFMetadata.Profile objProfile = new SFMetadata.Profile();

            objProfile.objectPermissions = lstProfObjPerm.ToArray();*/

             // Call the methods to retrieve the profiles and zip file

            String[] profileFiles = listPackages(strFolder, pckgType);
            retrievePackages(profileFiles,pckgType);
            Response.Write("Extraction Complete.");
            Response.Write("RetrievedSObjects");
       }
           private String[] listPackages(String strFolder, String strType)
           {
            // can't use wildcards with reports, so need to fetch the list
            // of ReportFolders first, then fetch all the reports in
            // each folder.
            ListMetadataQuery q = new ListMetadataQuery();
            q.type = strFolder;

            SFMetadata.SessionHeader h = new SFMetadata.SessionHeader();
            h.sessionId = lResult.sessionId;
            ms.SessionHeaderValue = h;

            FileProperties[] fp = ms.listMetadata(new ListMetadataQuery[] { q }, API_VERSION);

            if (fp == null)
            {
                Console.WriteLine("No profile folders returned");
                return new String[0];
            }

            List<String> packageFiles = new List<String>();
            q.type = strType;
           // int iCnt = 0;
            foreach (FileProperties p in fp)
            {
                q.folder = p.fullName;
                packageFiles.Add(p.fullName);
          //      Response.Write("\n Foldername : "+p.fullName);
              //  Response.Write("\n Full Name:"+p.fullName+"\n");
                // listMetadata can take more than one item at a time
                // left as an exercise for the reader to batch up these calls.
             /*   FileProperties[] rps = ms.listMetadata(new ListMetadataQuery[] { q }, API_VERSION);
                if (fp == null) continue;

               // packageFiles.Add(rps[iCnt].fullName);

               // Response.Write("\n File Name:" + rps[iCnt].fileName + "\n<br>");
                iCnt++;


              foreach (FileProperties rp in rps)
                {
                    Console.WriteLine("{0}", rp.fileName);
                    packageFiles.Add(rp.fullName);
                    //Response.Write("\n File Name:"+rp.fileName+"\n");
                }*/
            }
            return packageFiles.ToArray();
        }

        // Overload methods to retrieve the different package types and write them to disk.
        // TODO: compress these methods into more reusable methods.
          


        private void retrievePackages(String[] packageFiles,String strMetaName)
        {


           /* SFMetadata.SessionHeader h = new SFMetadata.SessionHeader();
            h.sessionId = lResult.sessionId;
            ms.SessionHeaderValue = h;*/
            // build up an unpackaged retrieve request for the list of reports.
            RetrieveRequest r = new RetrieveRequest();
            r.apiVersion = API_VERSION;
            r.unpackaged = new Package();
           // r.unpackaged = objPackage;

          //  objPackage.types.
            int i =0;

           /* foreach (PackageTypeMembers x in objPackage.types)
            {
                x.name = strMetaName.ToString();

                x.members = packageFiles;
                //string y = x.members.GetValue(i).ToString();  
                i++;
            }*/
 
         //   r.unpackaged.types = objPackage.types ;  

            

            PackageTypeMembers m = new PackageTypeMembers();
            m.name = strMetaName;
            m.members = packageFiles;
            r.unpackaged.types = new PackageTypeMembers[] { m };

            // start the retrieve request
            AsyncResult ar = metaService.retrieve(r);

            // wait for it to complete, sleeping as necassary.
            while (!ar.done)
            {
                System.Threading.Thread.Sleep(1000);
                ar = metaService.checkStatus(new String[] { ar.id })[0];
            }

            // did it work ?
            if (ar.state == AsyncRequestState.Error)
                Response.Write("\n ERROR Generated");
            else
            {
                // now actually go get the results
                RetrieveResult rr = metaService.checkRetrieveStatus(ar.id);
                /*  if (rr.messages != null)
                      foreach (RetrieveMessage rm in rr.messages)
                          Response.Write*/

                // write the zipFile out to a disk file.
                using (System.IO.FileStream fs = new System.IO.FileStream("c:\\retrieve\\" + strMetaName + ".zip", System.IO.FileMode.Create))
                    fs.Write(rr.zipFile, 0, rr.zipFile.Length);
            }
        }





            }

           
        }