locked
system.nullreferenceexception RRS feed

  • Question

  • User-1634604574 posted

    controller

    Login

      public JsonResult Authenticate2(string username, string time, string password)
            {
                var result = false;
                string queryString = @"SELECT [Username],[Set_new_password],Language,series FROM [dbo].[Users] WHERE [Username] = @username  AND [Set_new_password] = @password";
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", password);
                    try
                    {
                        connection.Open();
    
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                result = true;
                                Session["Username"] = username;
                                //Session["time"] = time;
                                //Session["Password"] = password;
                                Session["Language"] = reader.GetString(2);
                                //Session["UserSeries"] = reader.GetString(3);
    
                                HttpCookie usercookie = new HttpCookie("user", username);
                                usercookie.Expires.AddDays(1);
                                Response.Cookies.Add(usercookie);
    
                                HttpCookie languagecookie = new HttpCookie("language", reader.GetString(2));
                                languagecookie.Expires.AddDays(1);
                                Response.Cookies.Add(languagecookie);
    
                                //HttpCookie timecookie = new HttpCookie("time_log", reader.GetString(4));
                                //timecookie.Expires.AddDays(1);
                                //Response.Cookies.Add(timecookie);
    
                                HttpCookie userseriescookie = new HttpCookie("user_series", reader.GetString(3));
                                userseriescookie.Expires.AddDays(1);
                                Response.Cookies.Add(userseriescookie);
    
                                //usercookie.Secure = true;
                                //languagecookie.Secure = true;
                                //userseriescookie.Secure = true;
    
                            }
                        }
                    }
    
                    catch (Exception)
                    {
    
                    }
    
                }
    
                return Json(result, JsonRequestBehavior.AllowGet);
    
            }



    view

    <script>
    
      function login() {
             //  clearTimeout(t);
    
                var data = {
                    username: $("#username").val(),
                    password: $("#password").val(),
                    time:new Date(),//$("#time").text(),
                };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Authenticate2", "Login")',
                    data: data,
                    dataType: "json",
    
                }).done(function (response) {
    
                    if (response != "") {
    
                        @*window.location.href = '@Url.Action("Main", "Main")';
                        $("#im_green").show()
                        $("#im_blue").hide()
                        $("#im_red").hide()
                        $('#p_sign_in').text("Success")*@
    
    //--------------------------------------------------------------------
                        $.ajax({
                            type: "POST",
                            url: "/Login/Update_Time_Current_User",
                            data: {
                                time:new Date(),//$("#time").text(),
                                username: $("#username").val(),
                            },
                            success: function (data) {
    
                            }
                        }).done(function () {
    
                              $.ajax({
                            type: "POST",
                            url: "/Login/Authenticate4",
                            data: {
                                   username: $("#username").val(),
                    password: $("#password").val(),
                            },
                            success: function (data) {
                              
                            }
                              }).done(function () {
                                  
                        window.location.href = '@Url.Action("Main", "Main")';
                        $("#im_green").show()
                        $("#im_blue").hide()
                        $("#im_red").hide()
                        $('#p_sign_in').text("Success")
                              })
                        })
    //-----------------------------------------------------------------
    
                    }
                    else {
    
                        $('#p_sign_in').text("Invalid Username or Password");
                        $("#im_red").show()
                        $("#im_blue").hide()
    
                        $("#div_login").show()
                        $("#load_image").hide()
                    }
                });
        }
    //----------------------------------------------------
            $("#sign_in").on("click", function () {
    
                login()
    
    
                 });//closing sign in button
    
                $(document).keypress(function (e) { if (e.keyCode === 13) { login() } });
    
    
    </script>

    sometimes i get this error when main view is opening

    system.nullReferenceException: object reference not set to an instance of an object

    system.web.HttpCookieCollection.this[string].get returned nuu

    Wednesday, April 22, 2020 9:00 AM

All replies

  • User753101303 posted

    Hi,

    See https://blog.elmah.io/debugging-system-nullreferenceexception-object-reference-not-set-to-an-instance-of-an-object/

    Here the code you show seems to hide any exception that could happen. Do you have a global exception handler that would use Response.Write(ex.Message) to write an exception message (as well as a trace message) to the browser?

    Usually you don't send detailed error messages to the browser and you log full details to include the "at MyNamespace.MyMethod" part which allows to know for sure in which method it happens.

    Wednesday, April 22, 2020 10:17 AM
  • User-1634604574 posted

    when i open this page

      public ActionResult Main()
            {
    
                if (Request.Cookies["user"] == null)
                {
                    return RedirectToAction("Login", "Login");
                }
    
    
                if (Request.Cookies["language"] != null)
                {
                    if (Request.Cookies["language"].Value == "Arabic")
                    {
    
    
                        Thread.CurrentThread.CurrentCulture = new CultureInfo("ar".ToString());
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar".ToString());
                    }
    
                    if (Request.Cookies["language"].Value == "English")
                    {
    
    
                        Thread.CurrentThread.CurrentCulture = new CultureInfo("en".ToString());
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en".ToString());
                    }
                }
               
    
                return View();
    
            }

    Wednesday, April 22, 2020 12:24 PM
  • User1120430333 posted

    Why do you have a try/catch in your code that's doing nothing? No exception is being caught in the catch resulting in an unhandled exception. So why even have a try/catch if it's doing nothing? You could remove it. You can simply remove all try/catches from your code that makes all exceptions thrown unhandled making them catchable by the global exception handler you have implemented.

    https://stackify.com/csharp-catch-all-exceptions/

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    I use the concept but with some slight adjustments. All controllers inherit the Basecontroller and the unhandled exception is caught. Also if you log the stacktracke, it will give the method and the line number in the code the exception occurred. 

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVC.Controllers
    {
        public class HomeController : BaseController
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Error()
            {
                //  var feature = this.HttpContext.f.Features.Get<IExceptionHandlerFeature>();
                return View("~/Views/Shared/Error.cshtml", null);
            }
        }
    }
    using System.Web.Mvc;
    using MVC.Models;
    
    namespace MVC.Controllers
    {
        [Authorize]
        public class StudentsController : BaseController  
        {
            private IStudentModels studmods;
            public StudentsController(IStudentModels studentModels)
            {
                studmods = studentModels;
            }
    
            // GET: Students
    
            [AllowAnonymous]
            public ActionResult Index()
            {
                return View(studmods.GetStudents());
            }
    
            //[AllowAnonymous]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(studmods.GetStudentById(id));
            }
            public ActionResult Create()
            {
                return View(studmods.Create());
            }
    
            [HttpPost]
            public ActionResult Create(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Create(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
    
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(studmods.Edit(id));
            }
    
            [HttpPost]
            public ActionResult Edit(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Edit(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
    
            public ActionResult Delete(int id = 0 )
            {
                if (id > 0) studmods.Delete(id);
                
                return RedirectToAction("Index");
             }
        }
    }
    namespace MVC
    {
        using System;
    
        public class AppException : Exception
        {
            public AppException(String message) : base(message)
            { }
    
            public string Type { get; set; }
            public string StackTrace { get; set; }
            public string InnerException { get; set; }
            public AppException(String message, Exception inner) : base(message, inner) { }
        }
    
    }



    Thursday, April 23, 2020 12:26 AM