C# UserPrincipal Object reference not set to an instance of an object - c#

I am receiving the classic, Object reference not set to an instance of an object in my project when viewing the hosted website. Works when building a debug version locally.
Live
Example of code that is showing error message:
using System.DirectoryServices.AccountManagement;
protected void Page_Load(object sender, EventArgs e)
{
try
{
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}

Try this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
// you need to also take into account that someone could get to your
// page without having a Windows account.... check for NULL !
if (System.Security.Principal.WindowsIdentity == null ||
System.Security.Principal.WindowsIdentity.GetCurrent() == null)
{
return; // possibly return a message or something....
}
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// if the user name returned is null or empty -> abort
if(string.IsNullOrEmpty(username))
{
return;
}
username = username.Substring(3);
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);
// finding the user of course can also fail - check for NULL !!
if (user != null)
{
string NTDisplayName = user.DisplayName;
//String NTUser = user.SamAccountName;
lblntuser.Text = NTDisplayName;
}
}
catch (Exception Ex)
{
lblntuser.Text = Ex.Message;
System.Diagnostics.Debug.Write(Ex.Message);
}
}

Related

Add Computer in SCCM and import it to a specific Collection

i would like to import a computer to a specific SCCM-collection.
I've found this method on the msdn:
public int AddNewComputer(
WqlConnectionManager connection,
string netBiosName,
string smBiosGuid,
string macAddress)
{
try
{
if (smBiosGuid == null && macAddress == null)
{
throw new ArgumentNullException("smBiosGuid or macAddress must be defined");
}
// Reformat macAddress to : separator.
if (string.IsNullOrEmpty(macAddress) == false)
{
macAddress = macAddress.Replace("-", ":");
}
// Create the computer.
Dictionary<string, object> inParams = new Dictionary<string, object>();
inParams.Add("NetbiosName", netBiosName);
inParams.Add("SMBIOSGUID", smBiosGuid);
inParams.Add("MACAddress", macAddress);
inParams.Add("OverwriteExistingRecord", false);
IResultObject outParams = connection.ExecuteMethod(
"SMS_Site",
"ImportMachineEntry",
inParams);
// Add to All System collection.
IResultObject collection = connection.GetInstance("SMS_Collection.collectionId='ABC0000A'");
IResultObject collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
collectionRule["ResourceID"].IntegerValue = outParams["ResourceID"].IntegerValue;
Dictionary<string, object> inParams2 = new Dictionary<string, object>();
inParams2.Add("collectionRule", collectionRule);
collection.ExecuteMethod("AddMembershipRule", inParams2);
return outParams["ResourceID"].IntegerValue;
}
catch (SmsException e)
{
Console.WriteLine("failed to add the computer" + e.Message);
throw;
}
}
Now, I try to call it with a button event:
private void button2_Click(object sender, EventArgs e)
{
AddNewComputer(PcNameBox.Text, MacAdrBox, PcNameBox.Text, CollectionDropDown.Text);
}
But I'm sorry, I don't no how to call the WQLConnectionManager on this point?! I know the object must be preset before "PcNameBox.Text". That's all :(
On another event, I call it like this:
SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
WqlConnectionManager connection = new WqlConnectionManager(namedValues);
connection.Connect(PrimarySiteServer);
But this Method is struggling me.
(It's only a hobby, pleave be indulgent)
Thanks in advance for a hint...
Chris
Google is your friend, friend:
https://msdn.microsoft.com/en-us/library/cc146404.aspx
Example below:
public WqlConnectionManager Connect(string serverName, string userName, string userPassword)
{
try
{
SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
WqlConnectionManager connection = new WqlConnectionManager(namedValues);
if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
{
// Connect to local computer.
connection.Connect(serverName);
}
else
{
// Connect to remote computer.
connection.Connect(serverName, userName, userPassword);
}
return connection;
}
catch (SmsException e)
{
Console.WriteLine("Failed to Connect. Error: " + e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("Failed to authenticate. Error:" + e.Message);
return null;
}
}

about forms authentication and redirect

Every time I try to Response.Redirect("tothepageIwant.aspx"); tt takes me to ~/Account/Logon.aspx
Why is this happening? I'm using Forms Authentication, with a custom method of authenticating, using PrincipalContext.ValidateCredentials.
If the credentials are valid, I want to Redirect.Response to the page I'm allowing the user to reach.
Instead, anytime I successfully login, it redirects me to the old Account/Logon.aspx.
Any suggestions? Anything I need to look out for when using Forms Authentication with custom method of authenticating?
EDIT (add code):
protected void Submit1_Click(object sender, EventArgs e)
{
var auth = new AuthClass();
var result = auth.ValidateCredentials(UserEmail.Text, UserPass.Text);
if (result)
{
Response.Redirect("~/Members/RollReport.aspx");
}
else
{
Msg.Text = "Not authorized to access this page.";
}
}
public bool ValidateCredentials(string user, string pass)
{
using (var pc = new PrincipalContext(ContextType.Domain, "Domain.name"))
{
// validate the credentials
try
{
var isValid = pc.ValidateCredentials(user, pass);
if (isValid)
{
var isAuth = AuthorizeUser(user);
return isAuth;
}
else
{
return false;
}
}
catch (ActiveDirectoryOperationException)
{
throw;
}
}
}
private bool AuthorizeUser(string user)
{
var isAuth = false;
var authList = (List<string>)HttpContext.Current.Cache["AuthList"];
foreach (var id in authList)
{
if (id == user)
{
isAuth = true;
}
}
return isAuth;
}
var userName = Request.ServerVariables["LOGON_USER"];//or some other method of capturing the value from the username
var pc = new PrincipalContext(ContextType.Domain);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
if(userFind != null)
{
HttpContext.Current.Session["username"] = userFind.DisplayName;
}
If you want to check and redirect.. store the value inside a session variable inside the Global.asax
protected void Session_Start(object sender, EventArgs e)
{
//declare and Initialize your LogIn Session variable
HttpContext.Current.Session["username"] = string.Empty;
}
On the Page_Load of your login page assign the value if the code above succeeds
if(HttpContext.Current.Session["username"] == null)
{
//Force them to redirect to the login page
}
else
{
Response.Redirect("tothepageIwant.aspx");
}
if you want to do the same thing inside a using(){} statement
string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"yourusernamehere")) //User.Identity.Name
{
if (user != null)
{
fullName = user.DisplayName;
}
}
}
use the debugger and inspect all of the user. Properties ok

