Coder Social home page Coder Social logo

custommetadataloader's Introduction

Using CLI Commands

Salesforce CLI commands for custom metadata types are available in v49. The custom metadata loader is no longer supported or maintained. As such, Salesforce does not guarantee the functionality or performance of the loader.

The CLI commands simplify development and help you build automation and synchronize your source from scratch orgs when working with custom metadata types. CLI commands offer more functionality than the custom metadata loader. You can create custom metadata types, generate fields, create records, bulk insert records from a CSV file, and generate custom metadata types from an sObject. In addition, there's no limit on the number of records that can be loaded.

See the following for more information:

Custom Metadata Loader

Deploy to Salesforce

v 3.0 Custom Metadata tool now supports migration of Custom Settings or Custom Objects to Custom Metadata Types along with migration of records. If you already have Custom Metadata Type, then it can just migrate the Custom Settings/Custom Objects records.

v 2.0 The Custom Metadata loader tool now supports updates of existing custom metadata records. Load the csv file with updates to existing records, and use the tool the import and update the records.

How to use custom metadata loader to update existing records

  1. Please follow the instructions below to first load/create the records for the custom metadata type.
  2. Now create a csv file with record values you want to update
  3. Now select the CSV file and the corresponding custom metadata type.
  4. Click 'Create/Update custom metadata' to bulk update the records from the CSV file into your org.

v 1.0 Custom metadata loader is a tool for creating custom metadata records from a csv file. Create custom metadata types in your Salesforce org using Metadata API and then use custom metadata loader to bulk load the records. Behind the scenes, custom metadata loader uses Metadata API to bulk load up to 200 records with a single call.

Custom metadata loader has a sample custom metadata type CountryMapping__mdt that allows users to map country codes to country names.

How to deploy custom metadata loader

  1. Download the folder custom_md_loader and zip all the files inside this folder. Package.xml should be at the top level of the zipped file.
  2. Log in to your developer organization via workbench and deploy this zip file. (migration -> deploy)

How to use custom metadata loader

  1. Once you have deployed custom metadata loader in your org, assign the permission set 'Custom Metadata Loader' to the users who need to use the tool(See Step 2, 3 on how to assign the perm set) These users also need the 'Customize Application' to create Custom Metadata records. Admin should have this permission by default.
  2. To apply the permission set - CustomMetadataLoader to the user who is using the tool. Go to Administer->Manage Users ->Permission Sets. Click on Custom Metadata Loader. 3 You will be taken to Permission Set page - Click on Manage Assignments. Then click Add Assignments. Choose the user/users. Then click Assign. Then Done. Now the perm set should be successfully assigned.
  3. Create a CSV file with a header that contains the field API names, including the org namespace. Either Label or Developer Name is required. A sample csv for CountryMapping__mdt is in the same folder as this README file.
  4. Next you are ready to use the tool - Select Custom Metadata Loader from the app menu in your org, then go to the Custom Metadata Loader tab.The app will prompt you to create a remote site setting if it is missing.
  5. Select the CSV file and the corresponding custom metadata type.
  6. Click 'Create/Update custom metadata' to bulk load the records from the CSV file into your org.

How to use custom metadata migrator

Use one of the below option to migrate Custom Settings or Custom Objects to Custom Metadata Types. Go to the 'Custom Metadata Migrator' tab

Option 1: Migrate Custom Settings/Custom Objects to new Custom Metadata Type

Input the following:

--Api name of Custom Setting or Custom Object (e.g. VAT_Settings_CS__c)
--Api name of Custom Metadata Types (e.g. VAT_Settings__mdt)

Click on 'Migrate'

Option 2: Migrate Custom Settings/Custom Objects to existing Custom Metadata Type

Input the following:

--Api name of Custom Setting (e.g. VAT_Settings_CS__c)
--Select the name of existing Custom Metadata Types

Click on 'Migrate'

Option 3: Migrate Custom Settings/Custom Objects to existing Custom Metadata Type (using simple mapping)

Input the following:

--Api name of Custom Setting.fieldName (e.g. VAT_Settings_CS__c.Active__c)
--Api name of Custom Metadata Types.fieldName (e.g. VAT_Settings__mdt.Active__c)

Click on 'Migrate'

Option 4: Migrate Custom Settings/Custom Objects to existing Custom Metadata Type (using custom mapping)

Input the following:

--Api Name of Custom Setting (e.g. VAT_Settings_CS__c)
--Api Name of Custom Metadata Types (e.g. VAT_Settings__mdt)
--Json Mapping (Sample below)
{
	"Active__c" : "IsActive__c",
	"Timeout__c" : "GlobalTimeout__c",
}
Please note, key should be the Custom Setting/Object field name and that the value is the CMT field name.

Click on 'Migrate'

Custom metadata migrator: more details

  1. Custom metadata migrator provides two different options to do the migration:

    • Sync Operation: Migration will happen synchronously. Maximum 200 records can be migrated.
    • Async Operation: Migration will happen asynchronously. Maximum 50000 records can be migrated. To check the status of async migration, go to Deploy -> Deployment Status
  2. Custom Metadata Types label and names

    • Custom Setting/Custom Object record name converted into Custom Metadata Types label and name.
    • Custom Setting name special character replaced with "_" in Custom Metadata Type names
    • If Custom Setting name starts with digit, then Custom Metadata Types name will be prepended with "X"
  3. Custom Settings of type hierarchy not supported.

  4. Custom Objects with field types not supported in Custom Metadata Types not supported.

  5. Currency field on Custom Settings can't be migrated, you can use custom mapping to either avoid mapping or to map to another field.

custommetadataloader's People

Contributors

amarkulkarni-rc avatar anoop-76 avatar aroyfaderman avatar carolyng avatar fishofprey avatar iamthefbi avatar jamesmelville avatar jefersonchaves avatar rodion-r avatar soleger avatar sricharananand avatar svc-scm 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

custommetadataloader's Issues

"Attempt to de-reference a null object" - Error Upon Insert of New Custom Metadata

I tried using v2.0 with a CSV file, but still I am receiving below error message:

System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!upsertCustomMetadata}' in component apex:commandButton in page custommetadatarecorduploader: Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

How can I uninstall?

I installed and used the package...it worked great! Now I'd like to uninstall it. How do I go about doing that please.

Remove from ORG

Hello, how do I uninstall this from our Production ORG? Are there steps that have automated the removal of the tool? Thank you.

Error loading CustomMetadata records with null values for Number fields

Error Message detail

Web service callout failed: WebService returned a SOAP Fault: '' is not valid for the type xsd:double faultcode=soapenv:Client faultactor=
El error está en la expresión '{!upsertCustomMetadata}' del componente apex:commandButton en page custommetadatarecorduploader: Class.MetadataService.MetadataPort.upsertMetadata: line 9261, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 131, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 97, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 127, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Empty value issue

My CSV file looks like

DeveloperName,Level__c,Containing_Node_Label__c,Type__c,FieldA__c,FieldB__c,FieldC__c
OpportunityStage,0,,Field,,StageName,
Contacts,0,,List,Contacts_In_Opportunity__r,,

When I try upload, I'm getting this error:
Error occured processing component <CUSTOM_METADATA_TYPE_NAME>.OpportunityStage. Type: bad value for restricted picklist field: StageName (INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST). Fields Type__c.

It seems, that the tool skips empty values: ,, and ,

Does not Support UTF-8 characters

I see that the Custom MetaData loader does not support uploading a file with special characters (such as á, ã, ä, ç, é, í, ó, ö, ô, ú). I got the following error message: "An error has occurred while importing data. Please make sure input csv file is correct. BLOB is not a valid UTF-8 string".
I tried saving the file as UTF-8 encoding and still it is not being supported. I got the following error message "Header must contain at least one of these two fields - DeveloperName, Label."(The message is not accurate either because I removed the special character lines and I'm able to upload the file).
Please let me know if you have a solution/workaround.
Thanks for your help!!

Added new field to Custom MDT, Loader does not recognize new field

I previously utilized Custom Metadata Loader to populate some MDT records. Since that time, I have added new fields to the Custom Metadata Type, and when I try to load more MDT records into this same Custom Metadata Type (including data in the new field), I get an error that looks like this:

Header must contain the api names of the fields. Fields allowed for this type: (DeveloperName, Label, Description, Old_Field_1__c, Old_Field_2__c, Old_Field_3__c, ...) Fields in file header: {Old_Field_1__c, **NEW_FIELD__c**, Old_Field_2__c, Old_Field__c, Label, DeveloperName}

It's as if the Custom Metadata Loader introspected the fields of the Custom Metadata Type the first time it was run and cached those fields as opposed to introspecting the fields every time the Loader is run... Is there any special command that I need to run to get the Custom Metadata Loader to recognize the new fields on the Custom Metadata Type?

Error in uploading CSV file

Hi All,

Please help me to resolve the below issue when inserting a CSV file with three fields.

custom metadata
metadata222

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: Must specify the name in the CustomMetadataType.CustomMetadata format, Current Name: CountryMapping., Required Delimiter: . faultcode=soapenv:Client faultactor=
Error is in expression '{!upsertCustomMetadata}' in component apex:commandButton in page custommetadatarecorduploader: Class.MetadataService.MetadataPort.upsertMetadata: line 9261, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 158, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 124, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Class.MetadataService.MetadataPort.upsertMetadata: line 9261, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 158, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 124, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Create Remote Site Setting Bug

Installed this in a sandbox, and then in a dev org.
Step 1 after assigning the app permission set is to create a remote site with the button.
Fails with message:
"Cannot create a new component with the namespace: . Only
components in the same namespace as the organization can be created through the API"

Really a bummer as this tool was going to be a huge time saver.

Thanks for looking at it.

Updates of Boolean Fields Do Not Work

Updates to Boolean Subscriber Editable fields do not work. If field starts as False, or '0', changing value to '1' or 'True' using Custom Metadata Loader does not change the value of the Boolean field.

Regex too complicated

I am trying to upload a file that contains a mapping of SFDC ID's.

 DeveloperName,Label,Legacy_ID__c,Current_ID__c
 kA780000000CaRCCA0,kA780000000CaRCCA0,kA780000000CaRCCA0,kA30t0000004CuBCAU
 kA780000000CaRMCA0,kA780000000CaRMCA0,kA780000000CaRMCA0,kA30t0000004DfPCAU

When I upload this file I get the following error:

 Regex too complicated
 Error is in expression '{!upsertCustomMetadata}' in component <apex:commandButton> in page custommetadatarecorduploader: Class.CSVFileUtil.parseCSV: line 27, column 1
 Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 92, column 1
 Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

I looked at the relevant line in CSVFileUtil and my file does not contain any double quotes or the substring DBLQT.

Issue on Click of "Create Remote Site Setting"

On Click of "Create Remote Site Setting" from the tab "Custom Metadata Loader", below error shows up

Cannot create a new component with the namespace: laxmanvattam_dev_ed. Only components in the same namespace as the organization can be created through the API

How to overcome this issue?

Cannot get the sample to work

When I try to load the sample the following error occurs
Attempt to de-reference a null object
Error is in expression '{!upsertCustomMetadata}' in component apex:commandButton in page custommetadatarecorduploader: Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1
Could someone please help me out?
We want to move some of our custom objects to custom metadata but without a good way to migrate them it will be very difficult.

Cannot create a new component with the namespace: myNameSpace. Only components in the same namespace as the organization can be created through the API

Hello, installed this app via deploy button into my sandbox, now getting this when attempting to create Remote Site Setting via button on the app:
Cannot create a new component with the namespace: myNameSpace. Only components in the same namespace as the organization can be created through the API

Can we get instructions on how this can be created manually? or I have to reverse engineer VF page? :)

Error importing sample: "BLOB is not a valid UTF-8 string"

When I try to upload even the sample CSV I get this error message:

Error:
An error has occured while importin data. Please make sure input csv file is correct
BLOB is not a valid UTF-8 string
null

How do I resolve this? Perhaps this has something to do with the namespace, which is blank/null on the sample and my custom CMT object?

Invalid Cross Reference Key

I'm trying to import data that has a lookup to another Metadata type.
I am getting the error.

Error occured processing component ChildObject.NameOfRecord. In field: ParentObject__c - no CustomMetadata named ParentObject.Name found (INVALID_CROSS_REFERENCE_KEY).

The importer requires ParentObject__c to be there, and I've set the ID of the Parent Object as the value in the column ParentObject__c, but that's causing the error.

How do I import child CMDT object records?

"Attempt to de-reference a null object" error in CustomMetadataUploadControllerTest

Hi there,

We deployed this today on our Sandbox and this worked great, but when we tried to deploy it to our Production instance we noticed that the CustomMetadataUploadControllerTest was failing. Here's the error log.

