locked
NullReferenceException RRS feed

  • Question

  • Hello. I'm trying to understand why I keep getting a NullReferenceException on this line. It is underlined. Any help would be greatly appeciated,


    PCRider

    Here's the code
     public void SearchForMusic(string keyword, int Page)
    {
    //added by mayank arora 20th sep 2009

    string strTitle = "";
    this.Cursor = Cursors.Default;

    statusLabel.Text = "";

    //---clears the controls---

    lstMusic.Items.Clear();

    cboPage.Items.Clear();

    //---shows the Hourglass cursor---

    Cursor.Current = Cursors.WaitCursor;

    //---communicates with ECS---

    //Check to make sure the Combobox isnt empty

    try
    {

    if (cboPage.Text != null & txtKeywords.Text != null)
    {


    Convert.ToInt32(cboPage.Text);
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.ToString());


    cboPage.Text = "1";
    }

    GetMusicInformation(keyword, Convert.ToInt32(cboPage.Text));

    if (strTitle == null) return;


    try
    {

    nested = true;
    for (int i = 0; i <= amazonItems.Length - 1; i++)
    {

    {

    lstMusic.Items.Add(amazonItems[i].ItemAttributes.Title);

    }
    }

    //Clear items in cboPages

    cboPage.Items.Clear();

    cboPage.ResetText();
    for (int i = 1; i <= Convert.ToInt32(amazonResponse.Items[0].TotalPages); i++)
    {


    cboPage.Items.Add(i);
    }

    if (Page == 1)
    {


    cboPage.SelectedIndex = 0;
    }
    else
    {


    cboPage.SelectedIndex = Convert.ToInt32(Page) - 1;
    }

    nested = false;
    }
    catch (Exception ex)
    {


    MessageBox.Show(ex.ToString());
    }
    finally
    {


    Cursor.Current = Cursors.Default;

    }
    }


    private void DisplayError(string message)
    {

    statusLabel.Text = "Error:" + message;

    }


    private bool nested = false;
    private void cboPage_SelectedIndexChanged(System.Object sender, System.EventArgs e)
    {

    // if event occured by code, returns immadiatly

    if (nested)
    {
    return;
    }

    nested = true;

    SearchForMusic(txtKeywords.Text, Convert.ToInt32(cboPage.Text));


    nested = false;
    }


    Wednesday, October 7, 2009 8:56 PM

Answers

  • Assigning null to amazonItems won't make it not null. Again, look at your code for GetMusicInformation. Here it is with all the stuff removed that we don't need to pay attention to (from your post 7 before this one):
    public void GetMusicInformation(string keyword, int Page) {
           ... some stuff ...
                try
                {
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                    RSAParameters RSAParams = RSA.ExportParameters(false);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
    
                  
                    AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                    BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                    service = new AWSECommerceServicePortTypeClient(basicBinding, new EndpointAddress("https://ecs.amazonaws.com/onca/soap?Service=AWSECommerceService"));
                    service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects\Ensembecs\X509\cert-DTNIRKQDAN36QOO44JTDKZUE6DSWVOHX.pem");
                    amazonResponse = service.ItemSearch(itemSearch);
                    if (service.ItemSearch(itemSearch) != null)
                    {
                        amazonResponse = service.ItemSearch(itemSearch);
                    }
                    else
                    {
                       MessageBox.Show ("Search returned no values.");
                       
                    }
                    if (amazonResponse != null)
                    {
    
    
                        amazonItems = amazonResponse.Items[0].Item;
                    }
                }
                catch (Exception ex)
                {
    
                    MessageBox.Show("No information returned by Amazon.com" + ex.ToString());
                }
                
            }
    Notice that your call to amazon is in the catch part of a try/catch? Unless your calls to the crypto provider raise an exception, you never get to the lines that try to retreive the information from Amazon.

    Ron Whittle - If the post is helpful or answers your question, please mark it as such.
    • Proposed as answer by liurong luo Wednesday, October 14, 2009 7:05 AM
    • Marked as answer by liurong luo Thursday, October 15, 2009 8:11 AM
    Thursday, October 8, 2009 11:50 PM

