0

I took a look around before asking this and didn't find anything pertaining to this specifically, this error is easy to find when running in a local environment but not so much when the application is online. What I have is an online application that imports contacts. When I log in with IE, I can import no problem, however when I log in using Chrome, I get this type of error when I try to import contacts from Yahoo or Hotmail. Any idea's on why it works fine when using IE and not when using Chrome?

Stack Trace

    [NullReferenceException]: Object reference not set to an instance of an object.
at GSDataCollection.Home.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,     EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean     includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
[HttpUnhandledException]: Exception of type    'System.Web.HttpUnhandledException' was thrown.
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean     includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.home_aspx.ProcessRequest(HttpContext context)
at    System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.I   ExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&    completedSynchronously)

Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {         
        if(!IsPostBack)
        {
            #region Initilization

            string myName = Session["LoggedInUser"].ToString();
            ds = UC.GetMemberID(myName);

            Session["CurrentUserID"] = Convert.ToInt32(ds.Tables["Members"].Rows[0]["MemberID"].ToString());

            // Current Groups For User grid
            rgCurrentGroups.DataSource = UC.GetMemberGroups(Convert.ToInt32(Session["CurrentUserID"]));
            rgCurrentGroups.DataBind();

            // Add Contacts to Group grid
            rgAddContactsToGroups.DataSource = UC.GetMemberContactsForGrid(Convert.ToInt32(Session["CurrentUserID"]));
            rgAddContactsToGroups.DataBind();

            // Groups To Select
            ddGroupToSelect.DataSource = UC.GetMemberGroups(Convert.ToInt32(Session["CurrentUserID"]));
            ddGroupToSelect.DataTextField = "MemberGroupName";
            ddGroupToSelect.DataValueField = "MemberGroupsID";
            ddGroupToSelect.DataBind();

            #endregion

            #region Import Contacts
            //i.e. outlook
            if (Request.QueryString["code"] != null && Request.QueryString["state"] != null)
            {
                iOutlook io = new iOutlook();

                WebServerClient consumer = new WebServerClient(io.server, io.clientID, io.clientSecret);
                IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(null);

                string accessToken = grantedAccess.AccessToken;

                string returnStr = new System.Net.WebClient().DownloadString("https://apis.live.net/v5.0/me/contacts?access_token=" + accessToken);

                dynamic json = System.Web.Helpers.Json.Decode(returnStr);

                foreach (var item in json.data)
                {
                    Response.Write(item.name + "</br>" + item.emails.preferred + "</br>------------------------------</br>");
                }
            }

            //Yahoo
            string oauth_token = Request["oauth_token"];
            string oauth_verifier = Request["oauth_verifier"];

            //To Close open window opened by "Login with yahoo" button
            if (!string.IsNullOrEmpty(oauth_verifier) && oauth_verifier != "")
            {                    
                OauthToken = oauth_token;
                OauthVerifier = oauth_verifier;
                Page.ClientScript.RegisterStartupScript(GetType(), "refresh", "window.opener.location = 'home.aspx'; self.close();", true);
            }
            //This will load once we automatically close the login popup window by above if statement
            else if (!string.IsNullOrEmpty(OauthVerifier))
            {                 
                if (string.IsNullOrEmpty(OauthYahooGuid))
                    GetAccessToken(OauthToken, OauthVerifier);
                //RefreshToken();
                RetriveContacts();

                //need to set as empty because we don't need to repeat RetriveContacts() condition
                OauthVerifier = string.Empty;
            }
            #endregion
        }
    }
Chris
  • 2,953
  • 10
  • 48
  • 118
  • Why don't you show us what you've got and where the exception is thrown? – Stephen Jul 27 '15 at 20:55
  • You need to pinpoint the exact line where the exception occurs and then you could post your code here. The exception has a stack trace that tells you exactly where the malfunction occurs. (Better to use a debug version of your code) – Steve Jul 27 '15 at 20:56
  • No problem, I wasn't sure what I should have added. I'll edit and add it now – Chris Jul 27 '15 at 20:58
  • The error gets thrown on the redirect from hotmail and after you allow the application to access Yahoo – Chris Jul 27 '15 at 21:02
  • So the exception is thrown here: _GSDataCollection.Home.Page_Load_ what is the code of this Page_Load event? – Steve Jul 27 '15 at 21:04
  • @Steve, i editted and added – Chris Jul 27 '15 at 21:06
  • It is difficult for me to point exactly to a line that contains the error, However I am pretty sure that you need to code more defensively in many points. For example, you take for granted that there is a _Session[LoggedInUser]_ You are so sure of this that you apply immediately a ToString() to this variable. But what if there is no LoggedInUser? You get a null and converting a null to string will get you the error message. Of course if the browsers were coded identically this should not happen only in Chrome, but,,,, _if Session[LoggedInUser] != null_ will do no harm – Steve Jul 27 '15 at 21:12
  • 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) – Pierre-Luc Pineault Jul 27 '15 at 21:18
  • @Steve, i understand what you are saying about taking it for granted about the LoggedInUser, but I do know that there will always be one because you can't (hopefully) get to the Home.aspx page without logging in. But I will add the != null to it though and redirect back to the main page if it is null...Its just weird that it works perfectly fine in IE...I also get this Server Error in '/' Application above the stacktrace – Chris Jul 27 '15 at 21:29
  • @Chris I am not saying that this is your error. Probably not. I was just saying that there is a need to check if any reference variable used by your code is not null before using it. – Steve Jul 27 '15 at 21:33
  • @Steve, I know what you meant, its all good. I just tested in FireFox and its the same error. I think it might have to do with some other methods in the page load event that is dealing with the importing. – Chris Jul 27 '15 at 21:37

1 Answers1

2

It is probably that the session variable LoggedIn is still available in ie if you delete your cookies you will probably be able reproduce the error in IE as well.

You need to check for Null before using .ToString() or else it will throw this error. Try the code below and see if the problem is gone.

protected void Page_Load(object sender, EventArgs e)
{         
    if(!IsPostBack)
    {
        #region Initilization
        //Check for Null Session Variable
        if (Session["LoggedInUser"]) != null){

            string myName = Session["LoggedInUser"].ToString();

            ds = UC.GetMemberID(myName);
            //Check if the Table is empty
            if(ds.Tables.Contains("Members") && ds.Tables["Members"].Rows.Count > 0){

                Session["CurrentUserID"] = Convert.ToInt32(ds.Tables["Members"].Rows[0]["MemberID"].ToString());

                // Current Groups For User grid
                rgCurrentGroups.DataSource = UC.GetMemberGroups(Convert.ToInt32(Session["CurrentUserID"]));
                rgCurrentGroups.DataBind();

                // Add Contacts to Group grid
                rgAddContactsToGroups.DataSource = UC.GetMemberContactsForGrid(Convert.ToInt32(Session["CurrentUserID"]));
                rgAddContactsToGroups.DataBind();

                // Groups To Select
                ddGroupToSelect.DataSource = UC.GetMemberGroups(Convert.ToInt32(Session["CurrentUserID"]));
                ddGroupToSelect.DataTextField = "MemberGroupName";
                ddGroupToSelect.DataValueField = "MemberGroupsID";
                ddGroupToSelect.DataBind();
            }
        }
        #endregion

        #region Import Contacts
        //i.e. outlook
        if (Request.QueryString["code"] != null && Request.QueryString["state"] != null)
        {
            iOutlook io = new iOutlook();

            WebServerClient consumer = new WebServerClient(io.server, io.clientID, io.clientSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(null);

            string accessToken = grantedAccess.AccessToken;

            string returnStr = new System.Net.WebClient().DownloadString("https://apis.live.net/v5.0/me/contacts?access_token=" + accessToken);

            dynamic json = System.Web.Helpers.Json.Decode(returnStr);

            foreach (var item in json.data)
            {
                Response.Write(item.name + "</br>" + item.emails.preferred + "</br>------------------------------</br>");
            }
        }

        //Yahoo
        string oauth_token = Request["oauth_token"];
        string oauth_verifier = Request["oauth_verifier"];

        //To Close open window opened by "Login with yahoo" button
        if (!string.IsNullOrEmpty(oauth_verifier) && oauth_verifier != "")
        {                    
            OauthToken = oauth_token;
            OauthVerifier = oauth_verifier;
            Page.ClientScript.RegisterStartupScript(GetType(), "refresh", "window.opener.location = 'home.aspx'; self.close();", true);
        }
        //This will load once we automatically close the login popup window by above if statement
        else if (!string.IsNullOrEmpty(OauthVerifier))
        {                 
            if (string.IsNullOrEmpty(OauthYahooGuid))
                GetAccessToken(OauthToken, OauthVerifier);
            //RefreshToken();
            RetriveContacts();

            //need to set as empty because we don't need to repeat RetriveContacts() condition
            OauthVerifier = string.Empty;
        }
        #endregion
    }
}
EJD
  • 751
  • 6
  • 19
  • Hi, that stopped the error from happening but then the user logged in was no longer visible and the response.write wouldn't work. The reason I was using session to hold the user after the user logged in was because everytime I would do an import I was would lose the logged in user. I had asked this question http://stackoverflow.com/questions/31601933/logging-into-web-app-doesnt-always-show-that-im-logged-in?noredirect=1#comment51155230_31601933 So i came up with using Session to hold the user name – Chris Jul 29 '15 at 14:19
  • Then with the import of yahoo contacts, the yahoo popup didn't close on its own and just redirected to the home page in its popup window – Chris Jul 29 '15 at 14:21