· 6 years ago · Nov 08, 2019, 01:46 PM
1using Newtonsoft.Json;
2using Newtonsoft.Json.Linq;
3using System;
4using System.Collections.Generic;
5using System.Net.Http;
6using System.Net.Http.Headers;
7using System.Text;
8using System.Threading.Tasks;
9
10namespace ConsoleApp1
11{
12 class Program
13 {
14 static void Main()
15 {
16
17 runAPI();
18 Console.ReadLine();
19
20 }
21 private static async Task runAPI()
22 {
23 //Get token and URL
24 JObject Ojb = await getToken();
25
26 string authenToken = (String)Ojb["access_token"];
27 string serviceUrl = (String)Ojb["instance_url"];
28
29 //Get job ID when create job bulk complete
30 string jobID = await createJob(authenToken, serviceUrl);
31
32 //Send PUT request for add data to the job
33 await BatchesToJob(authenToken, serviceUrl, jobID);
34
35 //Send Patch request for close job
36 await closeJob(authenToken, serviceUrl, jobID);
37 }
38
39 // Get Token
40 private static async Task<JObject> getToken()
41 {
42
43 HttpClient authClient = new HttpClient();
44 HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
45 {
46 {"grant_type","password"},
47 {"client_id","input your Consumer Key"},
48 {"client_secret","input your Cunsumer Secret"},
49 {"username","input Username from your email"},
50 {"password","input your password following Security token (case-sensitive) from your email"}
51 }
52 );
53
54 string endpoint = "https://test.salesforce.com/services/oauth2/token";
55 HttpResponseMessage message = await authClient.PostAsync(endpoint, content);
56
57 string responsestring = await message.Content.ReadAsStringAsync();
58 JObject obj = JObject.Parse(responsestring);
59
60 Console.WriteLine("Get token complete");
61
62 return obj;
63 }
64
65 // Create Bulk API job
66 private static async Task<string> createJob(string Token, string Url)
67 {
68 HttpClient jobClient = new HttpClient();
69
70 var propertiesContent = new Dictionary<string, string>
71 {
72 {"object" , "Account"},
73 {"contentType" , "CSV"},
74 {"lineEnding" , "CRLF"},
75 {"externalIdFieldName" , "Entity_ID__c" },
76 {"operation" , "upsert"}
77 };
78
79 var propertiesJson = JsonConvert.SerializeObject(propertiesContent);
80 HttpContent strProperties = new StringContent(propertiesJson, Encoding.UTF8, "application/json");
81
82 jobClient.DefaultRequestHeaders.Authorization
83 = new AuthenticationHeaderValue("Bearer", Token);
84
85 string endpointJob = Url + "/services/data/v47.0/jobs/ingest";
86 HttpResponseMessage messageJob = await jobClient.PostAsync(endpointJob, strProperties);
87
88 string responseJob = await messageJob.Content.ReadAsStringAsync();
89
90 JObject jobObj = JObject.Parse(responseJob);
91 string jobId = (String)jobObj["id"];
92 Console.WriteLine("create job ", messageJob.IsSuccessStatusCode);
93
94 return jobId;
95
96 }
97
98 //Add Data to the Job
99 private static async Task BatchesToJob(string authenToken, string serviceUrl, string jobId)
100 {
101 HttpClient BatchesClient = new HttpClient();
102 HttpRequestMessage requestBatchesJob = new HttpRequestMessage(HttpMethod.Put,
103 serviceUrl + "/services/data/v47.0/jobs/ingest/" + jobId + "/batches");
104
105 requestBatchesJob.Headers.Add("Authorization", "Bearer " + authenToken);
106
107 string csv = "Entity_ID__c,Person_Code__c,Entity_Type__c,Name,First_Name_Eng__c,Last_Name_Eng__c,Gender__c,Date_of_Birth__c,ID_Card_No__c,Passport_No__c,PDPA_Consent__c,Consent_Channel__c,Consent_DateTime__c,Caution_Note__c" + System.Environment.NewLine +
108 "ID01,001,Person,testname1,Fname1,Lname1,Female,1997-01-06,1570000000000,AB1234567,false,Consent,2019-11-08T10:11:58.000+0000,Example test bulk api" + System.Environment.NewLine +
109 "ID02,002,Person,testname2,Fname2,Lname2,Male,1997-01-06,1570020000000,AB7654321,false,Consent,2019-11-08T10:11:58.000+0000,Example test PUT data";
110
111
112 StringContent csvContent = new StringContent(csv, Encoding.UTF8, "text/csv");
113 csvContent.Headers.ContentType.CharSet = string.Empty;
114 requestBatchesJob.Content = csvContent;
115
116 HttpResponseMessage responseAdd = new HttpResponseMessage();
117
118 try
119 {
120 responseAdd = await BatchesClient.SendAsync(requestBatchesJob);
121 String responseBatchesString = await responseAdd.Content.ReadAsStringAsync();
122 Console.WriteLine("Add data ", responseAdd.IsSuccessStatusCode);
123 }
124 catch (Exception ex)
125 {
126 Console.WriteLine(ex.Message);
127 }
128
129 }
130
131 //Close the job
132 private static async Task closeJob(string authenToken, string serviceUrl, string jobId)
133 {
134 HttpClient closeClient = new HttpClient();
135 HttpRequestMessage requestColseJob = new HttpRequestMessage(HttpMethod.Patch,
136 serviceUrl + "/services/data/v47.0/jobs/ingest/" + jobId);
137
138 requestColseJob.Headers.Add("Authorization", "Bearer " + authenToken);
139 requestColseJob.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
140
141 var stateRequset = new Dictionary<string, string>
142 {
143 {"state" , "UploadComplete"}
144 };
145
146 var jsonState = JsonConvert.SerializeObject(stateRequset);
147 StringContent strState = new StringContent(jsonState, Encoding.UTF8, "application/json");
148 requestColseJob.Content = strState;
149 HttpResponseMessage responseClose = new HttpResponseMessage();
150
151 try
152 {
153 responseClose = await closeClient.SendAsync(requestColseJob);
154 String responseCloseString = await responseClose.Content.ReadAsStringAsync();
155 Console.WriteLine("Close Job ", responseClose.IsSuccessStatusCode);
156 }
157 catch (Exception exx)
158 {
159 Console.WriteLine(exx.Message);
160 }
161 }
162 }
163}