Class
CustomMetadataUploadControllerTest
Method Name
testCreateCustomMetadataWithDevName
Error Message
System.NullPointerException: Attempt to de-reference a null object
Stack Trace
Class.MetadataService.MetadataPort.upsertMetadata: line 9274, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 131, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 97, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 127, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1
Class.CustomMetadataUploadControllerTest.testCreateCustomMetadataWithDevName: line 54, column 1

Class
CustomMetadataUploadControllerTest
Method Name
testCreateCustomMetadata
Error Message
System.NullPointerException: Attempt to de-reference a null object
Stack Trace
Class.MetadataService.MetadataPort.upsertMetadata: line 9274, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 131, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 97, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 127, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1
Class.CustomMetadataUploadControllerTest.testCreateCustomMetadata: line 44, column 1

Any ideas what's causing this? It's hard to tell when deploying external code if it's a problem on your end or ours.

We added a Remote Site Setting in advance of the Production deployment in the event that was the cause, but it doesn't seem to have addressed the issue.

Migrate data with comma and new lines

Hi,

I want to migrate DLRS records into the metadata. So I have exported dlrs records data from Salesforce and trying to migrate data into the custom metadata type. I have installed this tool and successfully migrated few records. But the tool is giving an error while loading data having comma or data with new lines. Please refer the data in Column G and H in attached file.
Any suggestions?

DLRS

Header must contain the api names of the fields

screen shot 2018-02-23 at 16 08 29
I'm trying to upload Custom Metadata Type records to Nation__mdt. I've matched up my fields as required but I'm encountering an error "Header must contain the api names of the fields. "

As you can see from the screenshot, the expected headers and the returned headers are the same but in a different order (despite the order I set the headers in my csv). Any help would be appreciated.

Error when creating Remote Site Setting

Error: Only components in the same namespace as the organization can be created through the API.
We have a custom "My Domain" set up.

Looked for details on how to create this manually but couldn't find any. Could you provide.

Funny thing is I am actually creating a Country Code lookup which was interestingly your sample.

Does not Support HTML tag in content

When there is content with HTML tags to be inserted into a Custom Metadata field, it shows an error The number of field values does not match the number of header fields on line4. Anybody faced the same issue before?

IO error on the Custom Metadata Loader page

I've uploaded a bunch of records (which was painful enough in and of itself)...

Now When I go to add more, I get this:

IO Exception: Exceeded max size limit of 6000000
Error is in expression '{!checkMdApi}' in component apex:page in page custommetadataloader: Class.MetadataService.MetadataPort.listMetadata: line 9218, column 1
Class.MetadataUtil.checkMetadataAPIConnection: line 30, column 1
Class.CustomMetadataLoaderController.checkMdApi: line 16, column 1

An unexpected error has occurred. Your development organization has been notified.

Error Deploying CustomMetadataLoader Into Production

System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1 Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1 Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1 Class.CustomMetadataUploadControllerTest.testCreateCustomMetadataWithDevName: line 54, column 1

Failure in deploying CustomMetadataLoader in a Sandbox

classes/AppConstants.cls(AppConstants):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/CustomMetadataUploadController.cls(CustomMetadataUploadController):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/CustomMetadataUploadControllerTest.cls(CustomMetadataUploadControllerTest):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/MDWrapperWebServiceMock.cls(MDWrapperWebServiceMock):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/CustomMetadataLoaderControllerTest.cls(CustomMetadataLoaderControllerTest):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/CustomMetadataLoaderController.cls(CustomMetadataLoaderController):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/CSVFileUtil.cls(CSVFileUtil):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/MetadataService.cls(MetadataService):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/MetadataUtil.cls(MetadataUtil):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000
classes/MetadataServiceTest.cls(MetadataServiceTest):The total size of apex code in this application after removing comments exceeds the maxiumum character size of 5000000

Not able to upload CSV for Unmanaged Org

Web service callout failed: WebService returned a SOAP Fault: Unknown SObject Namespace for Metadata Error Id: 144931985-272582 (-768177128) faultcode=soapenv:Server faultactor=
Error is in expression '{!upsertCustomMetadata}' in component apex:commandButton in page goc:custommetadatarecorduploader: Class.goc.MetadataService.MetadataPort.upsertMetadata: line 9261, column 1
Class.goc.MetadataUtil.upsertMetadataAndValidate: line 131, column 1
Class.goc.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 97, column 1
Class.goc.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 127, column 1
Class.goc.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Error Deploying CustomMetadataLoader Into Production

Got below today.

Deployment CompleteTest failure, method: CustomMetadataUploadControllerTest.testCreateCustomMetadataWithDevName -- System.NullPointerException: Attempt to de-reference a null object stack Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1
Class.CustomMetadataUploadControllerTest.testCreateCustomMetadataWithDevName: line 54, column 1

Test failure, method: CustomMetadataUploadControllerTest.testCreateCustomMetadata -- System.NullPointerException: Attempt to de-reference a null object stack Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1
Class.CustomMetadataUploadControllerTest.testCreateCustomMetadata: line 44, column 1

CSV file upload in visualforce page

Hi Team,

Please could help me out for CSV File upload

I have Writing code it's working fine.
but i have want to use custom setting get the values in map

if you go through code
String Oppid = inputvalues[1].trim(); // this is hard code values i am pass

I need to pass csv file sheet values in custom setting and custom setting values in code

