Search code examples
c#asp.net-core.net-corevisual-studio-2019iis-express

Getting NullReferenceException on IIS Express while running from Visual Studio 2019


I am trying to do CRUD operation on a table from a database (Oracle18c hosted on remote server)- "Items" which has item and UnitWeight as columns. This is my first ASP.NET project. Just following a tutorial that I found online (https://www.c-sharpcorner.com/blogs/crud-operation-in-asp-net-core30-with-oracle-database2). I was able to follow the steps without any issue. But when I am trying to run the project in IIS Express I am getting following error in the picture. I am not sure what I am doing wrong.

enter image description here

I am giving my snippets below.

Items.cs [Models]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Models
{
public class Items
    {
    public string item { get; set; }
    public int unitWeight { get; set; }

    }
}

itemService.CS [Services]

using cs550.Interface;
using cs550.Models;
using Microsoft.Extensions.Configuration;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Services
{
    public class itemService : IItemService
    {
        private readonly string _connectionString;
        public itemService(IConfiguration _configuration)
        {
            _connectionString = _configuration.GetConnectionString("OracleDBConnection");
        }
        public IEnumerable<Items> getAllItem()
        {
            List<Items> itemList = new List<Items>();
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.BindByName = true;
                    cmd.CommandText = "Select item, unitWeight from Items";
                    OracleDataReader rdr = cmd.ExecuteReader();
                    while(rdr.Read())
                    {
                        Items item = new Items
                        {
                            item = rdr["item"].ToString(),
                            unitWeight = Convert.ToInt32(rdr["unitWeight"])

                        };
                        itemList.Add(item);
                    }
                }
            }
            return itemList;
        }

    public Items getItemByItem(string it)
    {
        Items items = new Items();
         using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                con.Open();
                cmd.BindByName = true;
                cmd.CommandText = "Select item, unitWeight from Items Where item="+it+"";
                OracleDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    items.item = rdr["item"].ToString();
                    items.unitWeight = Convert.ToInt32(rdr["unitWeight"]);
                }
            }

            return items;
        }
    }
    
    public void AddItems(Items it)
    {
        try
        {
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.CommandText = "Insert into Items(item, unitWeight) Values('"+it.item+"',"+it.unitWeight+")";
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    public void EditItems(Items it)
    {
        try
        {
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.CommandText = "Update Items Set unitWeight="+it.unitWeight+" where item='"+it.item+"'";
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}
}

IItemService.cs [Interface]

using cs550.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Interface
{
    public interface IItemService
    {
        IEnumerable<Items> getAllItem();
        Items getItemByItem(string it);

        void AddItems(Items it);

        public void EditItems(Items it);
    }
}

Strtup.CS

using cs550.Interface;
using cs550.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IItemService, itemService>();
        services.AddSingleton<IConfiguration>(Configuration);
        services.AddMvc().AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Items/Index", "");
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Items}/{action=Index}/{item?}");
        });
    }
}
}

appsetting.JSON

{
"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},
"ConnectionStrings": {
  "OracleDBConnection": "User Id=myUserID;Password=myPassword; Data Source= remoteURL:1521/DB"
},
"AllowedHosts": "*"
}

ItemController.cs

using cs550.Interface;
using cs550.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Controllers
{
    public class ItemsController : Controller
    {
        IItemService itemService;

        public ItemsController(IItemService _itemService)
        {
            itemService = _itemService;
        }

        public ActionResult Index()
        {
            IEnumerable<Items> items = itemService.getAllItem();
            return View();
        }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Items it)
    {
        itemService.AddItems(it);
        return RedirectToAction(nameof(Index));
    }

    public ActionResult Edit(string item)
    {
        Items it = itemService.getItemByItem(item);
        return View(it);
    }

    [HttpPost]
    public ActionResult Edit(Items it)
    {
        itemService.EditItems(it);
        return RedirectToAction(nameof(Index));
    }
}
}

My Razor Pages:

Index.cshtml

@model IEnumerable<cs550.Models.Items>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.item)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.unitWeight)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.item)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.unitWeight)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item  }) |
                @Html.ActionLink("Delete", "Delete", new {  id=item })
            </td>
        </tr>
}
    </tbody>
</table>

Create.cshtml

@model cs550.Models.Items

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Items</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="item" class="control-label"></label>
                <input asp-for="item" class="form-control" />
                <span asp-validation-for="item" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="unitWeight" class="control-label"></label>
                <input asp-for="unitWeight" class="form-control" />
                <span asp-validation-for="unitWeight" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Edit.cshtml

@model cs550.Models.Items

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Items</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="item" class="control-label"></label>
                <input asp-for="item" class="form-control" />
                <span asp-validation-for="item" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="unitWeight" class="control-label"></label>
                <input asp-for="unitWeight" class="form-control" />
                <span asp-validation-for="unitWeight" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Solution

  •     Change:
    
         using (OracleConnection con = new OracleConnection(_connectionString))
                {
                    using (OracleCommand cmd = new OracleCommand())
                    {
                    
    

    To:

          using(OracleConnection con = new OracleConnection(_connectionString))
         {  
                  using(OracleCommand cmd = con.CreateCommand())
                  {   
    

    You have to use PL/SQL text in your data reader, or you can create a stored procedure and use ref cursor to work with data

    Also change :

    public class itemController : Controller
    
    

    To

    public class ItemsController : Controller
    

    Change your action Index code:

     public ActionResult Index()
            {
                IEnumerable<Items> items = itemService.getAllItem();
                return View(items);
            }