1

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;
    }
}
geostocker
  • 1,190
  • 2
  • 17
  • 29
  • https://stackoverflow.com/q/20940979/447156 ? – Soner Gönül Jul 22 '17 at 14:30
  • Not sure if that really helps me. The problem I seem to face is more regarding the fact that the null doesn't seem to be found in the calling code, even though it should be returned by the called code. – geostocker Jul 22 '17 at 14:34
  • You have some hard coded indexes, like `json["datatable"]["data"][0][1]`. The error is saying that even though neither `stockData` nor `json` are null, one of the indexes you're referencing doesn't exist. Set a breakpoint on `var stock = new Company()` and check the value of `json`. – Rufus L Jul 22 '17 at 18:40

0 Answers0