/********************************************************************************************************
// Name : BulkFeasibilityFileUploader.cls
// Description : Class to Read CSV File & insert Data On Request, Task & Response.
// Created By : Harsha Naik, TCS
// Created Date : 04 May 2017

public with sharing class BundleFeasibilityController {

    public string csvFileName{get;set;} // To Capture uploaded file
    public transient Blob contentFile{get;set;} // To Capture body of the file
    transient public String[] filelines = new String[]{};// To Capture he no. of lines in the file
    public Boolean successFlag{get;set;} //check it boolean flag
    public string Labelvalue{get;set;} // to check the customlabel values
    public String fileExtention = '.csv';  // To check the correct file extention
   
    

    public list<string>opptyIdList =new list<string>(); // to capture column values in list 
    public list<string>prodtypeList =new list<string>();// to capture column values in list
    public list<String>cityList = new List<String>(); // to capture column values in list
    public list<string>networkSolCktList =new list<string>(); // to capture column values in list
    public list<string>CustomerSiteList =new list<string>(); // to capture column values in list
    public List<Database.SaveResult> saveResult = new List<Database.SaveResult>(); // To capture Insert  Result for Request/Task/Respone.

    public Map<String,id> opptyIdProdTypeMap =new Map<String,id>(); //to capture column values in Map
    public Map<String,id> cityMap =new Map<String,id>(); //to capture column values in Map
    public Map<String,id> networkSolCktMap =new Map<String,id>(); //to capture column values in Map
    public Map<String,id> CustomerSiteMap =new Map<String,id>();  //to capture column values in Map 
    public Map<string,id> Opportunitymap = New Map<string,id>();  //to capture column values in Map

    
   public List<Case> successcaseList {get;set;} // Query the list case object
   public List<Case> caseList = new List<Case>(); // case object 
   public List<Feasibility_Task__c> FeasibilityTasklist1 =new List<Feasibility_Task__c>(); // Feasibility_Task__c object
   public list<Feasibility_Response_A__c> FeasibilityResponselist =new list<Feasibility_Response_A__c>(); // Feasibility_Response_A__c object
    
    public List<Id> fReqIdList = new List<Id>(); //To capture the Case Ids of  successfully inserted
    public list<id> fReqIdListerror =new list<id>(); //To capture the ID of failures 
    public list<id> FeasibilityTaskId =new list<id>();  //To capture the  Feasibility_Task__c Ids of successfully inserted
    public list<id> FeasibilityResponseId =new list<id>();//To capture the Feasibility_Response_A__c Ids of successfully inserted
    public list<id> caseid =new list<id>();

    /* siteloaction list */
    //public list<string> newjoin =new list<string>(); // to capture
    public List<Site_Location_ID__c> siteObjListresult = new List<Site_Location_ID__c>(); //  Query the list Site_Location_ID__c  object 
    public List<Site_Location_ID__c> siteObjList = new List<Site_Location_ID__c>(); // to capture list values in Site_Location_ID__c



public BundleFeasibilityController(){
 //successFlag=true;

}
Public BundleFeasibilityController (ApexPages.StandardController controller) {
     //this.successcaseList= new List<Case>();
    successFlag = false;
}

