locked
Data inserted and System.NullReferenceException error message on ViewModel class

    Question

  • Hi All,

    I am development an Windows Store app using c#, EF code first and Azure .Net Backend. I created ViewlModel class as MVVM pattern to helps separate application logic from presentation. So good so far, but I really don't understanding why I am getting this error message "System.NullReferenceException" after submitted data. If I checked the database I could see the data inserted correctly.

    Does someone could help me understand why I'm getting this error? Thanks.

    MainPage.xaml.cs

    public sealed partial class MainPage : Page
        {
            MyWindows8AppViewModel viewModel = new MyWindows8AppViewModel(App.MobileService);
    
            public MainPage()
            {
                this.InitializeComponent();
                this.DataContext = viewModel;
            }
    
            protected override async void OnNavigatedTo(NavigationEventArgs args)
            {
                await viewModel.GetAllAcessosAsync();
    
                if (viewModel.Acessos.Count > 0)
                {
                    AcessosListBox.SelectedIndex = 0;
                }
            }
    
            private async void btnAddFuncionario_Click(object sender, RoutedEventArgs e)
            {
                var id = Guid.NewGuid().ToString(); 
    
                //Acesso
                var acesso = new Acesso
                {
                    Id = id,
                    Usuario = txtUsuario.Text,
                    Senha = txtSenha.Text
    
                };
                
                
                //Funcionario
    
                var func = new Funcionario
                {
    
                    Id = id,
                    Nome = txtNome.Text,
                    RE = Convert.ToInt32(txtRE.Text),
                    Acesso = acesso
                    
                };
    
                //Here I received the error message
                await viewModel.AddFuncionarioAsync(func);
    
            }
        }

    ViewModel class

    public class MyWindows8AppViewModel : INotifyPropertyChanged
        {
            MobileServiceClient _client;
    
            public MyWindows8AppViewModel(MobileServiceClient client) 
            {
                _client = client;
    
            }
    
            // New code:
            // INotifyPropertyChanged implementation
            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void NotifyPropertyChanged(string propertyName)      
            {
                var handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this,
                        new PropertyChangedEventArgs(propertyName));
                }
            }
    
            
            private MobileServiceCollection<Acesso, Acesso> _acessos;
            public MobileServiceCollection<Acesso, Acesso> Acessos
            {
                get { return _acessos; }
                set 
                { 
                    _acessos = value;
                    NotifyPropertyChanged("Acessos"); 
                }
            }
    
            private MobileServiceCollection<Funcionario, Funcionario> _funcionarios;
            public MobileServiceCollection<Funcionario, Funcionario> Funcionarios
            {
                get { return _funcionarios; }
                set 
                {
                    _funcionarios = value;
                    NotifyPropertyChanged("Funcionarios"); 
                }
            }
    
            private bool _IsPending;
            public bool IsPending
            {
                get { return _IsPending; }
                set
                {
                    _IsPending = value;
                    NotifyPropertyChanged("IsPending");
                }
            }
    
            private string _ErrorMessage = "";
            public string ErrorMessage
            {
                get { return _ErrorMessage; }
                set
                {
                    _ErrorMessage = value;
                    NotifyPropertyChanged("ErrorMessage");
                }
            }        
    
    
            
            public async Task AddFuncionarioAsync(Funcionario funcionario)
            {
                IsPending = true;
                ErrorMessage = null;
    
                try
                {
                    IMobileServiceTable<Funcionario> tableFuncionario = _client.GetTable<Funcionario>();
                    await tableFuncionario.InsertAsync(funcionario);
                    Funcionarios.Add(funcionario); 
                    
                }
                catch (MobileServiceInvalidOperationException ex1)
                {
    
                    ErrorMessage = ex1.Message;
                }
                catch (HttpRequestException ex2)
                {
    
                    ErrorMessage = ex2.Message;
                }
                finally
                {
                    IsPending = false;
                }
            }
    
            public async Task GetAllAcessosAsync()
            {
                IsPending = true;
                ErrorMessage = "";
    
                try
                {
                    IMobileServiceTable<Acesso> table = _client.GetTable<Acesso>();
                    Acessos = await table.OrderBy(x => x.Usuario).ToCollectionAsync();
                }
                catch (MobileServiceInvalidOperationException ex)
                {
                    ErrorMessage = ex.Message;
                }
                catch (HttpRequestException ex2)
                {
                    ErrorMessage = ex2.Message;
                }
                finally
                {
                    IsPending = false;
                }
            }
    
    
        }

    DataObjects

    public class Acesso
        {
            public string Id { get; set; }
            public string Usuario { get; set; }
            public string Senha { get; set; }
        }
    
    public class Funcionario
        {
            public string Id { get; set; }
            public int RE { get; set; }
            public string Nome { get; set; }
    
            public virtual Acesso Acesso { get; set; }
        }
    }

    Tuesday, February 24, 2015 5:29 AM

Answers

  • Hi Fabio,

    I am not familiar with Azure programming, so I try replacing GetAllAcessosAsync method to use local data. You can see the following code snippet. When I run the project, it throw exception to say the Acessos property is null reference.

    Please try init it in MyWindows8AppViewModel constructor like the following.

    Acessos=new MobileServiceCollection<Acesso,Acesso>( new IMobileServiceTableQuery<Acesso>)

    I don’t know how to create an instance of the IMobileServiceTableQuery interface, so you need do it by yourself.

    Try and let me know the result.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Sunday, March 01, 2015 5:03 AM
    Moderator

All replies

  • Hi Fabio,

    Per my understanding, this issue may be caused by the Acesso property in Funcionario class. I found that you’ve not initialized that property. Try use the following code, test it and let me know the result.

    public class Funcionario
    
        {
    
            public string Id { get; set; }
    
            public int RE { get; set; }
    
            public string Nome { get; set; }
    
    
            public virtual Acesso Acesso { get; set; }
    
    
            public Funcionario()
    
            {
    
                Acesso = new Acesso();
    
            }
    
    }
    

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate the survey.

    Wednesday, February 25, 2015 2:03 AM
    Moderator
  • Dear Herro Wong,

    I did what you said but nothing change in my project. When I run as debug mode after I clicked button the code stopped saying System.NullReferenceException error.

    I've tried initialize all my properties, class and etc. I removed null value from local parameter even so, when I run the project, I got the same error message.

    I don't know that to do next. If do you get some insight about it, please let me know.

    Thanks.

    Thursday, February 26, 2015 2:13 AM
  • Hi Fabio,

    Can you try making a mini repro project about this issue? I need code snippet to look into it and know how to fix this. Use your OneDrive and share a link here.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate the survey.

    Thursday, February 26, 2015 2:46 AM
    Moderator
  • Sure I can Herro. Please access it by clicking on this ondrive short link http://1drv.ms/1vEagkz

    There, you'll find the full Windows Store App project and also the .Net Azure Mobile Service Backend running locally.

    Once again thank you in advanced for your help.

     
    Friday, February 27, 2015 2:25 AM
  • Hi Fabio,

    I am not familiar with Azure programming, so I try replacing GetAllAcessosAsync method to use local data. You can see the following code snippet. When I run the project, it throw exception to say the Acessos property is null reference.

    Please try init it in MyWindows8AppViewModel constructor like the following.

    Acessos=new MobileServiceCollection<Acesso,Acesso>( new IMobileServiceTableQuery<Acesso>)

    I don’t know how to create an instance of the IMobileServiceTableQuery interface, so you need do it by yourself.

    Try and let me know the result.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Sunday, March 01, 2015 5:03 AM
    Moderator