What is happening:
I'm trying to seed my database with company details when I run Update-Database
. However, for some reason that I can't understand it would seem as if the code in my Seed
helper-method ignores when one of its helpers returns null
.
What I'm doing:
The idea is rather simple:
Iterate over a file with a bunch of identifiers and send a HttpWebRequest
to an API to get the details using the identier. Then parse the response to a Company
object.
However if it turns out that one of the identifiers don't exist in the API (if the Request.StatusCode != HttpStatusCode.Ok
) I return null
. Or if the surrounding try-catch
fails, I return null
.
IT SHOULD BE NOTED THAT I KNOW THAT THE FIRST IDENTIFIER IN MY LIST RETURNS A NON-OK STATUSCODE!
The Problem:
The null
is never caught in my calling code (the first snippet bellow), so it would seem as if it is attempting to parse the empty JObject
, which gives me this error message:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Calling Code:
string[] symbols = Resources.Fixed_lines.Split(' ');
int stockId = 1;
foreach(var symbol in symbols)
{
var stockData = GetStockDataFromSymbol(symbol);
if (stockData != null)
{
var json = JObject.Parse(stockData);
var stock = new Company()
{
StockId = stockId,
Name = json["datatable"]["data"][0][1].ToString(),
Description = json["datatable"]["data"][0][0].ToString(),
Symbol = symbol
};
_context.Stocks.Add(stock);
stockId++;
} else
{
continue;
}
}
_context.SaveChanges();
The HttpWebRequest
helper:
private string GetStockDataFromSymbol(string symbol)
{
try
{
string url = string.Format("https://www.quandl.com/api/v3/datatables/ZACKS/CP.json?" +
"qopts.columns[]=comp_desc&qopts.columns[]=comp_name&ticker={0}" +
"&api_key=myApiKey", symbol);
Debug.WriteLine(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.
Create(url);
request.Method = "Get";
request.KeepAlive = true;
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
return null;
}
string responseBody = string.Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseBody = sr.ReadToEnd();
}
return responseBody;
}
catch (Exception ex)
{
return null;
}
}