public Pagereference ReadFile() {  
Id devRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Default Feasibility Request').getRecordTypeId();   
  /*
   if(test.isRunningTest())
   {
       csvFileName='testharshanaiktest.csv';
       string str = 'Sr.no,Opportunity ID,Product Name,Ckt ServiceID ,Customer Site ID ,Network Solution Circuit ID,Continent(A-End),Country (A-End) ,State (A-End),City (A End),Pin/Zip (A-End),ADDRESS LINE1(A-End),ADDRESS LINE2(A-End) ,ADDRESS LINE3 (A-End),Floor(A-End) ,Room(A-End) ,Rack(A-End) ,Continent(B-End) ,Country (B-End),State (B-End) ,City (B End) ,Pin/Zip (B-End) ,ADDRESS LINE1(B-End) ,ADDRESS LINE2(B-End) ,ADDRESS LINE3(B-End) ,Floor(B-End) ,Rack(B-End) ,Room(B-End) \r\n ';
       str = str +' 1,1758856,Hub - Global Dedicated Ethernet,12222,2222,,Asia,India,Maharashtra,Pune,400079,addresss1,Address1,addresss1,4th ,301,2221,Asia,India,Maharashtra,Pune,400079,addresss1,Address1,addresss1,4th,301,2221'; 
       contentfile = blob.valueof(str);
       
   }
  */
    System.debug('pkp csvFileName :'+ csvFileName);
   if(csvFileName !=null){
       if(csvFileName.subString(csvFileName.length() - 4, csvFileName.length()).equals(fileExtention)){
       
                          
           // csvFileName = blobToString( contentFile,'ISO-8859-1');
            csvFileName=contentFile.toString();
                system.debug('csvFileName.length()' +csvFileName.length());
                if(csvFileName.length() >30000) {
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File size is too large.Please reduce number of records in the file and try again');
                    ApexPages.addMessage(errormsg);
                    return null;
                } 
               
             system.debug('pkp csvFileName :::: '+csvFileName)  ; 
             filelines = csvFileName.split('\n');
                system.debug('filelines' + filelines.size());
                if(filelines.size() > 25) {
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Upto 25 activities are loaded at a time');
                ApexPages.addMessage(errormsg);
                return null;
                }
               system.debug('pkp1 filelines :::: '+filelines)  ;
               //.replaceAll(',(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)','&COMMA')
               
           system.debug('pkp2 filelines :::: '+filelines.size() + filelines )  ;
           //integer fileSize = filelines.size();
           //if(Test.isrunningTest()){fileSize = fileSize +1;}
                For (Integer i=1;i<filelines.size();i++)
                {
                    System.debug('pkp filelines :::'+filelines);
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                    String Oppid = inputvalues[1].trim();
                    system.debug('Oppid' + oppid);
                    String Prodtyp = inputvalues[2].trim();
                    system.debug('Prodtyp ' + Prodtyp );
                    String CustomerSiteID = inputvalues[4].trim();
                    String netSolCktId = inputvalues[5].trim();
                    String city=inputvalues[9].trim();
                    opptyIdList.add(Oppid);
                    system.debug('opptyIdList' + opptyIdList);
                    prodtypeList.add(Prodtyp);
                    system.debug('prodtypeList' + prodtypeList);  
                    CustomerSiteList.add(CustomerSiteID);
                    system.debug('CustomerSiteList'  + CustomerSiteList); 
                    networkSolCktList.add(netSolCktId);
                    system.debug('networkSolCktList'  + networkSolCktList);               
                    cityList.add(city); 
                    system.debug('cityList' + cityList);
                    //StateList.add(State);
                   // opptyIdCustSiteIdMap.put(Oppid,CustomerSiteID);
                    
                    

                }  
                if(opptyIdList!=null && !opptyIdList.isEmpty() && prodtypeList!=null && !prodtypeList.isEmpty()) {

                            for(Products_Services__c pr:[Select Id,Opportunity_SFDC_ID__c,Name,Product_Type__c From Products_Services__c where Opportunity_SFDC_ID__c IN:opptyIdList AND Product_Type__c IN:prodtypeList]){       
                            opptyIdProdTypeMap.put(pr.Opportunity_SFDC_ID__c+'_'+pr.Product_Type__c,pr.Id);      
                            System.debug('opptyIdProdTypeMap::'  + opptyIdProdTypeMap);
                        }

                }
                if(opptyIdList!=null && !opptyIdList.isEmpty()){
                        
                    for(Opportunity opp:[Select Id,AccountId,CurrencyISOCODE,Name,Opportunity_ID__c, is_partner_Order__c,Account.Profile__c from Opportunity where Opportunity_ID__c IN:opptyIdList]){
                                       Opportunitymap.put(opp.Opportunity_ID__c,opp.AccountId);
                                       System.debug('Opportunitymap::'+ Opportunitymap);
                                       
                                  }
                            
                }
                if(cityList!=null && !cityList.isEmpty()){
                    
                        for(CityStateCountryMD__c city:[Select Id,Name,State__c from CityStateCountryMD__c where Name in:cityList]){ 
                           
                                    cityMap.put(city.Name,city.Id);   
                                    System.debug('cityMap1' + cityMap); 
                                               
                        }
                        
                }
                set<Site_Location_ID__c> allstring =new set<Site_Location_ID__c>();
                  list<string> siteObjList1 =new list<string>();
                 list<string>siteObjList2 =new list<string>();
                 set<string>sitcollectList =new set<string>();
                 List<String> listUnion = new List<String>();
                if(CustomerSiteList!=null && !CustomerSiteList.isEmpty()){

                        for(Site_Location_ID__c SiteLocationID:[Select Id,Account__c,Customer_SITE_Reference__c , Site_ID__c FROM Site_Location_ID__c where Customer_SITE_Reference__c IN:CustomerSiteList]){      
                            CustomerSiteMap.put(SiteLocationID.Customer_SITE_Reference__c,SiteLocationID.Id);
                             system.debug('CustomerSiteMap1::' + CustomerSiteMap ); 
                              siteObjList1.add(SiteLocationID.id);  
                              system.debug('siteObjList1'+ siteObjList1);
                             
                           
                        }
                    for(integer j=1;j<filelines.size();j++){
                            system.debug('sit working2');
                            string[] sitObjectvalues1=filelines[j].replaceAll(',(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)','&COMMA').split(',');                        
                            String s = sitObjectvalues1[4].trim(); 
                            
                            if(!CustomerSiteMap.containskey(s)) {                                             
                                    Site_Location_ID__c siteObj = new Site_Location_ID__c();
                                    siteObj.Account__c=Opportunitymap.get(sitObjectvalues1[1].trim());
                                    system.debug('siteObj.Account__c ::' +siteObj.Account__c);
                                    siteObj.Customer_SITE_Reference__c = sitObjectvalues1[4].trim();
                                    siteObj.Region__c = sitObjectvalues1[8];
                                    siteObj.City__c=cityMap.get(sitObjectvalues1[9].trim());
                                    siteObj.ZIP_Code__c=sitObjectvalues1[10];
                                    siteObj.Address_Line_1__c=sitObjectvalues1[11];
                                    siteObj.Address_Line_2__c= sitObjectvalues1[12];
                                    siteObj.Address_Line_3__c= sitObjectvalues1[13];
                                    siteObj.Floor__c = sitObjectvalues1[14];
                                    siteObj.Room__c = sitObjectvalues1[15];
                                    siteObj.Rack__c = sitObjectvalues1[16];  
                                    siteObj.Site_Description__c='Site Creation'; 
                                    siteObj.Site_Status__c='Active';
                                    siteObjList.add(siteObj);
                                    system.debug('siteObjList::' + siteObjList);
                                     
                                    }
                                 
                                }            
                      
                     if(siteObjList!=null && !siteObjList.isEmpty()){
                            saveResult = database.insert(siteObjList,true); 
                        }
                            for(Database.SaveResult srObj:saveResult){   
                                    if (srObj.isSuccess()){
                                        fReqIdList.add(srObj.getId());
                                        system.debug('fReqIdList ::' +fReqIdList);
                                    }
                                else{
                                    for(Database.Error err : srObj.getErrors()){
                                        //successFlag =true;
                                         If(!srObj.isSuccess()){
                                         fReqIdListerror.add(srObj.getId());
                                    
                                        }
                                        System.debug('The following error has occurred.');                    
                                        ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'  '+err.getMessage()+''+ err.getFields());
                                        ApexPages.addMessage(errormsg);
                                        return null;                        
                                    }
                                }
                         }                                    
                    siteObjListresult =[Select Id,Customer_SITE_Reference__c ,ZIP_Code__c,Region__c,City__c,Account__c,Site_Description__c,Site_ID__c FROM Site_Location_ID__c WHERE ID IN:fReqIdList];
                        for(Integer i=0; i<siteObjListresult.size(); i++) {
                                siteObjList2.add(siteObjListresult.get(i).Id);
                                system.debug('siteObjList2'+siteObjList2); 
                        } 
                Set<String> setUnion = new Set<String>();
                setUnion.addAll(siteObjList1);
                system.debug('siteObjList1' +siteObjList1);
                setUnion.addAll(siteObjList2);
                system.debug('siteObjList2' +siteObjList2);
                listUnion.addAll(setUnion);
                system.debug('listUnion' +listUnion);
                }
            
             if(networkSolCktList!=null && !networkSolCktList.isEmpty()){

                    for(Network_Solution_Circuit__c NetworkSolutionCircuit:[Select Id,Name from Network_Solution_Circuit__c where Name IN:networkSolCktList])
                    {      
                        networkSolCktMap.put(NetworkSolutionCircuit.Name,NetworkSolutionCircuit.Id);       
                        System.debug('networkSolCktMap::'  + networkSolCktMap);
                    }
                }
            
                For (Integer i=1;i<filelines.size();i++){ 
                    system.debug('pkp3 filelines :::: '+filelines.size())  ;
                            String[] valuesToInsert = new String[]{};
                            valuesToInsert = filelines[i].split(',');
                            Case feasibilityReq = new Case();
                            feasibilityReq.Products_Services__c = opptyIdProdTypeMap.get((valuesToInsert[1].trim()+'_'+valuesToInsert[2].trim()));                
                            system.debug('Inside Request'+opptyIdProdTypeMap.get((valuesToInsert[1].trim()+'_'+valuesToInsert[2].trim())));
                            feasibilityReq.Ckt_ServiceID__c = valuesToInsert[3];
                            feasibilityReq.Site_Location_ID_A_End__c =listUnion[0]; 
                            system.debug('feasibilityReq site' + feasibilityReq.Site_Location_ID_A_End__c);
                            feasibilityReq.Network_Solution_Circuit_ID__c = networkSolCktMap.get(valuesToInsert[5].trim());
                            system.debug('Network_Solution_Circuit_ID__c:: ' +feasibilityReq.Network_Solution_Circuit_ID__c );
                                                                                          
                            Labelvalue=System.Label.BundleFeasibilitycase.trim();
                            list<string>sheetValuelist =new list<string>();
                               String sheetValues = valuesToInsert[2].trim();
                               sheetValuelist.add(sheetValues);
                                 for(string s:sheetValuelist){
                                    if(Labelvalue.contains(s)){
                                           /* A-End Details */ 
                                feasibilityReq.Continent_A_End__c = valuesToInsert[6];
                                feasibilityReq.Country_A_End__c = valuesToInsert[7];
                                feasibilityReq.State_A_End__c = valuesToInsert[8].trim();
                                feasibilityReq.CityAEnd__c= cityMap.get(valuesToInsert[9].trim());
                                //feasibilityReq.CityAEnd__c= cityMap.get((valuesToInsert[8].trim()+'_'+valuesToInsert[9].trim()));
                                feasibilityReq.Pin_Zip_A_End__c = valuesToInsert[10];
                                feasibilityReq.ADDRESS_LINE1_A_End__c = valuesToInsert[11];
                                feasibilityReq.ADDRESS_LINE2_A_End__c = valuesToInsert[12];
                                feasibilityReq.ADDRESS_LINE3_A_End__c = valuesToInsert[13];
                                feasibilityReq.Floor__c = valuesToInsert[14];
                                feasibilityReq.Room__c = valuesToInsert[15];
                                feasibilityReq.Rack__c = valuesToInsert[16];                                    
                                /* B-End Details */ 
                                feasibilityReq.Continent_B_End__c = valuesToInsert[17];
                                feasibilityReq.Country_B_End__c = valuesToInsert[18];
                                feasibilityReq.State_B_End__c = valuesToInsert[19];
                                //feasibilityReq.CityBEnd__c= cityMap.get((valuesToInsert[19].trim()+'_'+valuesToInsert[20].trim()));
                                feasibilityReq.CityBEnd__c= cityMap.get(valuesToInsert[20].trim());
                                feasibilityReq.Pin_Zip_B_End__c= valuesToInsert[21];
                                feasibilityReq.ADDRESS_LINE1_B_End__c = valuesToInsert[22];
                                feasibilityReq.ADDRESS_LINE2_B_End__c = valuesToInsert[23];
                                feasibilityReq.ADDRESS_LINE3_B_End__c = valuesToInsert[24];
                                feasibilityReq.Floor_B_End__c = valuesToInsert[25];
                                feasibilityReq.Room_B_End__c = valuesToInsert[26];
                                feasibilityReq.Rack_B_End__c = valuesToInsert[27];
                              
                                system.debug('working fine');
                                                                                        
                               }
                               else{
                               
                                    /* A-End Details */
                                    feasibilityReq.Continent_A_End__c = valuesToInsert[6];
                                    feasibilityReq.Country_A_End__c = valuesToInsert[7];
                                    feasibilityReq.State_A_End__c = valuesToInsert[8].trim();
                                    //feasibilityReq.CityAEnd__c= cityMap.get((valuesToInsert[8].trim()+'_'+valuesToInsert[9].trim()));
                                    feasibilityReq.CityAEnd__c= cityMap.get(valuesToInsert[9].trim());
                                    feasibilityReq.Pin_Zip_A_End__c = valuesToInsert[10];
                                    feasibilityReq.ADDRESS_LINE1_A_End__c = valuesToInsert[11];
                                    feasibilityReq.ADDRESS_LINE2_A_End__c = valuesToInsert[12];
                                    feasibilityReq.ADDRESS_LINE3_A_End__c = valuesToInsert[13];
                                    feasibilityReq.Floor__c = valuesToInsert[14];
                                    feasibilityReq.Room__c = valuesToInsert[15];
                                    feasibilityReq.Rack__c = valuesToInsert[16];
                                    system.debug('not working fine');
                                      
                                     }
                                   
                              }                                      
                        
                    Bundle_Feasibility_values__c BFVcase = Bundle_Feasibility_values__c.getInstance('Bundle Values');                        
                        feasibilityReq.Recordtypeid=BFVcase.CaseRecordtype__c;
                        feasibilityReq.Interface__c=BFVcase.Interface__c;
                        feasibilityReq.Status=BFVcase.Status__c;
                        feasibilityReq.Port_Circuit_Capacity__c=BFVcase.Port_Circuit_Capacity__c;
                        feasibilityReq.Last_Mile_Contract_Term__c=BFVcase.Last_Mile_Contract_Term__c;
                        feasibilityReq.Other_POP_A_End__c=BFVcase.Other_POP_A_End__c;
                        feasibilityReq.SPECIAL_REQUIREMENTS__c=BFVcase.SPECIAL_REQUIREMENTS__c;
                        feasibilityReq.Available_Telecom_PRI_Provider_A_End__c=BFVcase.Available_Telecom_PRI_Provider_A_End__c;
                        feasibilityReq.Other_POP_B_End__c=BFVcase.Other_POP_B_End__c;
                        feasibilityReq.Available_Telecom_PRI_Provider_B_End__c=BFVcase.Available_Telecom_PRI_Provider_B_End__c;                              
                        feasibilityReq.Request_Type__c=BFVcase.Request_Type__c;
                        caseList.add(feasibilityReq);
                    }               
            
             if(caseList!=null && !caseList.isEmpty()){
                    saveResult = database.insert(caseList,False); 
                }
            if(saveResult != null && !saveResult.isEmpty()){
                    //successcaseList = new list<case>();

                        for(Database.SaveResult srObj:saveResult){   
                                if (srObj.isSuccess()){fReqIdList.add(srObj.getId());}
                            else{
                                for(Database.Error err : srObj.getErrors()){
                                        If(!srObj.isSuccess()){fReqIdListerror.add(srObj.getId());}
                                        
                                    System.debug('The following error has occurred.');                    
                                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'  '+err.getMessage()+''+ err.getFields());
                                    ApexPages.addMessage(errormsg);
                                    return null;                        
                                }
                            }
                        }
                  
                successcaseList = [SELECT id,Products_Services__c,Ckt_ServiceID__c, Status,Port_Circuit_Capacity__c,Continent_A_End__c,Country_A_End__c,State_A_End__c,CityAEnd__c,ADDRESS_LINE1_A_End__c,ADDRESS_LINE2_A_End__c,ADDRESS_LINE3_A_End__c,Pin_Zip_A_End__c,Available_Telecom_PRI_Provider_A_End__c,Floor__c FROM Case WHERE ID IN  :fReqIdList];
                  system.debug('successcaseList2' + successcaseList );
                   //Id ResponseId = Schema.SObjectType.Feasibility_Response_A__c.getRecordTypeInfosByName().get('Wireline - MAN/VBL').getRecordTypeId();
                           if(successcaseList != null && !successcaseList.isEmpty()){
                                         successFlag = true;
                                            system.debug('successfully insert');
                                        List<Feasibility_Task__c> FeasibilityTasklist= new list<Feasibility_Task__c>();
                                        
                                for(integer i=0;i<successcaseList.size();i++)
                                {
                                 Bundle_Feasibility_values__c BFVTask = Bundle_Feasibility_values__c.getInstance('Bundle Values'); 
                                    Feasibility_Task__c FeasibilityTask =new Feasibility_Task__c();
                                    FeasibilityTask.Feasibility_Request__c=successcaseList[i].id;
                                    FeasibilityTask.Subject__c =BFVTask.Subject__c;
                                    FeasibilityTask.Status__c =BFVTask.Status__c;
                                    FeasibilityTask.Overall_Feasibility_Status__c =BFVTask.Overall_Feasibility_Status__c;
                                    FeasibilityTask.Group_Working_on_the_Task__c =BFVTask.Group_Working_on_the_Task__c;
                                    FeasibilityTask.Task_Close_Date__c=system.today();
                                    FeasibilityTask.Sub_Group__c=BFVTask.SubGroup__c ;
                                    FeasibilityTask.Task_Acknowledged_By__c='Abdul Munaf Sheikh';
                                    FeasibilityTasklist.add(FeasibilityTask);
                                
                                }
                                    if(FeasibilityTasklist!=null &&!FeasibilityTasklist.isEmpty())
                                    {
                                        saveResult = database.insert(FeasibilityTasklist,true); 
                                        
                                    }
                                    if(saveResult != null && !saveResult.isEmpty()){
                                            for(Database.SaveResult srObj1:saveResult)
                                            {
                                                if (srObj1.isSuccess()) {
                                                    FeasibilityTaskId.add(srObj1.getId()); 
                                                    System.debug('FeasibilityTaskId::'+ FeasibilityTaskId);           
                                                    
                                                }else{
                                                    for(Database.Error err1 : srObj1.getErrors())
                                                    {                
                                                                            
                                                        ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'  '+err1.getMessage()+''+ err1.getFields());
                                                        ApexPages.addMessage(errormsg);
                                                        return null;
                                                        
                                                    }                                    
                                                    
                                                }
                                            }
                                        
                                    }
                      FeasibilityTasklist1 =[Select Id,Name,CreatedDate,Feasibility_Request__r.Port_Feasibility_Flag__c,Feasibility_Request__r.Other_POP_A_End__c,Feasibility_Request__r.City_A_End__c,Feasibility_Request__r.State_A_End__c,Feasibility_Request__r.Country_A_End__c,Feasibility_Request__r.Port_Circuit_Capacity__c,Feasibility_Request__r.Products_Services__r.Cloud_Provider__c from Feasibility_Task__c where Feasibility_Request__c IN:successcaseList];
                                 system.debug('FeasibilityTasklist1 ::' +FeasibilityTasklist1);
                                 iF(FeasibilityTasklist1 !=null && !FeasibilityTasklist1.isEmpty()){
                                       
                                       for(integer i=0;i<FeasibilityTasklist1.size();i++)
                                        {           
        Bundle_Feasibility_values__c BFVResponse = Bundle_Feasibility_values__c.getInstance('Bundle Values');                                            
                  Feasibility_Response_A__c FeasibilityResponse = new Feasibility_Response_A__c(); 
                                            FeasibilityResponse.Recordtypeid=BFVResponse.Responserecordtype__c;
                                            FeasibilityResponse.Feasibility_Task__c = FeasibilityTasklist1[i].Id;
                                            FeasibilityResponse.Case__c = successcaseList[i].id;
                                            FeasibilityResponse.Response_Related_To__c  =BFVResponse.Response_Related_To__c;
                                            FeasibilityResponse.Feasibility_Status__c =BFVResponse.Feasibility_Status__c;
                                            FeasibilityResponse.Provider_Name__c=BFVResponse.Provider_Name__c;
                                            FeasibilityResponse.LM_Contract_Term__c=BFVResponse.LM_Contract_Term__c;
                                            FeasibilityResponse.Provider_Request_Date__c=System.today();
                                            FeasibilityResponse.Provider__c=System.today();
                                            FeasibilityResponse.Feasiblity_Expiry_Date__c=Date.today().addDays(30) ;
                                            FeasibilityResponse.Feasibility_Status_Category__c=BFVResponse.Feasibility_Status_Category__c;
                                            FeasibilityResponse.TCL_POP_Address__c=BFVResponse.TCL_POP_Address__c;
                                            FeasibilityResponse.Local_Loop_Interface__c=BFVResponse.Local_Loop_Interface__c;
                                            FeasibilityResponse.Sales_Selected_Response__c=BFVResponse.Sales_Selected_Response__c;
                                            FeasibilityResponse.Local_Loop_Capacity__c=BFVResponse.Local_Loop_Capacity__c;
                                            FeasibilityResponse.POP_Address__c='a6N20000000aJ10';
                                            
                                            FeasibilityResponselist.add(FeasibilityResponse);
                                            
                                        }
                                        
                                    }                                    
                                if(FeasibilityResponselist!=null && !FeasibilityResponselist.isEmpty()){
                                     saveResult = database.insert(FeasibilityResponselist,true);           
                                    System.debug('saveResult::'+saveResult);
                                    }   
                                    if(saveResult != null && !saveResult.isEmpty()){
                                            for(Database.SaveResult srObj2:saveResult)
                                            {
                                                if (srObj2.isSuccess()) {
                                                    FeasibilityResponseId.add(srObj2.getId()); 
                                                    System.debug('FeasibilityResponseId::'+FeasibilityResponseId);           
                                                    
                                                }else{
                                                    for(Database.Error err2 : srObj2.getErrors())
                                                    {                       
                                                        ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'  '+err2.getMessage()+''+ err2.getFields());
                                                        ApexPages.addMessage(errormsg);
                                                        return null;
                                                        
                                                    }                                    
                                                    
                                                }
                                            }
                                        
                                    }
                                    
                                }                                   
                  //successFullcase();
                   ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'successfully case completed: ');
                   ApexPages.addMessage(errormsg);
                }
           
            }
           else
           {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'Please Upload Only CSV Files.'));
            
            }
        }
      else{
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'Please Select A File To Upload'));
         
        }