All replies

  • I don't see where you have declared and initialized amazonItems in this code. Arrays are initialized as null at the time of declaration, so if you are declaring and initializing it in your underlined code, then it has a value of null at that point. And null - 1 is a NullReferenceException.

    You need to declare and initialize amazonItems before you try to do math with it.


    Wednesday, October 7, 2009 9:09 PM

  •         I did it here.

    -PCRider
    public partial class frmSearch : Form
        {
            ItemSearchResponse amazonResponse = null;
            Item[] amazonItems = null;

            [STAThread]
            static void Main()
            {

     public void GetMusicInformation(string keyword, int Page)
            {

                ItemSearchRequest itemSearchRequest = new ItemSearchRequest();
                ItemSearch itemSearch = new ItemSearch();

                // In order to find information about an item we need at least one search request
                // This search request (and any others) is attached to a search
                // finally the search is submitted on a port and returns a response

                ItemSearchRequest request = new ItemSearchRequest();
                request.SearchIndex = "Music";                // we are looking for a CD's, DVD-A's, SACD's
                request.Keywords = txtKeywords.Text;               // Don’t forget this
                request.ItemPage = Page.ToString();        // lookup-information
                request.ResponseGroup = new string[] { "Large, Tracks" }; // we want to know everything


                // Create request-object
                ItemSearch search = new ItemSearch();
                search.AWSAccessKeyId = "1SJQTBA88CSSF5V1EAG2";
                search.Request = new ItemSearchRequest[] { request };
              
                // Invoke service method
                try
                {

                    //---invoke the Amazon.com web service
                    AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                    //added my mayank on 5th oct 2009
                    BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                    service = new AWSECommerceServicePortTypeClient(basicBinding, new EndpointAddress("https://ecs.amazonaws.com/onca/soap?Service=AWSECommerceService"));
                    service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects\Ensembecs\X509\cert-DTNIRKQDAN36QOO44JTDKZUE6DSWVOHX.pem");
                    //added my mayank on 5th oct 2009
                    amazonResponse = service.ItemSearch(itemSearch);

                    if (amazonResponse != null)
                    {


                        amazonItems = amazonResponse.Items[0].Item;
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show("No information returned by Amazon.com" + ex.ToString());
                }

                //AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                //AmazonWS.serv();
                //ItemLookupResponse response = service.ItemLookup(lookup);

                //// Determine if music was found
                //bool itemFound = ((response.Items[0].Item != null)
                //    && (response.Items[0].Item.Length > 0));
                //if (itemFound)
                //{
                //    Item currItem = response.Items[0].Item[0];

                //}
                //else
                //{
                //    return null;
                //}

              
            }
    Wednesday, October 7, 2009 9:28 PM
  • You assume that your method GetMusicInformation worked. If it doesn't work, then amazonItems is null, and you never check for that. This line

    amazonResponse = service.ItemSearch(itemSearch);

    could return null, and you'd never know.

    Ron Whittle - If the post is helpful or answers your question, please mark it as such.
    Wednesday, October 7, 2009 10:21 PM
  • Actually I don't think it did but I'm not sure how to fix that.

    -PCRider
    Wednesday, October 7, 2009 10:46 PM
  • Well, there are a couple ways you could do that. You could check in the GetMusicInformation method to make sure it has a result other than null or you can check when you try to assign amazonResponse the value of service.ItemSearch(itemSearch); like this:

    if (service.ItemSearch(itemSearch) != null)
    {
    amazonResponse = service.ItemSearch(itemSearch);
    }
    else
    {
    console.write("Search returned no values.");
    }


    Wednesday, October 7, 2009 11:07 PM
  • Here is where I placed the code. Yet I still get the nullreference

    -PCRider


      public void GetMusicInformation(string keyword, int Page)
            {
    
                ItemSearchRequest itemSearchRequest = new ItemSearchRequest();
                ItemSearch itemSearch = new ItemSearch();
    
                // In order to find information about an item we need at least one search request
                // This search request (and any others) is attached to a search
                // finally the search is submitted on a port and returns a response
    
                ItemSearchRequest request = new ItemSearchRequest();
                request.SearchIndex = "Music";                // we are looking for a CD's, DVD-A's, SACD's
                request.Keywords = txtKeywords.Text;               // Don’t forget this
                request.ItemPage = Page.ToString();        // lookup-information
                request.ResponseGroup = new string[] { "Large, Tracks" }; // we want to know everything
    
    
                // Create request-object
                ItemSearch search = new ItemSearch();
                search.AWSAccessKeyId = "1SJQTBA88CSSF5V1EAG2";
                search.Request = new ItemSearchRequest[] { request };
    
                
               
                // Invoke service method
                try
                {
                    //Create a new RSACryptoServiceProvider object.
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
    
    
                //    //Export the key information to an RSAParameters object.
                //    //Pass false to export the public key information or pass
                //    //true to export public and private key information.
                    RSAParameters RSAParams = RSA.ExportParameters(false);
    
    
                }
                catch (CryptographicException e)
                {
                //    //Catch this exception in case the encryption did
                //    //not succeed.
                    Console.WriteLine(e.Message);
    
                  
                    //---invoke the Amazon.com web service
                    AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                    //added my mayank on 5th oct 2009
                    BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                    service = new AWSECommerceServicePortTypeClient(basicBinding, new EndpointAddress("https://ecs.amazonaws.com/onca/soap?Service=AWSECommerceService"));
                    service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects\Ensembecs\X509\cert-DTNIRKQDAN36QOO44JTDKZUE6DSWVOHX.pem");
                    //added my mayank on 5th oct 2009
                    amazonResponse = service.ItemSearch(itemSearch);
                    if (service.ItemSearch(itemSearch) != null)
                    {
                        amazonResponse = service.ItemSearch(itemSearch);
                    }
                    else
                    {
                       MessageBox.Show ("Search returned no values.");
                       
                    }
                    if (amazonResponse != null)
                    {
    
    
                        amazonItems = amazonResponse.Items[0].Item;
                    }
                }
                catch (Exception ex)
                {
    
                    MessageBox.Show("No information returned by Amazon.com" + ex.ToString());
                }
                
                //AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                //AmazonWS.serv();
                //ItemLookupResponse response = service.ItemLookup(lookup);
    
                //// Determine if music was found
                //bool itemFound = ((response.Items[0].Item != null)
                //    && (response.Items[0].Item.Length > 0));
                //if (itemFound)
                //{
                //    Item currItem = response.Items[0].Item[0];
    
                //}
                //else
                //{
                //    return null;
                //}
               
    
               
            }
    

    • Edited by PCRider Thursday, October 8, 2009 12:02 AM Added Code
    Wednesday, October 7, 2009 11:46 PM
  • Here's the actual error being shown from the message box:

    System.NullReferenceException: Object reference not set to an instance of an object.

       at Ensembecs.frmSearch.SearchForMusic(String keyword, Int32 Page) in C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects\Ensembecs\Ensembecs\frmSearch.cs:line 195

    Thursday, October 8, 2009 1:24 AM
  • And which line is line 195?

    You do know that if this is the actual code, you only request info from Amazon when you have a crypto failure? The request is in the catch block of your crypto statements (which I'm not even sure why they are there, since you don't seem to use them).


    Ron Whittle - If the post is helpful or answers your question, please mark it as such.
    Thursday, October 8, 2009 5:30 AM
  • The text in bold is line 195




    -PCRider
    public void SearchForMusic(string keyword, int Page)
    {
    //added by mayank arora 20th sep 2009

    string strTitle = "";
    this.Cursor = Cursors.Default;

    statusLabel.Text = "";

    //---clears the controls---

    lstMusic.Items.Clear();

    cboPage.Items.Clear();

    //---shows the Hourglass cursor---

    Cursor.Current = Cursors.WaitCursor;

    //---communicates with ECS---

    //Check to make sure the Combobox isnt empty

    try
    {

    if (cboPage.Text != null & txtKeywords.Text != null)
    {


    Convert.ToInt32(cboPage.Text);
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.ToString());


    cboPage.Text = "1";
    }

    GetMusicInformation(keyword, Convert.ToInt32(cboPage.Text));

    if (strTitle == null) return;


    try
    {

    nested = true;
    for (int i = 0; i <= amazonItems.Length - 1; i++)
    {

    {

    lstMusic.Items.Add(amazonItems[i].ItemAttributes.Title);

    }
    }

    //Clear items in cboPages

    cboPage.Items.Clear();

    cboPage.ResetText();
    for (int i = 1; i <= Convert.ToInt32(amazonResponse.Items[0].TotalPages); i++)
    {


    cboPage.Items.Add(i);
    }

    if (Page == 1)
    {


    cboPage.SelectedIndex = 0;
    }
    else
    {


    cboPage.SelectedIndex = Convert.ToInt32(Page) - 1;
    }

    nested = false;
    }
    catch (Exception ex)
    {


    MessageBox.Show(ex.ToString());
    }
    finally
    {


    Cursor.Current = Cursors.Default;

    }
    }


    private void DisplayError(string message)
    {

    statusLabel.Text = "Error:" + message;

    }


    private bool nested = false;
    private void cboPage_SelectedIndexChanged(System.Object sender, System.EventArgs e)
    {

    // if event occured by code, returns immadiatly

    if (nested)
    {
    return;
    }

    nested = true;

    GetMusicInformation(txtKeywords.Text, Convert.ToInt32(cboPage.Text));


    nested = false;
    }
    Thursday, October 8, 2009 12:04 PM
  • Again, you are assuming that amazonResponse actually has data. You need to check it for null before you try to use it's members (Right before line 195 would probably be a good place).

    Ron Whittle - If the post is helpful or answers your question, please mark it as such.
    Thursday, October 8, 2009 2:07 PM
  • OK. I moved the code just above line 195 and it does not recognize service.
    If (service.ItemSearch(itemSearch) != null)
                    {
                        amazonResponse = service.ItemSearch(itemSearch);
                    }
                    else
                    {
                        MessageBox.Show("Search returned no values.");
    
                    }
      for (int i = 0; i <= amazonItems.Length - 1; i++)
                    {
    
                        {
    
                            lstMusic.Items.Add(amazonItems[i].ItemAttributes.Title);
    
                        }
                    }
    
                    //Clear items in cboPages
    
                    cboPage.Items.Clear();
    
                    cboPage.ResetText();
                    for (int i = 1; i <= Convert.ToInt32(amazonResponse.Items[0].TotalPages); i++)
                    {
    
    
                        cboPage.Items.Add(i);
                    }
    
                    if (Page == 1)
                    {
    
    
                        cboPage.SelectedIndex = 0;
                    }
                    else
                    {
    
    
                        cboPage.SelectedIndex = Convert.ToInt32(Page) - 1;
                    }
    
                    nested = false;
                }
                catch (Exception ex)
                {
    
    
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
    
    
                    Cursor.Current = Cursors.Default;
    
                }
            }
    Thursday, October 8, 2009 2:52 PM
  • Someone told me about initializing  amazonItems at line 20 which is this:
     Item[] amazonItems = null;
    I've tried to do it but doesn't seem to work.what's the best way to initialize amazonItems?

    -PCRider
    Thursday, October 8, 2009 9:17 PM
  • Assigning null to amazonItems won't make it not null. Again, look at your code for GetMusicInformation. Here it is with all the stuff removed that we don't need to pay attention to (from your post 7 before this one):
    public void GetMusicInformation(string keyword, int Page) {
           ... some stuff ...
                try
                {
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                    RSAParameters RSAParams = RSA.ExportParameters(false);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
    
                  
                    AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient();
                    BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                    service = new AWSECommerceServicePortTypeClient(basicBinding, new EndpointAddress("https://ecs.amazonaws.com/onca/soap?Service=AWSECommerceService"));
                    service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"C:\Documents and Settings\User\My Documents\Visual Studio 2008\Projects\Ensembecs\X509\cert-DTNIRKQDAN36QOO44JTDKZUE6DSWVOHX.pem");
                    amazonResponse = service.ItemSearch(itemSearch);
                    if (service.ItemSearch(itemSearch) != null)
                    {
                        amazonResponse = service.ItemSearch(itemSearch);
                    }
                    else
                    {
                       MessageBox.Show ("Search returned no values.");
                       
                    }
                    if (amazonResponse != null)
                    {
    
    
                        amazonItems = amazonResponse.Items[0].Item;
                    }
                }
                catch (Exception ex)
                {
    
                    MessageBox.Show("No information returned by Amazon.com" + ex.ToString());
                }
                
            }
    Notice that your call to amazon is in the catch part of a try/catch? Unless your calls to the crypto provider raise an exception, you never get to the lines that try to retreive the information from Amazon.

    Ron Whittle - If the post is helpful or answers your question, please mark it as such.
    • Proposed as answer by liurong luo Wednesday, October 14, 2009 7:05 AM
    • Marked as answer by liurong luo Thursday, October 15, 2009 8:11 AM
    Thursday, October 8, 2009 11:50 PM