This documentation is archived and is not being maintained.

Start an Import Job

Forefront
banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

The following code example shows how to start an import job.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\DataMigration\StartImportJob.cs

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

[C#]
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Services.Protocols;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;


namespace Microsoft.Crm.Sdk.HowTo.DataMigration
{
    /// <summary> 
    /// This sample shows how to start an import job.
    /// </summary>
    class ImportRecordsImport
    {
       static void Main(string[] args)
        {
            bool success = false;

            try
            {
                // TODO: Change the server URL and organization to match your 
                //  Microsoft Dynamics CRM Server and Microsoft Dynamics CRM Organization.
                success = ImportRecordsImport.Run("http://localhost:5555", "CRM_Organization");

            }
            catch (SoapException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Detail.InnerText);
            }
            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);

                    SoapException se = ex.InnerException as SoapException;
                    if (se != null)
                        Console.WriteLine(se.Detail.InnerText);
                }
            }
            finally
            {
                Console.WriteLine("Completed successfully? {0}", success);
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }

        public static bool Run(string crmServerUrl, string orgName)
        {
            bool success = true;

            try
            {
                // Set up the CRM Service.
                CrmService service = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

                #region Setup Data Required for this Sample

                WhoAmIRequest who = new WhoAmIRequest();
                WhoAmIResponse whoResponse = (WhoAmIResponse) service.Execute(who);

                import imp = new import();
                imp.isimport = new CrmBoolean();
                imp.isimport.Value = true;

                // Note: ImportModeCode 0 = "Create"
                imp.modecode = new Picklist();
                imp.modecode.Value = 0;

                imp.name = "Importing accounts";
                imp.sendnotification = new CrmBoolean();
                imp.sendnotification.Value = false;

                Guid importId = service.Create(imp);   

                // Create the import file
                importfile file = new importfile();
                file.content =
@"Account Name,Address 1: Street 1,Address 1: Street 2,Address 1: City,Address 1: State/Province,Address 1: ZIP/Postal Code
Microsoft,123 fake st,,seattle,wa,29485
Microsoft,345 nowhere dr.,appt 1a,bellevue,wa,34534";

                file.headerrow = "Account Name,Address 1: Street 1,Address 1: Street 2,Address 1: City,Address 1: State/Province,Address 1: ZIP/Postal Code";
                file.name = "ImportFile1";
                file.isfirstrowheader = new CrmBoolean(true);
                file.recordsownerid = new Lookup("systemuser", whoResponse.UserId);
                file.source = "data.csv";
                file.sourceentityname = "Book1";
                file.importid = new Lookup("import", importId);
                
                // Note: Field delimiter 2 = comma;
                file.fielddelimitercode = new Picklist(2);
                file.targetentityname = "account";
                
                // Note: Data Delimiter 1 = double quote
                file.datadelimitercode = new Picklist(1);
                file.size = file.content.Length.ToString();
                
                // Note: Process code 1 = "Process"
                file.processcode = new Picklist(1);
                file.usesystemmap = new CrmBoolean(true);
             
                Guid fileId = service.Create(file);

                // Parse the import.
                ParseImportRequest parseRequest = new ParseImportRequest();
                parseRequest.ImportId = importId;
                service.Execute(parseRequest);

                // Transform the import.
                TransformImportRequest transRequest = new TransformImportRequest();
                transRequest.ImportId = importId;
                TransformImportResponse transResponse = (TransformImportResponse) service.Execute(transRequest);

                #endregion

                // Create an ImportRecordsImport request
                ImportRecordsImportRequest request = new ImportRecordsImportRequest();
                
                // Assign the request the id of the import we want to begin
                request.ImportId = importId;

                // Execute the request.
                ImportRecordsImportResponse response = (ImportRecordsImportResponse)service.Execute(request);
                    
                #region Check Success
                
                // After starting the import, it will take some time to complete.
                // Wait for the operation to complete by polling it's state every few seconds.
                ColumnSet cols = new ColumnSet();
                cols.Attributes = new string[] {"statecode"};
                for (int i = 0; i < 50; i++)
                {
                    System.Threading.Thread.Sleep(2000);
                    asyncoperation op = (asyncoperation)service.Retrieve(EntityName.asyncoperation.ToString(), response.AsyncOperationId, cols);
                    if (op.statecode.Value == AsyncOperationState.Completed)
                    {
                        break;
                    }
                }
                
                // Verify that records were imported.
                QueryByAttribute query = new QueryByAttribute();
                query.EntityName = EntityName.account.ToString();
                query.Attributes = new string[] { "name" };
                query.Values = new object[] { "Microsoft" };
                query.ColumnSet = cols;
                BusinessEntityCollection results = service.RetrieveMultiple(query);
                if (results.BusinessEntities.Length < 2)
                {
                    success = false;
                }
                
                #endregion


                #region Remove Data Required for this Sample

                //Delete the accounts that were imported
                foreach (account acct in results.BusinessEntities)
                {
                    service.Delete(EntityName.account.ToString(), acct.accountid.Value);
                }
                
                // Delete the import
                service.Delete(EntityName.import.ToString(), importId);

                #endregion

            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
            catch (Exception)
            {
                throw;
            }

            return success;
        }

    }
}

See Also

Concepts

See Also

Reference


© 2010 Microsoft Corporation. All rights reserved.


Show: