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