Avatar of j_tipps
j_tipps
 asked on

C#.net Custom Control Login Check namespace

Hello,
I'm haveing a problem using a control class to verfify if someone is login and if not repsond correctly.
It can't seem to import the correct namespace for the User.Identity.IsAuthenticated.  
I'm using windows authentication.
I have read something about Page.User....no idea.

For now i have this code in regualer code behind files and it works fine.  I'm not trying to get all my reusable items together and since this is code would be in almost every page it was the first on my list :)

here is the code in the class that i'm haveing a namespace problem:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;

namespace VenderRisk
{

      public class Common
      {
            SqlConnection Conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            
            public Common()
            {
                  //
                  // TODO: Add constructor logic here
                  //
            }
            public bool CheckLog()
            {
                  DataTable UserTB = new DataTable();
                  bool HowAboutIt;
                  if ((User.Identity.IsAuthenticated) & (Request.Cookies["UserInfo"] != null))      
                  {
                        HowAboutIt = true;
                        return HowAboutIt;
                  }
                  else
                  {
                        
                        SqlCommand SelRoles = new SqlCommand("SELECT   Users.RecID, Users.NTLog, Users.Fname, Users.Lname, Users.Email, Users.Phone, Users.EmpID, Users.Role, LOB.LOBID FROM  Users INNER JOIN  LOB ON Users.LOB = LOB.LOBID WHERE  (NTLog = @ID)", Conn);
                        SqlParameter Userparam  = new SqlParameter();
                        Userparam.ParameterName = "@ID";
                        Userparam.Value = User.Identity.Name.ToString();
                        SelRoles.Parameters.Add(Userparam);
                        SqlDataAdapter  FillRoles = new SqlDataAdapter(SelRoles);
                        FillRoles.Fill(UserTB);
                        if (UserTB.Rows.Count > 0)
                        {
                              HttpCookie cook = new HttpCookie("UserInfo");
                              cook.Values.Add("UserRole",UserTB.Rows[0]["Role"].ToString());
                              cook.Values.Add("LOBID", UserTB.Rows[0]["LOBID"].ToString());
                              cook.Values.Add("UserID", UserTB.Rows[0]["RecID"].ToString());
                              cook.Expires = DateTime.Now + TimeSpan.FromDays(1);
                              Response.Cookies.Add(cook);
                        }
                        else
                        {
                              Response.Redirect("http://" + Request.ServerVariables["http_host"] + "/VenderRisk/AddUsers.aspx");
                        }
                  }
            }
      }
}

Whats going on?  why wont it work? it has the correct namespace and then some!
I'm also haveing a problem with Request and Response namespaces.
I think i'm just miss understanding something.
Thanks for any help.
.NET Programming

Avatar of undefined
Last Comment
j_tipps

8/22/2022 - Mon
j_tipps

ASKER
sorry, here is the updated namespace list i'm importing

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
using System.Security.Principal;
using System.Security;
j_tipps

ASKER
Maybe i wasn't clear with my last two posting.  Let me try again.
I'll creating a "Common.cs" file to hold all my reuseable code. i.e. checking to see if a user is loged in.
The production code behind files currenlty have there own copy of the code to check users loged in.
Then I move one copy of that code into my "Common.cs" file and do a rebuild it gives me a namespace error on "User" , "Request", "Response"

These are the name spaces have in my "Common.cs" file:  
I have more then needed.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
using System.Security.Principal;
using System.Security;

This is my code for "Common.cs" File
namespace VenderRisk
{

     public class Common
     {
          SqlConnection Conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
         
          public Common()
          {
               //
               // TODO: Add constructor logic here
               //
          }
          public bool CheckLog()
          {
               DataTable UserTB = new DataTable();
               bool HowAboutIt;
               if ((    HERE IS NAMESPACE ERROR --->User.Identity.IsAuthenticated<----NAMESPACE ERROR) & (Request.Cookies["UserInfo"] != null))    
               {
                    HowAboutIt = true;
                    return HowAboutIt;
               }
               else
               {
                   
                    SqlCommand SelRoles = new SqlCommand("SELECT   Users.RecID, Users.NTLog, Users.Fname, Users.Lname, Users.Email, Users.Phone, Users.EmpID, Users.Role, LOB.LOBID FROM  Users INNER JOIN  LOB ON Users.LOB = LOB.LOBID WHERE  (NTLog = @ID)", Conn);
                    SqlParameter Userparam  = new SqlParameter();
                    Userparam.ParameterName = "@ID";
                    Userparam.Value = User.Identity.Name.ToString();
                    SelRoles.Parameters.Add(Userparam);
                    SqlDataAdapter  FillRoles = new SqlDataAdapter(SelRoles);
                    FillRoles.Fill(UserTB);
                    if (UserTB.Rows.Count > 0)
                    {
                         HttpCookie cook = new HttpCookie("UserInfo");
                         cook.Values.Add("UserRole",UserTB.Rows[0]["Role"].ToString());
                         cook.Values.Add("LOBID", UserTB.Rows[0]["LOBID"].ToString());
                         cook.Values.Add("UserID", UserTB.Rows[0]["RecID"].ToString());
                         cook.Expires = DateTime.Now + TimeSpan.FromDays(1);
                       HERE IS NAMESPACE ERROR --->  Response.Cookies.Add(cook);
                    }
                    else
                    {
                 HERE IS NAMESPACE ERROR --->        Response.Redirect("http://" + Request.ServerVariables["http_host"] + "/VenderRisk/AddUsers.aspx");
                    }
               }
          }
     }
}


Since it never gets past the build I can't create a new "Common" object to test further.
I hope that clears things up... if there was any confusion in the first place.
Thanks again, this one seems kinda weird.
sumo_the_cat

I haven't read your code properly (caught this Q from an old one of mine that you just posted in) - but making a "Common" class isn't necessarily the right way to do things. All your classes should be objects, which should be abstractions. But anyway, it looks like you have just got one public method, so it's maybe not that important...

Are you using webforms or winforms?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
sumo_the_cat

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
j_tipps

ASKER
webforms and its c#
the code just pulls the domain and user name from User.Identity.Name , checks the database and if it finds a user it makes a cookie and if it doens't then it redirects to the add user page.

I thought that classes where objects ??  Whats the differents in a class and an object?  I'm used to using VB
Thanks for the help
j_tipps

ASKER
OK Great, i missed that part.  I changed the common class to inherit from System.Web.UI.Page too and it does a build fine.
Thanks again but i still have a question how can i not just import that System.Web.UI.Page namespace?? why does it have to inherit from that.
j_tipps

ASKER
typed to fast, as per usual hehe. the question was supposed to say.
Why can't i just import the System.Web.UI.Page namespace.  
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
sumo_the_cat

ok, if that works then cool, but your common class is now effectively a "page"! you basically need to look into object-oriented stuff, and it's a topic too big for an EE question! It took me a while, and i still know little.. pete
sumo_the_cat

importing/using is really just a way of typing less. it doesn't do anything (so far as i know). inheriting from another class means that the class gets all the behavour, properties, methods of that parent class. Look on the web for the disctinction between class and object, inheritance etc...

Glad that it now compiles though...(does it actually work as you'd expect??) I still haven't read your code properly.
j_tipps

ASKER
well...it doesn't work haha.
the error - Request is not available in this context - on line 37
Line 37 is --  if ((User.Identity.IsAuthenticated) & (Request.Cookies["UserInfo"] != null))      

HERE IS THE COMMON.CS FILE CODE:

using System;
using System.Data;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;


namespace VenderRisk
{
      /// <summary>
      /// Summary description for Common.
      /// </summary>
      public class Common : System.Web.UI.Page
      {
            SqlConnection Conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            
            public Common()
            {
                  //
                  // TODO: Add constructor logic here
                  //
            }
            public bool CheckLog()
            {
                  DataTable UserTB = new DataTable();
                  bool HowAboutIt;
LINE 37----->            if ((User.Identity.IsAuthenticated) & (Request.Cookies["UserInfo"] != null))      
                  {
                        HowAboutIt = true;
                        return HowAboutIt;
                  }
                  else
                  {
                        
                        SqlCommand SelRoles = new SqlCommand("SELECT   Users.RecID, Users.NTLog, Users.Fname, Users.Lname, Users.Email, Users.Phone, Users.EmpID, Users.Role, LOB.LOBID FROM  Users INNER JOIN  LOB ON Users.LOB = LOB.LOBID WHERE  (NTLog = @ID)", Conn);
                        SqlParameter Userparam  = new SqlParameter();
                        Userparam.ParameterName = "@ID";
                        Userparam.Value = User.Identity.Name.ToString();
                        SelRoles.Parameters.Add(Userparam);
                        SqlDataAdapter  FillRoles = new SqlDataAdapter(SelRoles);
                        FillRoles.Fill(UserTB);
                        if (UserTB.Rows.Count > 0)
                        {
                              HttpCookie cook = new HttpCookie("UserInfo");
                              cook.Values.Add("UserRole",UserTB.Rows[0]["Role"].ToString());
                              cook.Values.Add("LOBID", UserTB.Rows[0]["LOBID"].ToString());
                              cook.Values.Add("UserID", UserTB.Rows[0]["RecID"].ToString());
                              cook.Expires = DateTime.Now + TimeSpan.FromDays(1);
                              Response.Cookies.Add(cook);
                              HowAboutIt = true;
                              return HowAboutIt;
                        }
                        else
                        {
                  //Response.Redirect("http://" + Request.ServerVariables["http_host"] + "/VenderRisk/AddUsers.aspx");
                           HowAboutIt = false;
                           return HowAboutIt;
                        }
                  }
            }
      }

}

HERE IS THE CODE BEHIND FILE :
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace VenderRisk
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.RadioButtonList RadioButtonList1;
      
            private void Page_Load(object sender, System.EventArgs e)
            {
                           Common UseThis = new Common();
                  bool CheckUser = UseThis.CheckLog();
                  if(CheckUser != true)
                  {
                  Response.Redirect("http://" + Request.ServerVariables["http_host"] + "/VenderRisk/AddUsers.aspx");;
                  }
            }

Should the Code Behind inherit from the Common.cs file?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
sumo_the_cat

BTW, a better way of doing this would perhaps to create an inheritance chain like this:

System.Web.UI.Page
\/
YourApp.Common
\/
YourApp.ParticularWebPage

I do something similr with my pages to get a common look and feel, and to place an identical header and footeron the page, etc. So your common page "builds" on the standard web page, and that is built on by you individual pages.

Good luck,
Pete.
sumo_the_cat

Can I just ask what you're trying to do exactly? the .net framework has stuff in it to deal with forms authentication etc.
j_tipps

ASKER
I'm grabing the NT-Login information then running it past a database to see if the user already has account.
if not then it should post them to the new user page. If the user has an account then get there ID, LOB and Role from the DB and puts into a cookie called "UserInfo".

Flow is like this:

On page load of each page i have to check two things.
1. if the user is even loged into domain--User.Identity.IsAuthenticated
2. if the user has a cookie called userinfo yet -- Request.Cookies["UserInfo"] != null)

