function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sushanto_dodosushanto_dodo 

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader Illegal Session

I have the folllowing code and i get the invalid session Id exception.  How to remove it ? Can someone please assist? I am new to use salesforce metadata API. The line highlighted in RED  is where the exception is raised.

 

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 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; }



        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("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)
        {

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

            sf = new WebApplication1.WebReference.SforceService();
            lr = new WebApplication1.WebReference.LoginResult();
            metaService = new MetadataService();
            userInfo = new GetUserInfoResult();
          loginresult is obtained here
            sfService.Url = lResult.serverUrl;
            Response.Write("URL : " + lResult.serverUrl);
            WebReference.SessionHeader hd = new WebReference.SessionHeader();
            hd.sessionId = lResult.sessionId;
            sfService.SessionHeaderValue = hd;
            Response.Write("\nSessionID"+lResult.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>();
            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
            // REPLACED  THE LIST PACKAGE METHOD

            // 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;
            Response.Write("\nSessionID"+lResult.sessionId+"\n");
            FileProperties[] fp = metaService.listMetadata(new ListMetadataQuery[] { q }, API_VERSION);
            /*
            if (fp == null)
            {
                Console.WriteLine("No profile folders returned");
                return ;
            }

            List<String> packageFiles = new List<String>();
            q.type = pckgType;
            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);
                }
            }

            String[] profileFiles = packageFiles.ToArray(); ;

            // RETRIEVEPACKAGE METHOD CODE

            // 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 = pck;

            PackageTypeMembers m = new PackageTypeMembers();
            m.name = pckgType;
            m.members = profileFiles;
            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:\\" + pckgType + ".zip", System.IO.FileMode.Create))
                    fs.Write(rr.zipFile, 0, rr.zipFile.Length);
            }
            */
            Response.Write("Extraction Complete.");
            Response.Write("RetrievedSObjects");

        }



    }
}

Best Answer chosen by Admin (Salesforce Developers) 
MartinHaagenMartinHaagen

Hi sushanto_dodo

 

I beilive you need to set the session header on the metaService. You should be able to use the same SessionHeader object as for the sfService object.

 

You should probably change your username and password - it's not wise to post username, password and security key on the boards. 

 

Best regards

 

Martin

All Answers

MartinHaagenMartinHaagen

Hi sushanto_dodo

 

I beilive you need to set the session header on the metaService. You should be able to use the same SessionHeader object as for the sfService object.

 

You should probably change your username and password - it's not wise to post username, password and security key on the boards. 

 

Best regards

 

Martin

This was selected as the best answer
sushanto_dodosushanto_dodo

Hey thanks a lot.

I have sorted it out. I obtained the session Id from the Partner WSDL and assigned it to the metadata Header and it worked. Now the problem that i am facing is it is not giving out the profile permissions and visibilities as it should. When we see the profiles which are retrieved it only displays the xml namespace and it doesnt give the profile object permissions as it should. I also checked in eclipse migration tool that the profiles are returned blank from my salesforce instance when i try to only retrieve profiles whereas when i try to retrieve all the components , then it works fine and all the profiles have proper object permissions and visibilities in them.

Can you please review the code and let me know how can i fix my code to retrieve the proper information about profiles?

 

sushanto_dodosushanto_dodo

this is the code that i have now.

Please check and let  me know how can i obtain all the info regarding the object permission and visibilities for all profiles.

 

 

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("********", "*********************");
            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,pck);
            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)
            {

                packageFiles.Add(p.fullName);
                //q.folder = p.fullName;
              //  packageFiles.Add("*");
          //      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, Package pck)
        {


           /* 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 = pck;

          //  objPackage.types.
          

            foreach (PackageTypeMembers x in pck.types)
            {
                x.name = strMetaName.ToString();

                x.members = packageFiles;
                //string y = x.members.GetValue(i).ToString();  
              //  i++;
            }
 
            r.unpackaged.types = pck.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);
            }
        }





            }

           
        }



    

MartinHaagenMartinHaagen
I don't remember if you can get a very detailed permission information in the outputed XML - however, my tip is to make sure the latest API version is used. The API version determines what infrormation you will se.

You can find the version number in the endpoint URL, simply change this to the latest version.
sushanto_dodosushanto_dodo

Hello

i m using the latestAPI version but it still doesnt retrieve the detailed information for the profiles in the output XML. any idea ?