Code Monkey home page Code Monkey logo

apex-mdapi's People

Contributors

afawcett avatar afawcettffdc avatar agarciaodeian avatar dfruddffdc avatar douglascayers avatar grekker avatar jmillsffdc avatar kgalant avatar ku8ar avatar mintotsai avatar orthographic-pedant avatar pokharna avatar wes1278 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apex-mdapi's Issues

Code to update field & Calling creatobject(), or creatfield() method

Hi , Great post , thank a lot ,
i am working on this post now a days ,
and i followed every step you described i.e : changing wsdl , updating class by adding attributes
and page is working fine . thanks .

My question is regarding some method you defined createobejct() , creatfields etc ,
you said "this will need to be done in your Visualforce controller via a timed refresh or via a scheduled job." how to accomplish that

cause when i m saving them in a apex class I am getting following error :

-> Save error: Initial expression is of incorrect type, expected: MetadataService.Metadata
at line
->MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> { customObject });

Can you give a simple example of calling createobject() method to insert new object

Thanks in advance

Test Coverage

Hi Andy,

First of all - thank you for such a great resource on using the metadata api. I have tried playing around with it and got some satisfying results. Just wanted to ask if you managed to write any test cases for the classes? I have been struggling to do so and any help will be hugely appreciated.

Regards
Vipul

MD-API: Retrieve Email Alerts Metadata

Dear Andrew,
Thanks again for stepping forward to help!

My use case is to retrieve the list of all email alerts in my org with their name, description, sender-address, recipients, & CC'ed recipients. For this I have come up with the below code which I execute from the anonymous exec in dev console.

MetadataService.MetadataPort service = MetadataService.createService();

List<MetadataService.ListMetadataQuery> queries = new List<MetadataService.ListMetadataQuery>();
MetadataService.ListMetadataQuery queryEmailAlert = new MetadataService.ListMetadataQuery();
queryEmailAlert.type_x = 'WorkflowAlert';
queries.add(queryEmailAlert);

//get metadatalist
MetadataService.FileProperties[] properties = service.ListMetaData(queries,30);
for(MetadataService.FileProperties emailalert:properties){
        system.debug('Email Alert Name:::'+emailalert.fullname);

       //read metadata
       MetadataService.Metadata[] mdInfo = service.readMetadata('WorkflowAlert',new String[]{emailalert.fullname}).records;
        for(MetadataService.Metadata md:mdInfo){
            MetadataService.WorkflowAlert alert = (MetadataService.WorkflowAlert)md;
            system.debug('description:::'+alert.description);
            system.debug('From:::'+alert.senderAddress);
        }
}

But the execution stops with the error:

 "incompatible types since an instance of MetadataService.Metadata is never an instance of MetadataService.WorkflowAlert"

I believe it doesn't allow Metadata to be Typecast to WorkflowAlert. But I am not sure if the results can be achieved without doing that.
Can you please help letting me know where I am going wrong here?
Greatly appreciate your help! Many Thanks!

Note:
Since the class generated by the MetadataAPI wsdl exceeds my Apex Limit, I have cut it short to contain only what is required to achieve the required use case. Below is my short version of the MetadataService class used here for additional info, in case you like to have a look.