If both these together is true then load the page, all good--
   
       if not grab the nt-login ID and hit the database looking for user

              if user is found then write cookie and load page

              if user is not found redirect to the add new user page where the user can add themselfs.

I have to run that code on every page so instead of puting in each code behine file i would like it to be in one spot and just called from the code behinds.
I thought i was on the right track for that, maybe not
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
hismightiness

Hey j_tipps...

You are calling the User context from an external class, where it is not readily available, even though you are inheriting the Page class.  I will say that it is not a good idea to inherit the page class unless you REALLY need all the members that it encompasses.  You are using way too much overhead.  You should instead Import the NameSpaces that you KNOW you need to utlilize.  Also, if you are importing a NameSpace to use it just once or twice in the class, then just write the whole thing out.  There is no need to import it if unless you are (1) referencing it often, or (2) need more than one or two members of the NameSpace.

Try referencing the current context to solve your current problem:

HttpContext.Current.User.Identity.IsAuthenticated
sumo_the_cat

I agree wholeheartedly! The get rid of the inheritance for now (but learn about OOP because it's incredibly cool).

You also seem to want to transfer to another page from this common class - try Server.Transfer(Request.ApplicationPath + "AddUserPage.aspx");

Or can he get the Response class from here, mighty?
sumo_the_cat

The other thing to say is: why can't you just put this in in the Glabal.asax? (Application_AuthenticateRequest). Surely the way you're doing it requires that on every web page you call the public method CheckLog? this is unecessary, and perhaps a security risk if you forget to put a check in a page. This would perhaps solve all your problems (and more!). You would not need to explicity check in every page, as this event fires on every request.
Pete.
Your help has saved me hundreds of hours of internet surfing.
fblack61
sumo_the_cat

Yep, looking at your code properly, this is what you need to do. simply move it to the Application_AuthenticateRequest event in the Global.asax file. (Then access the current user as mighy says. See the other question you posted in!)
j_tipps

ASKER
Cools, thanks for both your help and advice. i can use HttpContext.Current for response and reqest too, it works.
heck ya man, i'll move that code over.
thanks again.
sumo_the_cat

you can definitely use HttpContext.Current with Global.asax too. Put a breakpoint in there and see how it works. it's just what you need for the job!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
hismightiness

Yeah, that Current context is a lifesaver when you are trying to write external classes.  It allows you to access everything you need (request, response, session, server, application, trace, etc.).  I am glad you got this sorted out!  :)
sumo_the_cat

one last little thing - i noticed that you were instantiating a new instance of your Common class. if you are just writing a public static (shared) method, you do not need to do this - just call it directly without instantiating (e.g. look at the Math class).
j_tipps

ASKER
you guys are awsome! thank you

humm. how would i call it directly.
I have tryed like this
      bool Heya = VenderRisk.Common.CheckLog();
but it gives me
An object reference is required for the nonstatic field, method, or property 'VenderRisk.Common.CheckLog()'
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
sumo_the_cat

move it to the global asax! but for future ref, this is exactly right - but you need to make the method static (shared in VB) as well as public. ie public static bool CheckLog() {...
sumo_the_cat

Lots of methods are like this, and are the most similar to non-OO functions, as they don't depend on the properties of a particular instance of the class.
j_tipps

ASKER
OOKKK got cha, man, thanks alot for you help!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.