Return null;
}

 public PageReference cancel() {
 pageReference page = new pageReference('/apex/BundleFeasibilitypage');
 page.setRedirect(true);
  return page;
 //return null;
  
} 

/*
public PageReference successFullcase() {
if(caseid!=null && !caseid.isEmpty())
{
return Page.BundleFeasibilitySuccessResult;

   }
   else {
        ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'There are no successfully inserted Bundle Feasibilitypage'));
        return null;
    }
  
    
}

*/

public static String blobToString(Blob input, String inCharset){
String hex = EncodingUtil.convertToHex(input);

    System.assertEquals(0, hex.length() & 1);
    final Integer bytesCount = hex.length() >> 1;
    String[] bytes = new String[bytesCount];
    for(Integer i = 0; i < bytesCount; ++i)
    bytes[i] =  hex.mid(i << 1, 2);
System.Debug('pkppkp '+EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset));  
    return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);

}  

}

Size of apex Code Exceeded

Getting the following error when trying to deploy via workbench for all the file sunder the Classes folder:

The total size of apex code in this application after removing comments exceeds the maxiumum character size of 3000000

Problem Loading

I can't seem to upload a csv file into the Custom Metadata Type. I must be blind, but my file matches the recommendation in the error message. What am I missing?

Error:Header must contain the api names of the fields. Fields allowed for this type: (DeveloperName, Label, Description, autocred__School__c, autocred__State__c, autocred__Established__c, autocred__City__c, autocred__Degree__c)Fields in file header: {DeveloperName, autocred__City__c, autocred__Degree__c, autocred__Established__c, autocred__School__c, autocred__State__c, Label}

Error: Custom fields cannot be found

Hi there,

I had a custom metadata type created in my Salesforce sandbox and tried to load some records via the loader following the instruction provided.

The issue is that values for DeveloperName and Label can be found by the loader, but the values for the custom fields (Zone__c, Rating__c, Post_from__c, Post_to__c) cannot be loaded at all.

Here is a screenshot of the CSV file.
screen shot 2017-07-12 at 10 59 03 am

Here is a screenshot after loading the my CSV containing all records I need.
screen shot 2017-07-12 at 10 57 48 am

EDITED:

Problem solved by changing from comma "," to semicolon ";".

Thank you,
Terry.

Security bugs

Hey all,

Would this be the place to submit a security bug for fixing? Or would I submit it directly to Salesforce? Anyone know?

Would like to responsibly disclose rather than blast details out.

Please feel free to remove this if this is not the right forum.

Collection size 1,381 exceeds maximum size of 1,000.

I'm trying to upload a sample/test file that contains only two records and I'm receiving the error:
Collection size 1,381 exceeds maximum size of 1,000.

The 1,381 number matches how many metadata records are on this particular __mdt in our org.

Issue trying to upload some updated records

Haga clic para abrir la barra lateral El contenido empieza aquí
Web service callout failed: WebService returned a SOAP Fault: Unknown SObject Namespace for Metadata Error Id: 394018059-2725 (-1586907319) faultcode=soapenv:Server faultactor=
El error está en la expresión '{!upsertCustomMetadata}' del componente apex:commandButton en page custommetadatarecorduploader: Class.MetadataService.MetadataPort.upsertMetadata: line 9261, column 1
Class.MetadataUtil.upsertMetadataAndValidate: line 131, column 1
Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 97, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 127, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Attempt to de-reference a null object