How can I update Username and password in aspnet_Users table and other table was created by me tbl_users simultaneously?

I am Making a Web project and maintaining role management in this application. When I had been created web project then I defined role management in this application. When I create an user using createUser() function data stores in aspnet_Users,aspnet_Membership and other table that one has been created by me (tbl_users),stores all user information including some info of aspnet_Users,aspnet_Membership table. I am able to create data in these tables simultaneously but now I want to update and delete data in these tables simultaneously,how can it be possible please??..let me know.
Here is My code
protected void btn_signup_Click(object sender, EventArgs e)
{
try
{
// Create new user.
objuser.email=txt_email.Text;
objuser.password=txt_password.Text;
objuser.username = TextBox1.Text;
if (Membership.RequiresQuestionAndAnswer)
{
MembershipUser newUser =
Membership.CreateUser(objuser.email,objuser.password,
objuser.username);
}
else
{
MembershipUser newUser = Membership.CreateUser(
objuser.email,
objuser.password,
objuser.username);
int i = BusinessUser.BusinessRegisterUser(objuser);
if (i > 0)
{
Session["user_authenticate"] = "Verified";
Session["user_email"] = objuser.email;
Label1.Text = Session["user_email"].ToString();
login1.Style.Add("display", "none");
logout.Visible = true;
Response.Redirect("user_registration.aspx");
}
}
show_menu();
//Response.Redirect("login.aspx");
}
catch (MembershipCreateUserException ex)
{
WarningModal.Show();
lblWarning.Text = GetErrorMessage(ex.StatusCode);
pnlIssues.Visible = true;
}
catch (HttpException ex)
{
WarningModal.Show();
lblWarning.Text= ex.Message;
}
}
protected void loginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
try
{
if (Membership.ValidateUser(loginUser.UserName, loginUser.Password))
{
Session["user_authenticate"] = "Verified";
e.Authenticated = true;
Session["user_email"] = loginUser.UserName;
objuser.email = Session["user_email"].ToString();
Label1.Text = Session["user_email"].ToString();
login1.Style.Add("display", "none");
logout.Visible = true;
}
else
{
e.Authenticated = false;
}
}
catch (Exception ex)
{
}
}
You could always put a trigger on the aspnet_membership table that cascades the update and delete actions to the tbl_user table.
http://technet.microsoft.com/en-us/library/ms189799.aspx

validating web site credentials

I have a website: "https://blahblah.com"
To authenticate to it, I do this (which works fine):
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = AppVars.Username;
credentials.Password = AppVars.Password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
//.....
But how do I go about just validating the username and password if I want to add a login functionality?
UPDATED CODE:
private void btnLogIn_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Username = txtUserName.Text;
Properties.Settings.Default.Password = txtPassword.Text;
using (PrincipalContext pc = new PrincipalContext( ContextType.Domain, AppVars.ixLibraryConnectionTestURL))
{
try
{
bool isValid = false;
isValid = pc.ValidateCredentials(AppVars.Username, AppVars.Password);
if (isValid == true)
{
//just testing
MessageBox.Show("is valid");
}
else
{
//just testing
MessageBox.Show("is not valid");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
the domain name looks something like this: https://xxxxxx-services.zzz999.org/pqg_4/lib/api/sdo/rest/v1
Use: System.DirectoryServices.AccountManagement namespace
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
You can read more about it here:
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx

DotNetOpenAuth and Google

I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
var openId = new OpenIdRelyingParty();
HttpContext httpContext = HttpContext.Current;
var headers = new WebHeaderCollection();
foreach (string header in httpContext.Request.Headers)
{
headers.Add(header, httpContext.Request.Headers[header]);
}
string requestUrl = string.Format("http://localhost:12345/Login/{0}",
httpContext.Request.Url.Query);
var requestInfo = new HttpRequestInfo(httpContext.Request.HttpMethod,
new Uri(requestUrl),
httpContext.Request.RawUrl, headers,
httpContext.Request.InputStream);
var response = openId.GetResponse(requestInfo);
if (response != null)
{
ClaimsResponse claimResponse = response.GetExtension<ClaimsResponse>();
lblUser.Text = claimResponse.FullName;
if (response.Exception != null)
{
lblError.Text = response.Exception.Message;
}
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
try
{
using (OpenIdRelyingParty openId = new OpenIdRelyingParty())
{
string identifier = #"https://www.google.com/accounts/o8/id";
var request = openId.CreateRequest(identifier,
new Realm("http://localhost:12345/"),
new Uri("http://localhost:12345/Login/"));
request.AddExtension(new ClaimsRequest
{
Email = DemandLevel.Require
});
request.RedirectToProvider();
}
}
catch (Exception ex)
{
// TODO: log exception
throw;
}
}
When I execute the code, user is authenticated but ClaimsResponse is null.
Code works fine with MyOpenId.
Any help would be appreciated.
The information here is useful: Retrieve OpenId User Information (Claims) across providers
The gold nugget you are likely missing in your app is the AXFetchAsSregTransform.

Categories

Resources