locked
CRM 2011 Data Import using SDK RRS feed

Answers

All replies

  • Hi,

    please share your code so that we can identify the problem. Importing via the SDK is definitely possible.

    Greetings,

    Pavlos


    Please mark this reply as an answer and vote it as helpful if it helps you find a resolution to your problem.
    View my latest gallery contribution here.
    Visit my blog here.

    Thursday, November 1, 2012 11:08 PM
  • Its same code that is giving in SDK Sample, only change I have made is use of existing Import MapId by putting hard coded GUID

    /// <summary>
            /// Imports records to Microsoft Dynamics CRM from the specified .csv file.
            /// </summary>
            public void ImportRecords()
            {
    
                Guid importMapId = new Guid("E01D68E3-2F2A-4687-91EB-22A443D5E7C0");
    
                // Create Import
                Import import = new Import()
                {
                    // IsImport is obsolete; use ModeCode to declare Create or Update.
                    ModeCode = new OptionSetValue((int)ImportModeCode.Create),
                    Name = "Importing data"
                };
                Guid importId = _serviceProxy.Create(import);
    
                // Create Import File.
                ImportFile importFile = new ImportFile()
                {
                    Content = BulkImportHelper.ReadCsvFile("Import Accounts.csv"), // Read contents from disk.
                    Name = "BIV record import : " + DateTime.Now.ToString("MM-dd-yyyy-mm"),
                    IsFirstRowHeader = true,
                    ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId),
                    UseSystemMap = false,
                    Source = "Import Accounts.csv",
                    SourceEntityName = "Account_1",
                    TargetEntityName = "account",
                    ImportId = new EntityReference(Import.EntityLogicalName, importId),
                    EnableDuplicateDetection = false,
                    FieldDelimiterCode =
                        new OptionSetValue((int)ImportFileFieldDelimiterCode.Comma),
                    DataDelimiterCode =
                        new OptionSetValue((int)ImportFileDataDelimiterCode.DoubleQuote),
                    ProcessCode =
                        new OptionSetValue((int)ImportFileProcessCode.Process),
                        //FileTypeCode = ImportFileFileTypeCode.CSV;
                };
    
                // Get the current user to set as record owner.
                WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                WhoAmIResponse systemUserResponse =
                    (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);
    
                // Set the owner ID.				
                importFile.RecordsOwnerId =
                    new EntityReference(SystemUser.EntityLogicalName, systemUserResponse.UserId);
    
                Guid importFileId = _serviceProxy.Create(importFile);
    
                //<snippetImportWithCreate1>
                // Retrieve the header columns used in the import file.
                GetHeaderColumnsImportFileRequest headerColumnsRequest = new GetHeaderColumnsImportFileRequest()
                {
                    ImportFileId = importFileId
                };
                GetHeaderColumnsImportFileResponse headerColumnsResponse =
                    (GetHeaderColumnsImportFileResponse)_serviceProxy.Execute(headerColumnsRequest);
    
                // Output the header columns.
                int columnNum = 1;
                foreach (string headerName in headerColumnsResponse.Columns)
                {
                    Console.WriteLine("Column[" + columnNum.ToString() + "] = " + headerName);
                    columnNum++;
                }
                //</snippetImportWithCreate1>
    
                //<snippetImportWithCreate2>
                // Parse the import file.
                ParseImportRequest parseImportRequest = new ParseImportRequest()
                {
                    ImportId = importId
                };
                ParseImportResponse parseImportResponse =
                    (ParseImportResponse)_serviceProxy.Execute(parseImportRequest);
                Console.WriteLine("Waiting for Parse async job to complete");
                //</snippetImportWithCreate2>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, parseImportResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);
    
                //<snippetImportWithCreate3>
                // Retrieve the first two distinct values for column 1 from the parse table.
                // NOTE: You must create the parse table first using the ParseImport message.
                // The parse table is not accessible after ImportRecordsImportResponse is called.
                GetDistinctValuesImportFileRequest distinctValuesRequest = new GetDistinctValuesImportFileRequest()
                {
                    columnNumber = 1,
                    ImportFileId = importFileId,
                    pageNumber = 1,
                    recordsPerPage = 2,
                };
                GetDistinctValuesImportFileResponse distinctValuesResponse =
                    (GetDistinctValuesImportFileResponse)_serviceProxy.Execute(distinctValuesRequest);
    
                // Output the distinct values.  In this case: (column 1, row 1) and (column 1, row 2).
                int cellNum = 1;
                foreach (string cellValue in distinctValuesResponse.Values)
                {
                    Console.WriteLine("(1, " + cellNum.ToString() + "): " + cellValue);
                    Console.WriteLine(cellValue);
                    cellNum++;
                }
                //</snippetImportWithCreate3>
    
                //<snippetImportWithCreate4>
                // Retrieve data from the parse table.
                // NOTE: You must create the parse table first using the ParseImport message.
                // The parse table is not accessible after ImportRecordsImportResponse is called.
                RetrieveParsedDataImportFileRequest parsedDataRequest = new RetrieveParsedDataImportFileRequest()
                {
                    ImportFileId = importFileId,
                    PagingInfo = new PagingInfo()
                    {
                        // Specify the number of entity instances returned per page.
                        Count = 2,
                        // Specify the number of pages returned from the query.
                        PageNumber = 1,
                        // Specify a total number of entity instances returned.
                        PagingCookie = "1"
                    }
                };
    
                RetrieveParsedDataImportFileResponse parsedDataResponse =
                    (RetrieveParsedDataImportFileResponse)_serviceProxy.Execute(parsedDataRequest);
    
                // Output the first two rows retrieved.
                int rowCount = 1;
                foreach (string[] rows in parsedDataResponse.Values)
                {
                    int colCount = 1;
                    foreach (string column in rows)
                    {
                        Console.WriteLine("(" + rowCount.ToString() + "," + colCount.ToString() + ") = " + column);
                        colCount++;
                    }
                    rowCount++;
                }
                //</snippetImportWithCreate4>
    
                //<snippetImportWithCreate5>
                // Transform the import
                TransformImportRequest transformImportRequest = new TransformImportRequest()
                {
                    ImportId = importId
                };
                TransformImportResponse transformImportResponse =
                    (TransformImportResponse)_serviceProxy.Execute(transformImportRequest);
                Console.WriteLine("Waiting for Transform async job to complete");
                //</snippetImportWithCreate5>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, transformImportResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);
    
                //<snippetImportWithCreate6>
                // Upload the records.
                ImportRecordsImportRequest importRequest = new ImportRecordsImportRequest()
                {
                    ImportId = importId
                };
                ImportRecordsImportResponse importResponse =
                    (ImportRecordsImportResponse)_serviceProxy.Execute(importRequest);
                Console.WriteLine("Waiting for ImportRecords async job to complete");
                //</snippetImportWithCreate6>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, importResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);
            }


    MaKeer | myencounterwithcrm.wordpress.com | CRM2011 User Settings Utility | CRM2011 Lookup Preview | CRM2011 Lookup Attribute Mapping | CRM2011 TreeView Control (Beta) | CRM2011 N:N Entity View (Beta) | CRM 2011 Global Quick Search (Beta)

    Thursday, November 1, 2012 11:41 PM
  • Finally with the help of SQL Server Profiler, I could figured out the problem.

    Actually there was mismatch of values of ImportFile.SourceEntityName in code and EntityMap.SourceEntityName in mapping file.

    These values should exactly matched. Since it was not very clear from SDK I was setting it to some random value in code.

    And when we generate Wizard based DataMaps it takes SourceEntityName as CVS file name used for importing data.

    Hope SDK Documentation has more details around these properties.

    Thanks

    Mak



    MaKeer | myencounterwithcrm.wordpress.com | CRM2011 User Settings Utility | CRM2011 Lookup Preview | CRM2011 Lookup Attribute Mapping | CRM2011 TreeView Control (Beta) | CRM2011 N:N Entity View (Beta) | CRM 2011 Global Quick Search (Beta)

    • Marked as answer by Makarand Keer Friday, November 2, 2012 4:01 AM
    Friday, November 2, 2012 4:01 AM
  • Hi. Am having similar error to map field in CRM 2013. I'm actually mapping product which is having to reference another 2 tables.

    Below r the codes.

    Grateful if some1 can help.

    Thanks

    kevin



    //<snippetImportWithCreate>
    using System;
    using System.ServiceModel;
    using System.Collections.Generic;
    using System.Linq;

    // These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
    // located in the SDK\bin folder of the SDK download.
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;

    // These namespaces are found in the Microsoft.Crm.Sdk.Proxy.dll assembly
    // located in the SDK\bin folder of the SDK download.
    using Microsoft.Crm.Sdk.Messages;

    namespace Microsoft.Crm.Sdk.Samples
    {    
        /// <summary>
    /// This sample shows how to define a complex mapping for importing and then use the
        /// Microsoft Dynamics CRM 2011 API to bulk import records with that mapping.
    /// </summary>
        public class ImportWithCreate
        {
            #region Class Level Members

            private OrganizationServiceProxy _serviceProxy;
            private DateTime _executionDate;

            #endregion

            /// <summary>
            /// This method first connects to the organization service. Afterwards,
            /// auditing is enabled on the organization, account entity, and a couple
            /// of attributes.
            /// </summary>
            /// <param name="serverConfig">Contains server connection information.</param>
            /// <param name="promptforDelete">When True, the user will be prompted to delete all
            /// created entities.</param>
            public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
            {
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Log the start time to ensure deletion of records created during execution.
                    _executionDate = DateTime.Today;
                    ImportRecords();
                  //commented by kevin
                    //DeleteRequiredRecords(promptforDelete);
                }
            }

            /// <summary>
            /// Imports records to Microsoft Dynamics CRM from the specified .csv file.
            /// </summary>
            public void ImportRecords()
            {
                // Create an import map.
                ImportMap importMap = new ImportMap()
                {
                    Name = "Import Map " + DateTime.Now.Ticks.ToString(),
                    Source = "accounts.csv",
                    Description = "Description of data being imported",
                    EntitiesPerFile =
                        new OptionSetValue((int)ImportMapEntitiesPerFile.SingleEntityPerFile),
                    EntityState = EntityState.Created
                };
                Guid importMapId = _serviceProxy.Create(importMap);

                // Create column mappings.

                #region Column One Mappings
                // Create a column mapping for a 'text' type field.
                ColumnMapping colMapping1 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "ITEMID",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "productid",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId1 = _serviceProxy.Create(colMapping1);
                #endregion

        
                /////

                       
                #region Column two Mappings
                // Create a column mapping for a 'text' type field.
                ColumnMapping colMapping2 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "ITEMNAME",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "name",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId2 = _serviceProxy.Create(colMapping2);
                #endregion



                #region Column three Mappings
                // Create a column mapping for a 'text' type field.
                //Added by kevin
                ColumnMapping colMapping3 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "SUPPLIER",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "description",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId3 = _serviceProxy.Create(colMapping3);
                #endregion


                #region Column four Mappings
                // Create a column mapping for a 'text' type field.
                //Added by kevin
                ColumnMapping colMapping4 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "NESLORRYTYPE",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "vendorname",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId4 = _serviceProxy.Create(colMapping4);
                #endregion

               
                #region Column five Mappings
                // Create a column mapping for a 'text' type field.
                //Added by kevin
                ColumnMapping colMapping5 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "DESCRIPTION",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "producturl",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId5 = _serviceProxy.Create(colMapping5);
                #endregion

                #region Column six Mappings
                // Create a column mapping for a 'text' type field.
                //Added by kevin
                ColumnMapping colMapping6 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "ITEMGROUPID",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "vendorpartnumber",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId6 = _serviceProxy.Create(colMapping6);
                #endregion


                #region Column seven Mappings
                //// Create a column mapping for a 'text' type field.
             
                ///
                


                // Create a column mapping for a 'lookup' type field.
                ColumnMapping colMapping7 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "DEFAULTUNIT",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "defaultuomscheduleid",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process),
                };

                // Create the mapping.
                Guid colMappingId7 = _serviceProxy.Create(colMapping7);

                // Because we created a column mapping of type lookup, we need to specify lookup details in a lookupmapping.
                // One lookupmapping will be for the parent account, and the other for the current record.
                // This lookupmapping is important because without it the current record
                // cannot be used as the parent of another record.

                // Create a lookup mapping to the parent account.  
                LookUpMapping parentLookupMapping = new LookUpMapping()
                {
                    // Relate this mapping with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId7),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for an account entity by its name attribute.
                    LookUpEntityName = UoMSchedule.EntityLogicalName,
                    LookUpAttributeName = "name",
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.System)
                };

                 
            
                // Create the lookup mapping.
                Guid parentLookupMappingId = _serviceProxy.Create(parentLookupMapping);

                // Create a lookup on the current record's "src_name" so that this record can
                // be used as the parent account for another record being imported.
                // Without this lookup, no record using this account as its parent will be imported.
                LookUpMapping currentLookUpMapping = new LookUpMapping()
                {
                    // Relate this lookup with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId7),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for the current record by its src_name attribute.
                    LookUpAttributeName = "name",
                    //LookUpEntityName = "myid",
                    LookUpEntityName = UoMSchedule.EntityLogicalName,
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.Source)
                };

                // Create the lookup mapping
                Guid currentLookupMappingId = _serviceProxy.Create(currentLookUpMapping);
                #endregion

                
                #region Column eight Mappings
                // Create a column mapping for a 'text' type field.
                //Added by kevin
                ColumnMapping colMapping8 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "DECIMALSSUPPORTED",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "quantitydecimal",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process)
                };

                // Create the mapping.
                Guid colMappingId8 = _serviceProxy.Create(colMapping8);
                #endregion

                
                #region Column nine Mappings

                // Create a column mapping for a 'lookup' type field.
                ColumnMapping colMapping9 = new ColumnMapping()
                {
                    // Set source properties.
                    SourceAttributeName = "UNITGROUP",
                    SourceEntityName = "Account_1",

                    // Set target properties.
                    TargetAttributeName = "defaultuomid",
                    TargetEntityName = Product.EntityLogicalName,

                    // Relate this column mapping with the data map.
                    ImportMapId =
                        new EntityReference(ImportMap.EntityLogicalName, importMapId),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)ColumnMappingProcessCode.Process),
                };

                // Create the mapping.
                Guid colMappingId9 = _serviceProxy.Create(colMapping9);

                // Because we created a column mapping of type lookup, we need to specify lookup details in a lookupmapping.
                // One lookupmapping will be for the parent account, and the other for the current record.
                // This lookupmapping is important because without it the current record
                // cannot be used as the parent of another record.

                // Create a lookup mapping to the parent account.  
                LookUpMapping parentLookupMapping1 = new LookUpMapping()
                {
                    // Relate this mapping with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId9),
                        
                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for an account entity by its name attribute.
                    LookUpEntityName = "uom",
                    LookUpAttributeName = "name",
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.System)
                };

                // Create the lookup mapping.
                Guid parentLookupMappingId1 = _serviceProxy.Create(parentLookupMapping1);

                // Create a lookup on the current record's "src_name" so that this record can
                // be used as the parent account for another record being imported.
                // Without this lookup, no record using this account as its parent will be imported.
                LookUpMapping currentLookUpMapping1 = new LookUpMapping()
                {
                    // Relate this lookup with its parent column mapping.
                    ColumnMappingId =
                        new EntityReference(ColumnMapping.EntityLogicalName, colMappingId9),

                    // Force this column to be processed.
                    ProcessCode =
                        new OptionSetValue((int)LookUpMappingProcessCode.Process),

                    // Set the lookup for the current record by its src_name attribute.
                    LookUpAttributeName = "name",
                   // LookUpEntityName = "MyotherId",
                    LookUpEntityName = "uom",
                    LookUpSourceCode =
                        new OptionSetValue((int)LookUpMappingLookUpSourceCode.Source)
                };

                // Create the lookup mapping
                Guid currentLookupMappingId1 = _serviceProxy.Create(currentLookUpMapping1);
                #endregion

                ///////////////////////////////////////////////////////////////////////////////////////////


                // Create Import
                Import import = new Import()
                {
                    // IsImport is obsolete; use ModeCode to declare Create or Update.
                    ModeCode = new OptionSetValue((int)ImportModeCode.Create),
                    Name = "Importing data"
                };
                Guid importId = _serviceProxy.Create(import);

                // Create Import File.
                ImportFile importFile = new ImportFile()
                {
                    Content = BulkImportHelper.ReadCsvFile("accounts.csv"), // Read contents from disk.
                    Name = "Product record import",
                    IsFirstRowHeader = true,
                    ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId),
                    UseSystemMap = false,
                    Source = "accounts.csv",
                    SourceEntityName = "Account_1",
                    TargetEntityName = Product.EntityLogicalName,
                    ImportId = new EntityReference(Import.EntityLogicalName, importId),
                    EnableDuplicateDetection = false,
                    FieldDelimiterCode =
                        new OptionSetValue((int)ImportFileFieldDelimiterCode.Comma),
                    DataDelimiterCode =
                        new OptionSetValue((int)ImportFileDataDelimiterCode.DoubleQuote),
                    ProcessCode =
                        new OptionSetValue((int)ImportFileProcessCode.Process)
                };

                // Get the current user to set as record owner.
                WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                WhoAmIResponse systemUserResponse =
                    (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);

                // Set the owner ID.
                importFile.RecordsOwnerId =
                    new EntityReference(SystemUser.EntityLogicalName, systemUserResponse.UserId);

                Guid importFileId = _serviceProxy.Create(importFile);

                //<snippetImportWithCreate1>
                // Retrieve the header columns used in the import file.
                GetHeaderColumnsImportFileRequest headerColumnsRequest = new GetHeaderColumnsImportFileRequest()
                {
                    ImportFileId = importFileId
                };
                GetHeaderColumnsImportFileResponse headerColumnsResponse =
                    (GetHeaderColumnsImportFileResponse)_serviceProxy.Execute(headerColumnsRequest);

                // Output the header columns.
                int columnNum = 1;
                foreach (string headerName in headerColumnsResponse.Columns)
                {
                    Console.WriteLine("Column[" + columnNum.ToString() + "] = " + headerName);
                    columnNum++;
                }
                //</snippetImportWithCreate1>

                //<snippetImportWithCreate2>
                // Parse the import file.
                ParseImportRequest parseImportRequest = new ParseImportRequest()
                {
                    ImportId = importId
                };
                ParseImportResponse parseImportResponse =
                    (ParseImportResponse)_serviceProxy.Execute(parseImportRequest);
                Console.WriteLine("Waiting for Parse async job to complete");
                //</snippetImportWithCreate2>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, parseImportResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);

                //<snippetImportWithCreate3>
                // Retrieve the first two distinct values for column 1 from the parse table.
                // NOTE: You must create the parse table first using the ParseImport message.
                // The parse table is not accessible after ImportRecordsImportResponse is called.
                GetDistinctValuesImportFileRequest distinctValuesRequest = new GetDistinctValuesImportFileRequest()
                {
                    columnNumber = 1,
                    ImportFileId = importFileId,
                    pageNumber = 1,
                    recordsPerPage = 2,
                };
                GetDistinctValuesImportFileResponse distinctValuesResponse =
                    (GetDistinctValuesImportFileResponse)_serviceProxy.Execute(distinctValuesRequest);

                // Output the distinct values.  In this case: (column 1, row 1) and (column 1, row 2).
                int cellNum = 1;
                foreach (string cellValue in distinctValuesResponse.Values)
                {
                    Console.WriteLine("(1, " + cellNum.ToString() + "): " + cellValue);
                    Console.WriteLine(cellValue);
                    cellNum++;
                }
                //</snippetImportWithCreate3>

                //<snippetImportWithCreate4>
                // Retrieve data from the parse table.
                // NOTE: You must create the parse table first using the ParseImport message.
                // The parse table is not accessible after ImportRecordsImportResponse is called.
                RetrieveParsedDataImportFileRequest parsedDataRequest = new RetrieveParsedDataImportFileRequest()
                {
                    ImportFileId = importFileId,
                    PagingInfo = new PagingInfo()
                    {
                        // Specify the number of entity instances returned per page.
                        Count = 2,
                        // Specify the number of pages returned from the query.
                        PageNumber = 1,
                        // Specify a total number of entity instances returned.
                        PagingCookie = "1"
                    }
                };

                RetrieveParsedDataImportFileResponse parsedDataResponse =
                    (RetrieveParsedDataImportFileResponse)_serviceProxy.Execute(parsedDataRequest);

                // Output the first two rows retrieved.
                int rowCount = 1;
                foreach (string[] rows in parsedDataResponse.Values)
                {
                    int colCount = 1;
                    foreach (string column in rows)
                    {
                        Console.WriteLine("(" + rowCount.ToString() + "," + colCount.ToString() + ") = " + column);
                        colCount++;
                    }
                    rowCount++;
                }
                //</snippetImportWithCreate4>

                //<snippetImportWithCreate5>
                // Transform the import
                TransformImportRequest transformImportRequest = new TransformImportRequest()
                {
                    ImportId = importId
                };
                TransformImportResponse transformImportResponse =
                    (TransformImportResponse)_serviceProxy.Execute(transformImportRequest);
                Console.WriteLine("Waiting for Transform async job to complete");
                //</snippetImportWithCreate5>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, transformImportResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);

                //<snippetImportWithCreate6>
                // Upload the records.
                ImportRecordsImportRequest importRequest = new ImportRecordsImportRequest()
                {
                    ImportId = importId
                };
                ImportRecordsImportResponse importResponse =
                    (ImportRecordsImportResponse)_serviceProxy.Execute(importRequest);
                Console.WriteLine("Waiting for ImportRecords async job to complete");
                //</snippetImportWithCreate6>
                BulkImportHelper.WaitForAsyncJobCompletion(_serviceProxy, importResponse.AsyncOperationId);
                BulkImportHelper.ReportErrors(_serviceProxy, importFileId);
            }

       
            static public void Main(string[] args)
            {
                try
                {
                    // Obtain the target organization's web address and client logon 
                    // credentials from the user.
                    ServerConnection serverConnect = new ServerConnection();
                    ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                    var app = new ImportWithCreate();
                    app.Run(config, true);
                }

                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    Console.WriteLine("The application terminated with an error.");
                    Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                    Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                    Console.WriteLine("Message: {0}", ex.Detail.Message);
                    Console.WriteLine("Trace: {0}", ex.Detail.TraceText);
                    Console.WriteLine("Inner Fault: {0}",
                        null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                }
                catch (System.TimeoutException ex)
                {
                    Console.WriteLine("The application terminated with an error.");
                    Console.WriteLine("Message: {0}", ex.Message);
                    Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                    Console.WriteLine("Inner Fault: {0}",
                        null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("The application terminated with an error.");
                    Console.WriteLine(ex.Message);

                    // Display the details of the inner exception.
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine(ex.InnerException.Message);

                        FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                            as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                        if (fe != null)
                        {
                            Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                            Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                            Console.WriteLine("Message: {0}", fe.Detail.Message);
                            Console.WriteLine("Trace: {0}", fe.Detail.TraceText);
                            Console.WriteLine("Inner Fault: {0}",
                                null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                        }
                    }
                }
                // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
                // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

                finally
                {
                   // commented by kevin

                    Console.WriteLine("Press <Enter> to exit.");
                    Console.ReadLine();
                }
            }
            #endregion Main method
        }
    }


    //</snippetImportWithCreate>


    Tuesday, August 26, 2014 5:29 AM