Attempt to de-reference a null object
Error is in expression '{!upsertCustomMetadata}' in component apex:commandButton in page custommetadatarecorduploader: Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

Adding quotes around text fields with commas.

I saw a somewhat related issue around not being able to load metadata fields with commas in the field value.

Now when loading text fields with commas the data includes unwanted quotes around the field value. For example I have a metadata field with a value similar to value1,value2,value3, and when loaded it shows as "value1,value2,value3" in the metadata record (with the quotes as part of the string value).

Maximum view state size limit exceeded error

Hi,

I'm trying to upload some metadata via the Custom Metadata Loader visualforce page. When I load my file, I get this error: "Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 166.907KB". I did some research to see what the error meant to see that it means you're returning too much data and the calls in your controllers are too large (link to doc here) Is there a limit on how big the files can be? My file is only 208 rows, 6 columns, and 14KB. I tried testing with just one row and I am still having issues. Is it the columns?

Thanks!

Rachel

package.xml is not found on deploy

I have tried deploying into a few sandboxes (after one successful deployment into a sandbox) however I am running into the package.xml not found error.

It shows all the components missing the Package.xml. I zipped at the top level of the custom-md-loader folder where all subfolders and package.xml were viewed.

So folders and xml were all at the top level when zipped.
example from
applications folder

  • changed: false
  • componentType:
  • created: false
  • createdDate: 2018-01-24T04:09:22.000Z
  • deleted: false
  • fileName: applications/package.xml
  • fullName: package.xml
    - problem: No package.xml found
  • problemType: Error
  • success: false

Attempt to de-reference a null object

Error is in expression '{!upsertCustomMetadata}' in component <apex:commandButton> in page custommetadatarecorduploader: Class.MetadataUtil.transformToCustomMetadataAndCreateUpdate: line 114, column 1
Class.CustomMetadataUploadController.importCSVFileAndCreateUpdateCmdRecords: line 144, column 1
Class.CustomMetadataUploadController.upsertCustomMetadata: line 52, column 1

An unexpected error has occurred. Your development organization has been notified.

The same issue when i try to upload the sample.csv file. Could you please explain how to fix this problem?

Trying to upload a CSV with fields that contain commas.

Some of the field values have commas in them which is causing issues when uploading. I have tried surrounding that field in double quotes and it accepts the field but won't match it to the correct value as it doesn't remove the double quotes.
Any suggestions?

Remote site setting creation

if my domain name (sbx) is like aa-bbb-cc--testfull.cs87.my.salesforce.com, remote site setting creation failed because label with 2 "_" is forbidden "aa_bbb_cc__testfull_mdapi"

classe : CustomMetadataLoaderController
prefixOrLocal = host.substringBefore('.').replaceAll('-', '');
=> prefixOrLocal = host.substringBefore('.').replaceAll('-', '
').replaceAll('__', '_'); /for instance/

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.