Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Dynamics CRM 2013 SDK Import CSV

Posted on by Microsoft Employee

Hello

I am trying to import a csv file using hte CRM dynamics SDK 2013. I keep seeing examples of code using the import class as shown below

Import myimport = new Import();

or

 ImportFile importFile = new ImportFile();

however i cant seem to get these classes referenced. Were these introduced in later versions of the sdk? if yes is there another way to achieve the same effect. Essentially i wana take  a csv file and import it into dynamics using the sdk 2013. It would help if it can use an existing data map to make the import code shorter.

regards

*This post is locked for comments

  • Verified answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Dynamics CRM 2013 SDK Import CSV

    Hi netzero,

     you need to create early-bound classes:

    https://msdn.microsoft.com/en-us/library/gg327844.aspx

    if you wanted to use late-bound,  here is an example (should get you started, at least):

    public string GetSourceEntityName(Entity importMap)
            {
                var columnMapping = (from cl in context.CreateQuery("columnmapping")
                                 where (Guid)cl["importmapid"] == importMap.Id && cl["sourceentityname"] != null
                                 select cl).FirstOrDefault();
                return (string)columnMapping["sourceentityname"];
            }
    
            public static void WaitForAsyncJobCompletion(string jobName, OrganizationService service, Guid asyncJobId)
            {
                Microsoft.Xrm.Sdk.Query.ColumnSet cs = new Microsoft.Xrm.Sdk.Query.ColumnSet("statecode", "statuscode");
                var asyncjob =
                    service.Retrieve("asyncoperation", asyncJobId, cs);
    
                int retryCount = 200;
    
                while (((OptionSetValue)asyncjob["statecode"]).Value != 3 && retryCount > 0)
                {
                    asyncjob = service.Retrieve("asyncoperation", asyncJobId, cs);
                    System.Threading.Thread.Sleep(2000);
                    retryCount--;
                }
                if(((OptionSetValue)asyncjob["statecode"]).Value == 3) Console.WriteLine(jobName + " completed successfully..");
                else Console.WriteLine(jobName + " failed!");
            }
    
            public bool ImportData(string mapName, string targetEntityName, string data)
            {
                Console.WriteLine("Loading data for " + targetEntityName + " using \"" + mapName + "\" map..");
                var importMap = (from imp in context.CreateQuery("importmap")
                                 where (string)imp["name"] == mapName
                                 select imp).FirstOrDefault();
                if (importMap == null)
                {
                    Console.WriteLine("Cannot find the import map: " + mapName);
                    return false;
                }
    
                GetSourceEntityName(importMap);
    
                Entity import = new Entity("import");
                import.Attributes.Add("modecode", new OptionSetValue(0));
                import.Attributes.Add("name", "DataLoader: " + targetEntityName + "/" + mapName);
                import.Attributes.Add("sendnotification", false);
                import.Id = service.Create(import);
    
                Entity importFile = new Entity("importfile");
                importFile.Attributes.Add("targetentityname", targetEntityName);
                importFile.Attributes.Add("content", data);
                importFile.Attributes.Add("name", "DataLoader: " + targetEntityName);
                importFile.Attributes.Add("source", targetEntityName);
                importFile.Attributes.Add("size", data.Length.ToString());
                importFile.Attributes.Add("datadelimitercode", new OptionSetValue(int.Parse(System.Configuration.ConfigurationManager.AppSettings["datadelimitercode"])));
                importFile.Attributes.Add("fielddelimitercode", new OptionSetValue(int.Parse(System.Configuration.ConfigurationManager.AppSettings["fielddelimitercode"])));
                importFile.Attributes.Add("filetypecode", new OptionSetValue(int.Parse(System.Configuration.ConfigurationManager.AppSettings["filetypecode"])));
                importFile.Attributes.Add("isfirstrowheader", Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["isfirstrowheader"]));
                importFile.Attributes.Add("importid", import.ToEntityReference());
                importFile.Attributes.Add("enableduplicatedetection", Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["enableduplicatedetection"]));
                importFile.Attributes.Add("importmapid", importMap.ToEntityReference());
                importFile.Attributes.Add("sourceentityname", GetSourceEntityName(importMap));//IMPORTANT? Does it correspond to the original file name?
     
                service.Create(importFile);
    
    
                ParseImportRequest parseRequest = new ParseImportRequest();
                parseRequest.ImportId = import.Id;
                ParseImportResponse parseImportResponse = (ParseImportResponse)service.Execute(parseRequest);
                WaitForAsyncJobCompletion("Parsing data", service, parseImportResponse.AsyncOperationId);
    
                TransformImportRequest transRequest = new TransformImportRequest();
                transRequest.ImportId = import.Id;
                TransformImportResponse transResponse = (TransformImportResponse)service.Execute(transRequest);
                WaitForAsyncJobCompletion("Transforming data", service, transResponse.AsyncOperationId);
    
                ImportRecordsImportRequest request = new ImportRecordsImportRequest();
                request.ImportId = import.Id;
                ImportRecordsImportResponse response = (ImportRecordsImportResponse)service.Execute(request);
                WaitForAsyncJobCompletion("Importing data", service, response.AsyncOperationId);
                return true;
            }


Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans