-7

Can someone please be kind enough as to tell us what is wrong with this code (The code below is happening in the same class called EntityNameBusinessLayer and we are using the C# ASP.NET MVC 5):

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.Http;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Globalization;

public HttpRequest Request { get; set; }
public HttpBrowserCapabilities Browser { get; set; }

public class Request { private HttpRequest request;

    public Request(HttpRequest request)
    {
        if(request.Browser == null)
        {

        }
        else
        {

        }
    }
}

public HttpBrowserCapabilities Browser { get; set; }

public  class ShogunTypeBusinessLayer
{

public string RetrieveUserBrowserDetails()
{               
    string browserSignature;
    HttpBrowserCapabilities browserCapabilities = Request.Browser;
    string typeBrowser = "Type : " + browserCapabilities.Type + " ";
    string nameBrowser = "Name = " + browserCapabilities.Browser + " ";
    string versionBrowser = "Version = " + browserCapabilities.Version + " ";
    string majorVersionBrowser = "Major Version = " + browserCapabilities.MajorVersion + " ";
    string minorVersionBrowser = "Minor Version = " + browserCapabilities.MinorVersion + " ";
    string browserCapabilitiesBrowser = "Platform = " + browserCapabilities.Platform + " ";
    string betaBrowser = "Is Beta = " + browserCapabilities.Beta + " ";
    string isCrawlerBrowser = "Is Crawler = " + browserCapabilities.Crawler +  " ";
    string isAOLBrowser = "Is AOL = " + browserCapabilities.AOL +  " ";
    string isWin16Browser = "Is Win16 = " + browserCapabilities.Win16 +  " ";
    string isWin32Browser = "Is Win32 = " + browserCapabilities.Win32 +  " ";
    string supportFramesBrowserStatus ="Supports Frames = " + browserCapabilities.Frames + " ";
    string supportTableBrowserStatus = "Supports Tables = " + browserCapabilities.Tables + " ";
    string supportCookiesBrowserStatus = "Supports Cookies = " + browserCapabilities.Cookies + " ";
    string supportVBScriptBrowserStatus = "Supports VB Script = " + browserCapabilities.VBScript + " ";
    string supportJavaScriptBrowserStatus = "Supports JavaScript = " + browserCapabilities.JavaScript + " ";
    string supportJavaAppletsBrowserStatus = "Supports Java Applets = " + browserCapabilities.JavaApplets + " ";
    string supportActiveXControlsBrowserStatus ="Supports ActiveX Controls = " + browserCapabilities.ActiveXControls + " ";
    string supportChannelDefinitionFormatBrowserStatus = "CDF = " + browserCapabilities.CDF + " ";

    browserSignature = typeBrowser + 
                       nameBrowser + 
                       versionBrowser + 
                       majorVersionBrowser + 
                       minorVersionBrowser + 
                       browserCapabilitiesBrowser + 
                       betaBrowser +
                       isCrawlerBrowser +
                       isAOLBrowser + 
                       isWin16Browser + 
                       isWin32Browser + 
                       supportFramesBrowserStatus + 
                       supportTableBrowserStatus +  
                       supportCookiesBrowserStatus + 
                       supportVBScriptBrowserStatus + 
                       supportJavaScriptBrowserStatus +  
                       supportJavaAppletsBrowserStatus + 
                       supportActiveXControlsBrowserStatus + 
                       supportChannelDefinitionFormatBrowserStatus;

    return browserSignature;
}

After execution we get the following exception. We are trying to save the appended string into a database to be able to determine what browser had done the insertion.

Description title: Object reference not set to an instance of an object

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 791: string browserSignature; Line 792: Line 793: HttpBrowserCapabilities browserCapabilities = Request.Browser; Line 794: Line 795: string typeBrowser = "Type : " + browserCapabilities.Type + " ";

Source File:

c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs    Line:  793 

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   censys.BusinessLayer.ShogunTypeBusinessLayer.RetrieveUserBrowserDetails() in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs:793
   censys.BusinessLayer.ShogunTypeBusinessLayer.AddShogunType(SHOGUN_TYPEda shogunType) in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs:1124
   censys.Controllers.ShogunTypeController.Create_Post() in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\Controllers\ShogunTypeController.cs:33
   lambda_method(Closure , ControllerBase , Object[] ) +101
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651532
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

The code for some reason it's not executing.

Iragi KNJ
  • 121
  • 2
  • 11
  • 4
    How is `Request` being set in this class? Seems like it is null / never set. – stephen.vakil Aug 18 '16 at 20:31
  • @stephen.vakil This is the line of the code on the top of the class public HttpRequest Request { get; set; } – Iragi KNJ Aug 18 '16 at 20:34
  • @MethodMan We have just applied your patch. I am running and testing the system again. Will let you know. – Iragi KNJ Aug 18 '16 at 20:36
  • you need to show all relevant code in regards to how variables , objects etc are declared and initialized in regards to this specifically `Request.Browser` – MethodMan Aug 18 '16 at 20:38
  • I have shared the entire code @MethodMan. Please look up in the question. All the code is there... Please advise. – Iragi KNJ Aug 18 '16 at 20:43
  • 1
    Nothing in the code seems to initialize the value of `Request` -- it is being declared but never set. Is this application using property-based Dependency Injection and perhaps not wiring up the dependency properly? – stephen.vakil Aug 18 '16 at 20:46
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mason Aug 18 '16 at 20:49
  • Okay @stephen.vakil how do I initialize the Request because even on MSDN I can hardly find the answer. Thanks for reply. – Iragi KNJ Aug 18 '16 at 20:49
  • 3
    `I have shared the entire code @MethodMan...` <= I do not think you have. This code will not compile as c# will not allow you to have methods and properties that are not defined in a class/type. Really you should have a class and that class should have a constructor and that constructor should take a `Request` instance as a parameter and execute a null value check in the constructor. Then make the Request property a private field. This will ensure that a caller will not get some hard to track down NRE at run time. – Igor Aug 18 '16 at 20:57
  • Thanks @mason, we are looking into the matter. I will keep you posted. – Iragi KNJ Aug 18 '16 at 20:57
  • None of the answers yo provided is working @mason in the link http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Iragi KNJ Aug 18 '16 at 21:32
  • Instead, I am getting this error. 'censys.BusinessLayer.ShogunTypeBusinessLayer' is a 'property' but it is used like a 'type'. When I INITIALIZE like some of you said. Request question = new Request(); This is how we initialized the Request variable. Now, I see only one outcome here – Iragi KNJ Aug 18 '16 at 21:38
  • Yes, they are. That is the canonical answer to your question. Once you understand what an NRE is you'll never have this question again. So read it again. – mason Aug 18 '16 at 21:39
  • One hint: you named your class `Request` but `System.Web.UI.Page` already has a [Request](https://msdn.microsoft.com/en-us/library/system.web.ui.page.request(v=vs.110).aspx) property. Don't name your things after common properties. – mason Aug 19 '16 at 01:10
  • @mason what is NRE then... All I am getting from Google or Bing is something called Non-Recurssive Engineering which has nothing to do with programming. Please spell out NRE. Thanks. – Iragi KNJ Aug 19 '16 at 01:11
  • `NRE=NullReferenceException`. It means you are trying to access an object off of something that doesn't exist. Easy recreation: `MyClass myObject = null; myObject.SomeProperty` will give you an NRE. The solution is simple: check if it's null before accessing a property off of it. Which is explained in the link I provided earlier. – mason Aug 19 '16 at 01:14
  • Thank you for the explanation, but I have 15+ years in Systems, so I am pretty knowledgeable. I wanted to know the meaning of NRE. Please tell me, with regard to your remark on System.Web.UI.Page, what is your suggestion. Remove the using System.Web.UI.Page; or @Igo, do we create a Request1 class as 'code'public class Request1 { public HttpBrowserCapabilities Browser { get; private set; } public Request(HttpRequest requester) { if(requester != null) requester.Browser = new HttpBrowserCapabilities(); } }'code' – Iragi KNJ Aug 19 '16 at 08:33
  • I undeleted my answer. As @mason said that existing question/answer on NRE will save you some time once you fully understand the whole thing and ensuring that there are guards in your type definitions against null values where there should be none will save you time in the future tracking down NREs. – Igor Aug 19 '16 at 09:07

1 Answers1

1

This code will not compile as c# will not allow you to have methods and properties that are not defined in a class/type. Really you need to have a class and that class should have a constructor and that constructor should take a Request instance as a parameter and execute a null value check in the constructor. Then make the Request property a private field. This will ensure that:

  1. That a caller will not get some hard to track down NRE at run time.
  2. The code fails early
  3. The requirements of the type are clear as you can't create a valid instance with a bad state (null value for Request)

Alternatively you could have the method take in a Request instance and have it check if the parameter is not null.

public class EntityNameBusinessLayer
{
    // private member, i left the naming the same but the usual convention for private members is camelcase and not pascal.
    private HttpRequest Request;

    // constructor
    public EntityNameBusinessLayer(HttpRequest request) {
        // check for null
        if(request == null)
            throw new ArgumentNullException("request");
        Request = request; // now the state of the instance is valid and it can be used by the caller
    }

    public string RetrieveUserBrowserDetails()
    { /*your code*/ }
}

Calling code in asp.net web forms

public class YourAspWebPage : System.Web.UI.Page {
    protected void Button_Click(object sender, EventArgs args) {
        var bl = new EntityNameBusinessLayer(this.Request);
        var result = bl.RetrieveUserBrowserDetails();
    }
}

Calling code in an Asp.net Mvc controller. Note that it is discouraged to use the type HttpRequest directly when you are working in Mvc. Instead use the type HttpRequestBase as it is easy to mock/fake for unit testing. See also How do I convert an HttpRequestBase into an HttpRequest object?, the 2nd answer by CountZero (one with the most votes).

public class YourController : System.Web.Mvc.Controller {
    public void SomeAction() {
        var bl = new EntityNameBusinessLayer(System.Web.HttpContext.Current.Request);
        var result = bl.RetrieveUserBrowserDetails();
    }
}
Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175
  • Okay @Igor, just by analyzing this code, I can say that it is neat. All the information has been noted. Appreciated. – Iragi KNJ Aug 19 '16 at 19:50