Skip to content

Commit b50a9b3

Browse files
committed
Modifyng ApiClient for Large file downloads
1 parent c558868 commit b50a9b3

File tree

1 file changed

+170
-31
lines changed

1 file changed

+170
-31
lines changed

generator/cybersource-csharp-template/ApiClient.mustache

Lines changed: 170 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,83 @@ namespace {{packageName}}.Client
237237
return request;
238238
}
239239

240+
// Creates and sets up a HttpWebRequest for calls which needs response in a file format.
241+
private HttpWebRequest PrepareHttpWebRequest(
242+
String path, {{^netStandard}}RestSharp.{{/netStandard}}Method method, Dictionary<String, String> queryParams, Object postBody,
243+
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
244+
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
245+
String contentType)
246+
{
247+
// Change to path(Request Target) to be sent to Authentication SDK
248+
// Include Query Params in the Request target
249+
var firstQueryParam = true;
250+
foreach (var param in queryParams)
251+
{
252+
var key = param.Key;
253+
var val = param.Value;
254+
255+
if (!firstQueryParam)
256+
{
257+
path = path + "&" + key + "=" + val;
258+
}
259+
else
260+
{
261+
path = path + "?" + key + "=" + val;
262+
firstQueryParam = false;
263+
}
264+
}
265+
266+
//initiate a HttpWebRequest object
267+
HttpWebRequest requestT = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString("https://" + RestClient.BaseUrl.Host + path));
268+
requestT.UserAgent = Configuration.UserAgent;
269+
270+
if (Configuration.Proxy != null)
271+
{
272+
requestT.Proxy = Configuration.Proxy;
273+
}
274+
requestT.ContentType = contentType;
275+
276+
// add header parameter, if any
277+
// passed to this function
278+
foreach (var param in headerParams)
279+
{
280+
if (param.Key == "Accept")
281+
{
282+
requestT.Accept = param.Value;
283+
}
284+
else
285+
requestT.Headers.Add(param.Key, param.Value);
286+
}
287+
288+
//initiate the default authentication headers
289+
if (postBody == null)
290+
{
291+
CallAuthenticationHeaders(method.ToString(), path);
292+
}
293+
else
294+
{
295+
CallAuthenticationHeaders(method.ToString(), path, postBody.ToString());
296+
}
297+
298+
foreach (var param in Configuration.DefaultHeader)
299+
{
300+
if (param.Key == "Authorization")
301+
{
302+
requestT.Headers.Add("Authorization", string.Format("Bearer " + param.Value));
303+
}
304+
else if (param.Key == "Date")
305+
{
306+
requestT.Date = DateTime.Parse(param.Value);
307+
}
308+
else if (param.Key == "Host")
309+
{ }
310+
else
311+
requestT.Headers.Add(param.Key, param.Value);
312+
}
313+
314+
return requestT;
315+
}
316+
240317
/// <summary>
241318
/// Makes the HTTP request (Sync).
242319
/// </summary>
@@ -254,44 +331,106 @@ namespace {{packageName}}.Client
254331
String path, {{^netStandard}}RestSharp.{{/netStandard}}Method method, Dictionary<String, String> queryParams, Object postBody,
255332
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
256333
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
257-
String contentType)
334+
String contentType, bool downloadResponseAsFile = false)
258335
{
259-
var request = PrepareRequest(
260-
path, method, queryParams, postBody, headerParams, formParams, fileParams,
261-
pathParams, contentType);
336+
//declared separately to handle both regular call and download file calls
337+
int httpResponseStatusCode;
338+
IList<Parameter> httpResponseHeaders = null;
339+
string httpResponseData = string.Empty;
262340
263-
// set timeout
264-
RestClient.Timeout = Configuration.Timeout;
265-
// set user agent
266-
RestClient.UserAgent = Configuration.UserAgent;
267-
268-
RestClient.ClearHandlers();
341+
var response = new RestResponse();
269342
270-
if (Configuration.Proxy != null)
343+
//check if the Response is to be downloaded as a file, this value to be set by the calling API class
344+
if (!downloadResponseAsFile)
271345
{
272-
RestClient.Proxy = Configuration.Proxy;
273-
}
346+
var request = PrepareRequest(
347+
path, method, queryParams, postBody, headerParams, formParams, fileParams,
348+
pathParams, contentType);
349+
350+
// set timeout
351+
RestClient.Timeout = Configuration.Timeout;
352+
// set user agent
353+
RestClient.UserAgent = Configuration.UserAgent;
354+
355+
RestClient.ClearHandlers();
274356
275-
InterceptRequest(request);
276-
{{#netStandard}}
277-
var response = RestClient.Execute(request).Result;
278-
{{/netStandard}}
279-
{{^netStandard}}
280-
{{^supportsUWP}}
281-
var response = RestClient.Execute(request);
282-
{{/supportsUWP}}
283-
{{#supportsUWP}}
284-
// Using async method to perform sync call (uwp-only)
285-
var response = RestClient.ExecuteTaskAsync(request).Result;
286-
{{/supportsUWP}}
287-
{{/netStandard}}
288-
InterceptResponse(request, response);
357+
if (Configuration.Proxy != null)
358+
{
359+
RestClient.Proxy = Configuration.Proxy;
360+
}
361+
362+
InterceptRequest(request);
363+
{{#netStandard}}
364+
response = RestClient.Execute(request).Result;
365+
{{/netStandard}}
366+
{{^netStandard}}
367+
{{^supportsUWP}}
368+
response = RestClient.Execute(request);
369+
{{/supportsUWP}}
370+
{{#supportsUWP}}
371+
// Using async method to perform sync call (uwp-only)
372+
response = RestClient.ExecuteTaskAsync(request).Result;
373+
{{/supportsUWP}}
374+
{{/netStandard}}
375+
InterceptResponse(request, response);
289376

290-
Configuration.DefaultHeader.Clear();
377+
Configuration.DefaultHeader.Clear();
291378

292-
var httpResponseStatusCode = (int)response.StatusCode;
293-
var httpResponseHeaders = response.Headers;
294-
var httpResponseData = response.Content;
379+
httpResponseStatusCode = (int)response.StatusCode;
380+
httpResponseHeaders = response.Headers;
381+
httpResponseData = response.Content;
382+
}
383+
{
384+
//setting file name
385+
string downloadReponseFileName = path.Split('/')[path.Split('/').Length - 1] + "_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".csv";
386+
387+
//prepare a HttpWebRequest request object
388+
var requestT = PrepareHttpWebRequest(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
389+
390+
//getting the response stream using httpwebrequest
391+
HttpWebResponse responseT = (HttpWebResponse)requestT.GetResponse();
392+
using (Stream responseStream = responseT.GetResponseStream())
393+
{
394+
//setting high timeout to accomodate large files till 2GB, need to revisit for a dynamic approach
395+
responseStream.ReadTimeout = 8000000;
396+
responseStream.WriteTimeout = 9000000;
397+
using (Stream fileStream = File.OpenWrite(@downloadReponseFileName))
398+
{
399+
byte[] buffer = new byte[4096];
400+
int bytesRead = responseStream.Read(buffer, 0, 4096);
401+
while (bytesRead > 0)
402+
{
403+
fileStream.Write(buffer, 0, bytesRead);
404+
bytesRead = responseStream.Read(buffer, 0, 4096);
405+
}
406+
}
407+
}
408+
409+
httpResponseStatusCode = (int)responseT.StatusCode;
410+
httpResponseHeaders = new List<Parameter>();
411+
foreach (var header in responseT.Headers)
412+
{
413+
string[] headerValue = responseT.Headers.GetValues(header.ToString());
414+
httpResponseHeaders.Add(new Parameter(header.ToString(), String.Join(",", headerValue.ToArray()), ParameterType.HttpHeader));
415+
}
416+
417+
httpResponseData = "Custom Message: Response downloaded to file " + downloadReponseFileName;
418+
419+
//setting the generic RestResponse which is returned to the calling class
420+
response.StatusCode = responseT.StatusCode;
421+
if (responseT.StatusCode == HttpStatusCode.OK)
422+
{
423+
response.Content = "Custom Message: Response downloaded to file " + downloadReponseFileName;
424+
}
425+
else if (responseT.StatusCode == HttpStatusCode.NotFound)
426+
{
427+
response.Content = "Custom Message: The requested resource is not found. Please try again later.";
428+
}
429+
else
430+
{
431+
response.Content = responseT.StatusDescription;
432+
}
433+
}
295434

296435
Console.WriteLine($"\n");
297436
Console.WriteLine($"RESPONSE STATUS CODE: {httpResponseStatusCode}");

0 commit comments

Comments
 (0)