//Generated by wsdl2apex
public class MetadataService {
    public class MetadataPort {
        public String endpoint_x = 'https://cs30.salesforce.com/services/Soap/m/30.0';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public MetadataService.SessionHeader_element SessionHeader;
        public MetadataService.DebuggingInfo_element DebuggingInfo;
        public MetadataService.CallOptions_element CallOptions;
        public MetadataService.DebuggingHeader_element DebuggingHeader;
        private String SessionHeader_hns = 'SessionHeader=http://soap.sforce.com/2006/04/metadata';
        private String DebuggingInfo_hns = 'DebuggingInfo=http://soap.sforce.com/2006/04/metadata';
        private String CallOptions_hns = 'CallOptions=http://soap.sforce.com/2006/04/metadata';
        private String DebuggingHeader_hns = 'DebuggingHeader=http://soap.sforce.com/2006/04/metadata';
        private String[] ns_map_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata', 'MetadataService'};
        public MetadataService.FileProperties[] listMetadata(MetadataService.ListMetadataQuery[] queries,Double asOfVersion) {
            MetadataService.listMetadata_element request_x = new MetadataService.listMetadata_element();
            MetadataService.listMetadataResponse_element response_x;
            request_x.queries = queries;
            request_x.asOfVersion = asOfVersion;
            Map<String, MetadataService.listMetadataResponse_element> response_map_x = new Map<String, MetadataService.listMetadataResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://soap.sforce.com/2006/04/metadata',
              'listMetadata',
              'http://soap.sforce.com/2006/04/metadata',
              'listMetadataResponse',
              'MetadataService.listMetadataResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.result;
        }
        public MetadataService.ReadResult readMetadata(String type_x,String[] fullNames) {
            MetadataService.readMetadata_element request_x = new MetadataService.readMetadata_element();
            MetadataService.readMetadataResponse_element response_x;
            request_x.type_x = type_x;
            request_x.fullNames = fullNames;
            Map<String, MetadataService.readMetadataResponse_element> response_map_x = new Map<String, MetadataService.readMetadataResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://soap.sforce.com/2006/04/metadata',
              'readMetadata',
              'http://soap.sforce.com/2006/04/metadata',
              'readMetadataResponse',
              'MetadataService.readMetadataResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.result;
        }
    }
    public class ReadResult {
        public MetadataService.Metadata[] records;
        private String[] records_type_info = new String[]{'records','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'records'};
    }
    public class Metadata {
        public String fullName;
        private String[] fullName_type_info = new String[]{'fullName','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'fullName'};
    }
    public class WorkflowEmailRecipient {
        public String field;
        public String recipient;
        public String type_x;
        private String[] field_type_info = new String[]{'field','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] recipient_type_info = new String[]{'recipient','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] type_x_type_info = new String[]{'type','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'field','recipient','type_x'};
    }
    public class WorkflowAlert {
        public String[] ccEmails;
        public String description;
        public Boolean protected_x;
        public MetadataService.WorkflowEmailRecipient[] recipients;
        public String senderAddress;
        public String senderType;
        public String template;
        private String[] ccEmails_type_info = new String[]{'ccEmails','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] description_type_info = new String[]{'description','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] protected_x_type_info = new String[]{'protected','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] recipients_type_info = new String[]{'recipients','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] senderAddress_type_info = new String[]{'senderAddress','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] senderType_type_info = new String[]{'senderType','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] template_type_info = new String[]{'template','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'ccEmails','description','protected_x','recipients','senderAddress','senderType','template'};
    }
    public class DebuggingInfo_element {
        public String debugLog;
        private String[] debugLog_type_info = new String[]{'debugLog','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'debugLog'};
    }
    public class CallOptions_element {
        public String client;
        private String[] client_type_info = new String[]{'client','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'client'};
    }
    public class DebuggingHeader_element {
        public MetadataService.LogInfo[] categories;
        public String debugLevel;
        private String[] categories_type_info = new String[]{'categories','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] debugLevel_type_info = new String[]{'debugLevel','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'categories','debugLevel'};
    }
    public class SessionHeader_element {
        public String sessionId;
        private String[] sessionId_type_info = new String[]{'sessionId','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'sessionId'};
    }
    public class LogInfo {
        public String category;
        public String level;
        private String[] category_type_info = new String[]{'category','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] level_type_info = new String[]{'level','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'category','level'};
    }
    public class listMetadataResponse_element {
        public MetadataService.FileProperties[] result;
        private String[] result_type_info = new String[]{'result','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'result'};
    }
    public class ListMetadataQuery {
        public String folder;
        public String type_x;
        private String[] folder_type_info = new String[]{'folder','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] type_x_type_info = new String[]{'type','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'folder','type_x'};
    }
    public class FileProperties {
        public String createdById;
        public String createdByName;
        public DateTime createdDate;
        public String fileName;
        public String fullName;
        public String id;
        public String lastModifiedById;
        public String lastModifiedByName;
        public DateTime lastModifiedDate;
        public String manageableState;
        public String namespacePrefix;
        public String type_x;
        private String[] createdById_type_info = new String[]{'createdById','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] createdByName_type_info = new String[]{'createdByName','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] createdDate_type_info = new String[]{'createdDate','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] fileName_type_info = new String[]{'fileName','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] fullName_type_info = new String[]{'fullName','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] id_type_info = new String[]{'id','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] lastModifiedById_type_info = new String[]{'lastModifiedById','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] lastModifiedByName_type_info = new String[]{'lastModifiedByName','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] lastModifiedDate_type_info = new String[]{'lastModifiedDate','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] manageableState_type_info = new String[]{'manageableState','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] namespacePrefix_type_info = new String[]{'namespacePrefix','http://soap.sforce.com/2006/04/metadata',null,'0','1','false'};
        private String[] type_x_type_info = new String[]{'type','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'createdById','createdByName','createdDate','fileName','fullName','id','lastModifiedById','lastModifiedByName','lastModifiedDate','manageableState','namespacePrefix','type_x'};
    }
    public class listMetadata_element {
        public MetadataService.ListMetadataQuery[] queries;
        public Double asOfVersion;
        private String[] queries_type_info = new String[]{'queries','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] asOfVersion_type_info = new String[]{'asOfVersion','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'queries','asOfVersion'};
    }
    public class readMetadata_element {
        public String type_x;
        public String[] fullNames;
        private String[] type_x_type_info = new String[]{'type','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] fullNames_type_info = new String[]{'fullNames','http://soap.sforce.com/2006/04/metadata',null,'0','-1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'type_x','fullNames'};
    }
    public class readMetadataResponse_element {
        public MetadataService.ReadResult result;
        private String[] result_type_info = new String[]{'result','http://soap.sforce.com/2006/04/metadata',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
        private String[] field_order_type_info = new String[]{'result'};
    }
    public static MetadataService.MetadataPort createService() {
        partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
//        system.debug('loging in...');
        partnerSoapSforceCom.LoginResult loginResult = sp.login('uid','pwd');
//        system.debug('Login Result:::' +loginResult);

        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = loginResult.sessionId;
//      service.SessionHeader.sessionId = UserInfo.getSessionId();
        return service;    
    }
}

Need help..Getting error while trying to deploy hello world class

I am trying to deploy a hello world class in MetadataDeploy controller using the api.When i click on Deploy button,getting the error :

System.NullPointerException: Attempt to de-reference a null object Error is in expression '{!checkAsyncRequest}' in page metadatadeploy
Class.MetadataDeployController.checkAsyncRequest: line 106, column 1

Any info or pointers would be helpful.

Saving MetadataController causes errors..

When I try to save MetadataController it gives error below in eclips...
Error::
Save error: Method does not exist or incorrect signature: WebServiceCallout.invoke(MetadataService.MetadataPort, MetadataService.retrieve_element, MAP<String,AbdnS3.MetadataService.retrieveResponse_element>, LIST) MetadataService.cls /Abdullah/src/classes...

I am stuck at this point... need help.

Add field in page layout and create a profile using apex metadata api

Hi

I just want to add/remove field from Custom object page layout also make it read only from the page layout using Apex metadata api can u provide me the syntax,

Other problem is that I want to create profile by cloning the “Standard User” using Apex Metadata API .

Can u help me to come out of this.

Need help..Getting error while trying to deploy profile

I am trying to deploy a profile using the api. I am getting an error

profiles/Standard Platform Usercopy.profile (Line: null: Column:null) : duplicate value found: duplicates value on record with id: .

Any info or pointers would be helpful.

Failed to add Custom Button to the Layout RelatedList

Hi Andrew,

I tried to add a Custom Button to the OpportunityLineItem related list on the Opportunity layout. Got the "message=Field: relatedLists, value:RelatedLineItemList appears more than once," error when I ran the code below, any ideas why? Please advise.

Best Regards,

Paul

public PageReference updateLayout(){
    try {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();      

        // Read the Layout      
        MetadataService.Layout OPMPlayout = 
        (MetadataService.Layout) service.readMetadata('Layout', 
        new String[] { 'Opportunity-Opportunity Layout' }).getRecords()[0];

        // Add the Custom Button to the Layout relatedLists
        if(OPMPlayout.relatedLists==null)
            OPMPlayout.relatedLists = new List<MetadataService.relatedListItem>();
        MetadataService.relatedListItem OPMPrelatedListItem = new MetadataService.relatedListItem();
        OPMPrelatedListItem.relatedList = 'RelatedLineItemList';            
        if(OPMPrelatedListItem.customButtons==null)
            OPMPrelatedListItem.customButtons = new List<String>();
        OPMPrelatedListItem.customButtons.add('Mass_Price');            
        OPMPlayout.relatedLists.add(OPMPrelatedListItem);   

        // Update the Layout
        MetadataService.SaveResult[] OPMPresults = service.updateMetadata(new List<MetadataService.Metadata> { OPMPlayout });
        system.debug('OPMPresults = ' + OPMPresults);           
    } catch (Exception e) {
        return null;
    }
    return null;                    
}  

16:07:10:898 USER_DEBUG [300]|DEBUG|OPMPresults =
(SaveResult:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false),
errors=(Error:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false),
field_order_type_info=(fields, message, statusCode),
fields=null,
fields_type_info=(fields, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false),
message=Field: relatedLists, value:RelatedLineItemList appears more than once,
message_type_info=(message, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false),
statusCode=FIELD_INTEGRITY_EXCEPTION,
statusCode_type_info=(statusCode, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false)]),
errors_type_info=(errors, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false),
field_order_type_info=(errors, fullName, success),
fullName=Opportunity-Opportunity Layout,
fullName_type_info=(fullName, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false),
success=false, success_type_info=(success, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false)])

I could manually add my Custom Button to the Layout Related List, below is the xml after it's added ...

image

This is a question - maybe an issue with new Spring '14 call

There is a new CRUD call in Spring '14 / API 30 named "readMetadata" (http://www.salesforce.com/us/developer/docs/api_meta/Content/meta_readMetadata.htm).

I expect this is an implementation error but since it's a new call I thought my challenge was worth reporting.

I think in my instance the SFDC parser was failing to recognize the response as the CustomField class extending Metadata.

Error message: Web service callout failed: Unable to parse callout response. Apex type not found for element externalId

Here's the raw soap response up until the point of failure
'''
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<readMetadataResponse>
<result>
<records xsi:type="CustomField">
<fullName>Case.Custom_Field__c</fullName>
<externalId>false</externalId>
'''

And the apex classes for the parsing
'''
public class readMetadataResponse_element {
public SFDC_API_MetaData.ReadResult result;
private String[] result_type_info = new String[]{'result','http://soap.sforce.com/2006/04/metadata','ReadResult','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
private String[] field_order_type_info = new String[]{'result'};
}
public class ReadResult {
public SFDC_API_MetaData.Metadata[] records;
private String[] records_type_info = new String[]{'records','http://www.w3.org/2001/XMLSchema','Metadata','0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
private String[] field_order_type_info = new String[]{'records'};
}
public virtual class Metadata {
public String fullName;
private String[] fullName_type_info = new String[]{'fullName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/2006/04/metadata','true','false'};
private String[] field_order_type_info = new String[]{'fullName'};
}
public class CustomField extends Metadata {
public String type = 'CustomField';
public String fullName;
[...]
public Boolean externalId;
[...]
private String[] type_att_info = new String[]{'xsi:type'};
[...]
private String[] externalId_type_info = new String[]{'externalId','http://www.w3.org/2001/XMLSchema','boolean','0','1','false'};
[...]
}
'''

Adding "public boolean externalId;" to the Metadata class results in the next field being reported as missing. I think the instruction to create CustomField instances is in the "xsi:type='CustomField'" attribute of the tag, which uses a different namespace (which you can see I've been fiddling with).

Create an Apex REST Websevice wrapper

Given the amount of Apex code that this creates in the respective Orgs, it would be interesting to create 1 org that exposes these as Apex REST services and then anyone call those Apex REST services using the session Id from the respective orgs. You can either use the Ajax proxy to make the call using JS form a VF/Custom button or use Apex HTTP callouts to make these calls.

Essentially make this MDAPI-aaS so that any improvements you do to this single org can be automatically available to everyone consuming.

readmetadata returning null records when used for getting Flows in Salesforce Org

i am using apex-mdapi .i invoked the function

MetadataService.ReadFlowResult c = (MetadataService.ReadFlowResult) service.readMetaData('Flow', new List{'Calculator','SAMPLE_Lead_Convert_Flow'});

where Calculator and SAMPLE_Lead_Convert_Flow is the name of flows in my dev org.in debug log response is

21:28:23.542 (542647408)|SYSTEM_METHOD_ENTRY|[8583]|WebServiceCallout.invoke(APEX_OBJECT, APEX_OBJECT, MAP, LIST)
21:28:23.546 (546821097)|CALLOUT_REQUEST|[8583]|

<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Header><SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata"><sessionId>00D90000000vSiF!AQYAQNpub28oY56fhJDV1s5fErWLQ.hC_cjCHYloA1c_.qvLy6LAEHBSH5SCCe92uKqBRIf3n.O.nEm13H4TucMVyXMWOZfi</sessionId></SessionHeader></env:Header><env:Body><readMetadata xmlns="http://soap.sforce.com/2006/04/metadata"><type>Flow</type><fullNames>SAMPLE_Lead_Convert_Flow</fullNames><fullNames>Calculator</fullNames></readMetadata></env:Body></env:Envelope>

21:28:23.546 (546918624)|CALLOUT_REQUEST|[8583]|readMetadata_element:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(type_x, fullNames), fullNames=(SAMPLE_Lead_Convert_Flow, Calculator), fullNames_type_info=(fullNames, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false), type_x=Flow, type_x_type_info=(type, http://soap.sforce.com/2006/04/metadata, null, 1, 1, false)]::SFDC_STACK_DEPTH=1 SOAPAction="" User-Agent=SFDC-Callout/30.0 Accept=text/xml Content-Type=text/xml; charset=UTF-8
21:28:23.574 (574584199)|CALLOUT_RESPONSE|[8583]|

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><readMetadataResponse><result><records xsi:nil="true"/><records xsi:nil="true"/></result></readMetadataResponse></soapenv:Body></soapenv:Envelope>

as you can see in readMetadataResponse records are giving null.i was expecting two xml correspoding to two flow objects.can anyone plz help how to resolve this issue ??

Metadata API exception: IO Exception: Exceeded max size limit of 3000000

I am using your Metadata API wrapper class to get information about our org. I want to retrieve all custom fields present in my org. I am using listMetadata() method which returns list of components. Below is my code:

MetadataService.MetadataPort service = createService();            
        List<MetadataService.ListMetadataQuery> queries = new List<MetadataService.ListMetadataQuery>();       
        MetadataService.ListMetadataQuery queryLayout = new MetadataService.ListMetadataQuery();
        //queryLayout.folder = MetaDataFolder;
        queryLayout.type_x ='CustomField';
        queries.add(queryLayout);      
        MetadataService.FileProperties[] fileProperties; 
        try{    
         fileProperties= service.listMetadata(queries, 29); //here 29 is api version
        }catch(exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info,e.getMessage()));
        }

I am get exception as "IO Exception: Exceeded max size limit of 3000000". I know that number of custom fields present in my org is to much and the response that I am getting exceeding the allowed limit of 3MB. I want to list all custom fields present in my org. Same exception is coming when I am retrieving few other metadata(like all profile). Above mentioned code works fine in my developer org but in sandbox, its not working as number of metadata components is too much in my sandbox.

I tried retrieving the components using Workbench which also uses metadata api. Workbench retrieved all components successfully. So there will be some mechanism in metadata API through which I can retrieve large number of components. I saw few post where people says to retrieve info in different chunks by splitting single request in 2 or 3 different request. But in my case, I am not able to split my request as I want all custom fields.

Can you guide me on how I can resolve this issue ?

Not able to Retrieve Approval Process

Hi,

I want to list metadata about Approval Process, when I changed the API version to 30 in "MetadataRetrieveController" class then it shows me "ApprovalProcess" in "Metadata Type" but when as I select this value then getting error "Cannot use: ApprovalProcess in this version faultcode=sf:INVALID_TYPE faultactor=".

Can you please help me to fix this issue.

Thanks in Advance.
Imran

How to get List View from metadata API?

Hi Andrew,

Your API is pretty good. I have a problem on getting ListView for objects.

Your API tells us how to create and delete listviews. I want to know how to get (search) listviews for object.
Can you please provide some code to get the List Views for each object?

Need Help - Add components to Home Page Layout through Metadata API

As per my requirement I have to add components to Home Page Layout through Apex, and my client has suggested to use Metadata API. I found two wrapper classes “HomePageLayout” and “HomePageComponent”,, but I am not able to add components to HomePageLayout . I am stuck in this big time. Could you help me please

Request : need some help on record type , Picklist field Describe call

Hi ,
I was working on assigning Picklist values to record type (Updating Record Type )and i discovered a huge issue
May be you can help me out here

1 . Here is the code for creating a Record type
Object : Lead
New Record Type name : Second Record Type
business Process= first lead process
Picklist Field : dependent picklist
Existing Picklist values in this Picklist - Dependent 0 , Dependent 1 , Dependent 2 , Dependent 3

Picklist values to be assigned in this record type :  Dependent 0, Dependent 1 , Dependent 2

Public static void InserRecordtype()
    {
        MetadataService.MetadataPort service = createService(); 
        MetadataService.RecordType rt = new MetadataService.RecordType();
            rt.fullName='lead.second_Record_Type';
            rt.label='Second Record Type';
            rt.active= true;
            rt.businessProcess= 'first lead process';
        
        MetadataService.RecordTypePicklistValue mrt = new MetadataService.RecordTypePicklistValue ();
            mrt.picklist = 'dependent_picklist__c';
                metadataservice.PicklistValue two = new metadataservice.PicklistValue();
                    two.fullName= 'Dependent 1';
                    two.default_x=false ;
                metadataservice.PicklistValue three = new metadataservice.PicklistValue();
                    three.fullName= 'Dependent 0';
                    three.default_x=false ; 
                    
                metadataservice.PicklistValue four = new metadataservice.PicklistValue();
                    four.fullName= 'Dependent 2';
                    four.default_x=false ;       
                
          mrt.values = new list<metadataservice.PicklistValue> {two,three,four} ;
          
        rt.picklistValues = new list <MetadataService.RecordTypePicklistValue>{mrt};
        
      MetadataService.AsyncResult[] results = service.create (new List<MetadataService.Metadata> { rt });
    }



---- works perfectly , new Record type created , and picklist values assigned for field ---------------

2 . Now .
if I want to add new values in Assigned Picklist Values at above record type
New Picklist value to be added : Dependent 3
so here is the code for updating record type

 

Public static void UpdateRecordtype()
    {
        MetadataService.MetadataPort service = createService(); 
        MetadataService.RecordType rt = new MetadataService.RecordType();
        rt.fullName='lead.second_Record_Type';
        rt.label='Second Record Type';
        rt.active= true;
        rt.businessProcess= 'first lead process';
        
        MetadataService.RecordTypePicklistValue mrt = new MetadataService.RecordTypePicklistValue ();
        mrt.picklist = 'dependent_picklist__c';
            metadataservice.PicklistValue five = new metadataservice.PicklistValue();
                five.fullName= 'Dependent 3';
                five.default_x=false ;
           
          mrt.values = new list<metadataservice.PicklistValue> {five} ;
          
        rt.picklistValues = new list <MetadataService.RecordTypePicklistValue>{mrt};
        
        
        
         MetadataService.UpdateMetadata ut = new MetadataService.UpdateMetadata();
        ut.currentName='lead.second_Record_Type';
        ut.metadata= rt;
       MetadataService.AsyncResult[] results = service.updateMetadata(new List<MetadataService.updateMetadata> {ut});
    
    }

3- Ideally in a perfect word : now assigned values should be : Dependent 0 , Dependent 1 , Dependent 2 , Dependent 3

.............................BUT ........................
---> Now assigned value contain only : Dependent 3 (i.e it removes all existing values )

So my question is : is there any method to get existing assigned picklist values for any record type
in my case Dependent 0 , Dependent 1 , Dependent 2 . before inserting new values
If i pass
Object : lead
Record type name : Second record Type
Picklist Field name : dependent picklist

In Describe Metadata or any other method ???

or , any method by which we can keep the existing values and add new picklist values without removing old one ??

Error While Creating a Button Through Meta Api

Hi , Great post , thank a lot ,
i am working on this ,
My question is regarding Creation of A button
I have created Fields and Lookup but when i want to create a button one error occurs

public void createButton()
{
MetadataService.MetadataPort service=createService();
MetadataService.ActionOverride customButton=new MetadataService.ActionOverride();
customButton.actionName = '';
customButton.comment = '';
customButton.content = '';
customButton.skipRecordTypeSelect = false;
customButton.type_x = '';
MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> {customButton});/error/
}

Save error: Initial expression is of incorrect type, expected: MetadataService.Metadata
Sir How can i Resolve this...?

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INSUFFICIENT_ACCESS: use of the Metadata API requires a user with the ModifyAllData permission

Hi Andrew,

I am facing below exception when I log in as non admins. It works well for Sysadmin.
System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INSUFFICIENT_ACCESS: use of the Metadata API requires a user with the ModifyAllData permission.

Apex runs in system mode how does Metadata API taking the permission of the user. Can you please help me in understanding this.

Thank you in advance.

Dynamic object name how to assign to Layout name location?

Hi andrew fawcett,

Field accepted but Layout name not accepted(Fullname Error).My object name like below

String objectname='rajesh__'+objectname+'__c';//In debug like:rajesh__Test__c

I try to below ways:

1)MetadataService.Layout layout =
(MetadataService.Layout) service.readMetadata('Layout',
new String[] {'rajesh__+objectname__c-rajesh__+objectname Layout'}).getRecords()[0];//here problem
2)MetadataService.Layout layout =
(MetadataService.Layout) service.readMetadata('Layout',
new String[] {'rajesh__'+objectname+'c'-'rajesh'+objectname Layout'}).getRecords()[0];//here problem
3)String obj='rajesh__'+objectname+'c';//debug no problem:rajesh__Test__C
String layoutname='rajesh
'+objectname;//debug no problem:rajesh__Test
MetadataService.Layout layout =
(MetadataService.Layout) service.readMetadata('Layout',
new String[] {'obj-layoutname Layout'}).getRecords()[0];//here problem

Above 3 ways same error:

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: null: Required field is missing: fullName faultcode=sf:UNKNOWN_EXCEPTION faultactor=
Error is in expression '{!createField}' in component apex:commandButton in page rajesh:createfields

Class.rajesh.MetadataService.MetadataPort.updateMetadata: line 8193, column 1
Class.rajesh.MetadataController11.addFieldToLayout: line 918, column 1
Class.rajesh.MetadataController11.createField: line 243, column 1

help me........

updateMetadata with listView & filterScope

Hi Andrew,
I really like the work you've done here - I've been applying it to several different projects. I have a need to programmatically modify the sharing on list views, i've been playing around with this but I haven't been able to achieve the results I'm looking for. When I pass a list to the updateMetadata method, the pieces I have declared update but everything else is set to erased; such as the fields, filters, etc. Second, I noticed that updating some lists I need to designate the listView.filterScope or an error returns "System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: '' is not a valid value for the enum 'FilterScope' faultcode=soapenv:Client faultactor=", which isn't a huge problem but I would have to set that value to 'Everyone' that may overwrite some lists settings.

In a perfect world I'd like to run this process:

  1. Query all listViews created by a specific user/role
  2. Change the sharing to a public group
  3. Update

I've attached the code I've found to work best so far, and to simplify i'm only looking at a single list - ideally I would run it in bulk. If you have any pointers please let me know, maybe i'm using this completely wrong.

'''

public void listViewShare(string lvName){
    MetadataService.ListView listView = new MetadataService.ListView();
    listView.fullName = 'contact.'+lvName;
    listView.filterScope = 'Everything';
    listView.sharedTo = new MetadataService.sharedTo();
    listView.sharedTo.groups = new list<String>{ 'Territory_Central' };

    List<MetadataService.UpdateMetadata> updateMetadataList = new List<MetadataService.UpdateMetadata>();   
    updateMetadataList.add(new MetadataService.UpdateMetadata());
    updateMetadataList[0].currentName = 'contact.'+lvName;
    updateMetadataList[0].metadata = listView;

    MetadataService.AsyncResult[] results = service.updateMetadata(updateMetadataList); 

}

'''

How to retrieve Custom Object Definition Detail fields with in the pageblock table?

Hi Andrew Fawcett,
I want to below fields not Object related Standard fields
How to retrieve below fields with in the pageblocktable using wrapper class in an visualforce page
Object Name: DynamicForm
Created By : rajesh, 5/6/2014 8:14 PM
Modified By : epani bisoftsols, 6/5/2014 9:34 PM

Note:Not object Standard fields

help me ......

Using metadata api how to delete object permanently From database?

Using below code i deleted objects.but permanently not deleted
public PageReference doDelete(){
MetadataService.MetadataPort service = createService();
String selectedid = System.currentPagereference().getParameters().get('p2');
List myCustomObjectList = new List();
MetadataService.CustomObject customObject = new MetadataService.CustomObject();
customObject.fullName = 'rajesh__'+selectedid+'__c';
myCustomObjectList.add(customObject);

MetadataService.AsyncResult[] results = service.deleteMetadata(myCustomObjectList);
}
When i displayed all objects in an page block table using Tooling api.Some objects names come looks like below with in the pageBlock table .
DynamicForm_del
PurchaseForm_del
Master_zip_load_del
How to remove these objects permanently From Database using above code?
help me......

fetching custom label

Hi ,

Thanks for the great examples. Using the metadataretrieve page we can get the custom label name, But is it possible to get the value of the custom label??

Regards
Sam

How give Field accessable permission as Editable in pagelayouts Using metadata api?

Hi Andrew Fawcett,
I got following Error Related to addFieldToLayout() in your metadata api github related method.

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: null: Required field is missing: fullName faultcode=sf:UNKNOWN_EXCEPTION faultactor=
Error is in expression '{!createField}' in component apex:commandButton in page rajesh:createfields

Class.rajesh.MetadataService.MetadataPort.updateMetadata: line 8193, column 1
Class.rajesh.MetadataController11.addFieldToLayout: line 906, column 1
Class.rajesh.MetadataController11.createField: line 243, column 1
line 906:
handleSaveResults(
service.updateMetadata(
new MetadataService.Metadata[] { layout })[0]);
line 246:I called addFieldToLayout()

Enhancement : Insert Picklist fields with controlling field and controlling field values

It took me quite a time to figure picklist , controlling, dependent etc so . i though it would be helpful addition on your work

Here is the example for Creating picklist field , with controlling field , and controlling field values


  public static void createPicklistField()
    {
        MetadataService.MetadataPort service = createService();     
        MetadataService.CustomField customField = new MetadataService.CustomField();
            customField.fullName = 'lead.dependent_picklist__c';
            customField.label = 'Dependent Picklist';
            customField.type_x = 'Picklist';
            
        
        metadataservice.Picklist pt = new metadataservice.Picklist(); // creat picklist metadata
            pt.sorted= false;
            pt.controllingField = 'Controlling_Picklist__c'; // Define controlling field only name . not object name, only if you are creating Dependent field , else dont include line : if field dependency doesnot exist , it will create new one
        
        metadataservice.PicklistValue one = new metadataservice.PicklistValue(); // create picklist values metadata
            one.fullName= 'Dependent 0';
            one.default_x=false ;
            one.controllingFieldValues = new list <string> {'Control Odd number'};  // assign controlling field values
           
        metadataservice.PicklistValue two = new metadataservice.PicklistValue();
            two.fullName= 'Dependent 1';
            two.default_x=false ;
            two.controllingFieldValues = new list <string> {'Control Odd number','Control Even number'}; // assign controlling field values
            
        pt.picklistValues = new list<metadataservice.PicklistValue>{one,two}; // assign picklist values
            customField.picklist = pt ;                                       // assign Picklist
        MetadataService.AsyncResult[] results = service.create (new List<MetadataService.Metadata> { customField });
      
    } 

and here is the code to update picklist field


 

public static void UpdatePicklistField()
    {
         MetadataService.MetadataPort service = createService();
         MetadataService.CustomField customField = new MetadataService.CustomField(); 
            customField.fullName = 'lead.dependent_picklist__c';
            customField.label = 'Dependent Picklist';
            customField.type_x = 'Picklist'; 
            
        metadataservice.Picklist pt = new metadataservice.Picklist();
            pt.sorted= false;
            pt.controllingField= 'Controlling_Picklist__c'; //***** name of controlling field . if picklist has contrlloing field , this must be asssigned . else field dependency will be deleted
            
                metadataservice.PicklistValue first_dependent = new metadataservice.PicklistValue();
                 first_dependent.fullName= 'Dependent 2'; 
                 first_dependent.default_x=false ;
                 first_dependent.controllingFieldValues = new list <string>{'Control Even number'};  // list of names of controlling field Picklist value . dont put this line , if you dont want any controlling picklist value
           pt.picklistValues = new list<metadataservice.PicklistValue>{first_dependent};
         customField.picklist = pt ;
       
       
       MetadataService.UpdateMetadata ut = new MetadataService.UpdateMetadata();
            ut.currentName='lead.dependent_picklist__c';
            ut.metadata= customField;
       MetadataService.AsyncResult[] results = service.updateMetadata(new List<MetadataService.updateMetadata> {ut});
         
    }

Code to Create Button

I Want to Create a Button But I have got this exception "Save error: Initial expression is of incorrect type, expected: MetadataService.Metadata" . How Can i Resolve this?

Can't update manage package Page Layout

Hi. I'm trying to update Layout:

    MetadataService.MetadataPort service = new MetadataService.MetadataPort();
    service.SessionHeader = new MetadataService.SessionHeader_element();
    service.SessionHeader.sessionId = sessionId;
    service.endpoint_x = endpoint;

    MetadataService.Layout layout = 
        (MetadataService.Layout)service.readMetadata('Layout', 
            new String[] { 'CaAwsCloudTrailEvent__c-AWS CloudTrail Event Layout' }).getRecords()[0];

    System.debug(layout.fullName);

    handleSaveResults(
        service.updateMetadata(
            new MetadataService.Metadata[] { layout })[0]);        

    System.debug('DONE');

but getting error "Required field is missing: fullName", because retrieved field fullName is null. It is possible update MP page layout through metadata api? Thank you.

User with Api enabled gets logged off.

I have been trying to hit the metadata api by making a callout from Salesforce.com. I was successful in retrieving Validation rules/ List Views et al using JSZip and the metadata controller for the system Administrator.

However, when the User who has been "API enabled" but not a System Admin access it , he gets logged out when clicks on a button that internally makes a callout. Although, I am not making use of the exact same code, I am essentially trying to do the same thing. May be I am just missing something here, but I would be glad if you could replicate it? Am I missing something at the Profile level?

Merge is not handling the private sharing rules

Winning Record A ("Customer DM" recordtype) has sharing granted to a set of 5 roles
Losing Record B ("Customer CRM" recordtype) has sharing granted to a Role "Director de CSO" and a Public Group "CSO Back Office" as well and these two sharing settings are not present on Record A.
Upon Merge, we should assign the Sharing Settings on Losing Record B to the Winning Record A.
This way all users who had access to Record B, will have access on Merged Record A.

How can we achieve this, can we handle this case by providing extension to default feature.

Invalid Type

Hi

I'm getting error for the followed line

"public MetadataService.AsyncResult AsyncResult {get; private set;}"

It's giving me Invalid Type error for "MetadataService.AsyncResult

I have copied the page and Controller code to my eclipse and made two artifacts( page n contoller)

I have uploaded the the static resources provided in the src

Please guide me if I'm missing anything..!

Thanks in advance

How to display Dynamically coming multiselectpicklist Values as checkboxs?

Hi Andrew Fawcett,
Using metadata api i created multiselectpicklist.This created multiselectpicklist field dynamically I displayed on visualforce page(I was displayed all fields dynamically without using fieldset in an visualforce page).How to display comming Multiselectpicklist field values as checkboxes Dynamically in an visualforce page?

please help me....................

How to retrieve all custom objects related created dates within the pageblocktable?

Hi ,

Using schema methods and wrapper class I displayed all custom objects with in the pageblocktable one column.another column name is created dates(column name).How to retrieve all custom objects related created dates(column name) with in the pageblock table column(means created Dates column)?

Note:i posted lot of blogs no reply

help me..

How give Field accessable permission as Editable in pagelayouts Using metadata api?

Hi sir,
I try to Field accessable permission as Editable on pagelayout using following code.
But i got following error

public void updateFieldpageLayoutEdit()
{

       MetadataService.MetadataPort service = createService();

      List<MetadataService.Metadata> myCustomlayoutList = new List<MetadataService.Metadata>();
       // Read the Layout
    MetadataService.Layout layout =
    (MetadataService.Layout) service.readMetadata('Layout',
    new String[] { 'rajesh__+ strFieldName+__c-strFieldName Layout' }).getRecords()[0];

    // Here add your field by finding or adding the layout section and columns etc…
   MetadataService.LayoutItem LayoutItem = new MetadataService.LayoutItem();
    LayoutItem.field = 'rajesh__'+ strFieldName+'__c.'+'rajesh__'+Field2+'__c';
    // This code assumes the first section, first column of the layout
 layout.layoutSections[0]. layoutColumns[0].layoutItems.add(LayoutItem);

    // Update the Layout
    handleSaveResults(
    service.updateMetadata(
    new MetadataService.Metadata[] { layout })[0]);

}
But i got following error 

System.NullPointerException: Attempt to de-reference a null object
Error is in expression ‘{!createField}’ in component in page rajesh:createfields

Class.rajesh.MetadataController11.updateFieldpageLayout: line 882, column 1

line 882: layout.layoutSections[0]. layoutColumns[0].layoutItems.add(layoutItem);

Class.rajesh.MetadataController11.createField: line 243, column 1
line 243: updateFieldpageLayout();//i call above code using this method

help me …..

Can multiple retrieve request be combined in single zip/package.xml like IDE and ANT

Hi Andrew,

Greetings and much adulation for your work and your passion for APIs.

I have been following your GIt and trying to build a component which will allow taking Org backup of metadata. I have been able to do this for single metadata type but as per documentation "The queries array can contain up to three ListMetadataQuery queries for each call. "

This limitation if I understand correctly will not allow retrieving more than 3 metadata types per call.

So for this we will have to make successive calls and retrieve metadata but that will be in separate files and separate package.xml.

If IDE and ANT are also based on same API then how do they handle this kind of requests/limitation. Both of them provide single files for zip and packaga.xml.

Is this possible in APEX? to have the single file single package behavior as well?

Could it be like we have to use tooling and metadata api together at the same time to achieve this?

Thanks again for your time and guidance.

Web service callout failed

In a brand new org, all I did was to deploy this package and add a remove site as the self: in my case: https://c.na15.visual.force.com. I am able move around in all the other pages but when I visit metadatadata. I get the following error, what am I missing?

Visualforce Page: /apex/metadatadata

caused by: System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_TYPE: Unknown type: faultcode=sf:INVALID_TYPE faultactor=

Error is in expression '{!constructResponse}' in component apex:page in page metadatadata

Class.MetadataService.MetadataPort.listMetadata: line 1506, column 1
Class.MetadataDataController.constructResponse: line 58, column 1

Error when Adding CustomObject to list<Metadataservice.saveresult>

Hi, Thank you for a such a great post.

Facing an issue At this point

MetadataService.SaveResult [] results =
service.createMetadata(
new MetadataService.Metadata[] { customObject });

The Error is : Compile Error: Initial expression is of incorrect type, expected: MetadataService.Metadata

This is how i declared Sobject type
MetadataService.CustomObject customObject = new MetadataService.CustomObject();
Kindly help me resolve this.

How to schedule my batch class based on frequency Dynamically?

Hi Andrew Fawcett,
I have one frequency picklist field.I this picklist field values are Weekly,Monthly by day,Monthly by date and custom.When i select Weekly picklist value page rendered as Sunday,Monday.......Saturday checkboxes will be displayed.When i select Monthly by day picklist value page rendered as two picklists one is 1st,2nd,3rd,4th and last ,second picklist as Sunday,Monday.......Saturday will be displayed.When i select Monthly by date picklist value page rendered as picklist as 1st,2nd,3rd,4th........31st and last will be displayed.When i select Custom value in picklist page rendered as DayOfMonth(Textbox),Month:(Textbox),DayOfWeek:(Textbox),Year:(Textbox) .I gave Job name ,Startdate,Enddate and PreferredStartTime field as Hours(12AM,1AM....11PM),Minuts(00,01,02....59) and seconds(00,01,02....59).

NOTE:Above UI I designed how to perform backend operation based on my UI.

How to add Frequency as CRON Expresson Dynamically From visualforce page?

please help me..............

Error when deploying

Hi Andy, I'm getting the following error when deploying to my dev org (I used your button/ heroku app):

classes/MetadataServiceTest.cls(76,9):Method does not exist or incorrect signature: Test.setMock(Type, MetadataServiceTest.WebServiceMockImpl)

Updating Picklist with controlling field and controlling value

Hi , i been working on creating picklist , updating and assign to controlling field
and i came across an issues . that might interest you .

so ..

  1. I can Create new picklist field via this method :
  public static void createPicklistField()
{
    MetadataService.MetadataPort service = createService();     
    MetadataService.CustomField customField = new MetadataService.CustomField();
    customField.fullName = 'lead.picklist__c';
    customField.label = 'picklist';
    customField.type_x = 'Picklist';

    metadataservice.Picklist pt = new metadataservice.Picklist();
    pt.sorted= false;

    metadataservice.PicklistValue one = new metadataservice.PicklistValue();
    one.fullName= 'first'; 
    one.default_x=false ;

    pt.picklistValues = new list<metadataservice.PicklistValue>{one};
    customField.picklist = pt ;
    MetadataService.AsyncResult[] results = service.create (new List<MetadataService.Metadata> { customField });


}
  1. I can update / add new values via :
public static void UpdatePicklistField()
{
    MetadataService.MetadataPort service = createService();     
    MetadataService.CustomField customField = new MetadataService.CustomField();
    customField.fullName = 'lead.picklist__c';
    customField.label = 'picklist';
    customField.type_x = 'Picklist';


    metadataservice.Picklist pt = new metadataservice.Picklist();
    pt.sorted= false;
      metadataservice.PicklistValue two = new metadataservice.PicklistValue();
        two.fullName= 'second';
        two.default_x=false ;

        metadataservice.PicklistValue three = new metadataservice.PicklistValue();
        three.fullName= 'third';
        three.default_x=false ;
    pt.picklistValues = new list<metadataservice.PicklistValue>{two,three};
    customField.picklist = pt ;

    MetadataService.UpdateMetadata ut = new MetadataService.UpdateMetadata();
    ut.currentName='lead.picklist__c';
    ut.metadata= customField;

    MetadataService.AsyncResult[] results = service.updateMetadata(new List<MetadataService.updateMetadata> {ut});


}
  1. Now issues arises when i decided to add values in any depend picklist field :
    suppose there is a relation : controlling field : picklist..c : values : first, second, third
    and then dependent picklist : dependent_picklist..c , values : -none-

and now i write code to insert new value: "first_dependent" in dependent picklist

code is saving and running fine

  public static void update_dependent_PicklistField()
{
    MetadataService.MetadataPort service = createService();     
    MetadataService.CustomField customField = new MetadataService.CustomField();
    customField.fullName = 'lead.dependent_picklist__c';
    customField.label = 'dependent_picklist';
    customField.type_x = 'Picklist';

    metadataservice.Picklist pt = new metadataservice.Picklist();
    pt.sorted= false;
    pt.controllingField= 'lead.picklist__c';
       metadataservice.PicklistValue first_dependent = new metadataservice.PicklistValue();
         first_dependent.fullName= 'first_dependent'; 
         first_dependent.default_x=false ;
         first_dependent.controllingFieldValues = new list <string>{'first'};
     pt.picklistValues = new list<metadataservice.PicklistValue>{first_dependent};
     customField.picklist = pt ;


     MetadataService.UpdateMetadata ut = new MetadataService.UpdateMetadata();
    ut.currentName='lead.picklist1__c';
    ut.metadata= customField;
   MetadataService.AsyncResult[] results = service.updateMetadata(new List<MetadataService.updateMetadata> {ut});

}

But it WONT INSERT any value in dependent picklist cause
: its sending update metadata as follows :

Please do let me know your thoughts on this

OAuth-ready ?

Hi Andy,
I explored adding OAuth compatibility : getting an OAuth token is easy enough, as well as initialising the InputHttpHeader on the MetadataService.
However, for some reason, WebServiceCallout.invoke insists on using the SessionId in the SessionHeader : have you any reason why ?

Any other idea about making apex-mdapi OAuth-compatible ?

Regards,
Rupert

workflow elements do not extend metadata class

Hi,
I am trying to create "workflow" metadata via the wrapper. I'm having trouble adding the "fullName" attribute to the parent workflow and its child elements

code like this:
((MetadataService.metadata)myWorkflow).fullName = source.subject;
produces this error:
Error: Compile Error: Incompatible types since an instance of MetadataService.Workflow is never an instance of MetadataService.Metadata at line xyz

The attempt to create workflow fails with a similar type error.
MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> { myWorkflow});

that line fails with an error saying that the method is expecting a metadata object.

Creating Triggers

Hi Andrew

Hope you are well, and I hope I'm not overstepping the boundaries by asking for some advice here.

Please could you help a guy out? I've been searching everywhere for an answer to this and am going out of my mind.

I can't find a way to programmatically create new ApexTriggers using any of the available Salesforce APIs. The closest I've gotten is using the tooling API, but that always throws an error at me:

http://salesforce.stackexchange.com/questions/14352/how-can-i-create-a-new-apex-trigger-using-the-tooling-api

My question is: how do you people normally create an ApexTrigger programmatically via the APIs. I can handle ApexClasses and Pages, but all my searching returns people asking the same question but getting no answer.

Any help with this would be greatly appreciated :)

Thanks for your time
Tom

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.