Creating User in dotnetnuke and Assign Role using c# - c#

I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?
//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
rndString += c;
}
string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();
//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;
//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;
UserCreateStatus result = UserController.CreateUser(ref oUser);
if (result == UserCreateStatus.Success)
{
RoleController oDnnRoleController = new RoleController();
//Get the role information
RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
// RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
//Assign to user
oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
// oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}

The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.

Related

NullReferenceException When Using VerifyHashedPassword in asp.net core

Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.

how to Update same member_id if Phone number and Country code exist in database

public class RegistrationController : ApiController
{
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("ACcount", "token");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK",Registration.getResponse(reg));
}
public DefaultRespons GetActivate(int registration_id, int verification_code)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = dc.registrations.Where(r => r.id == registration_id && r.verification_code == verification_code && r.registration_date==null).SingleOrDefault();
if (reg!=null)
{
List<registration> previous = dc.registrations.Where(r => r.mobile_number == reg.mobile_number && r.country_code == reg.country_code).ToList();
foreach (registration r in previous)
{
member mem = dc.members.Where(mb => mb.registration_id == r.id).SingleOrDefault();
if (mem!=null)
mem.online_status = -1;
}
member m = new member();
m.registration_id = reg.id;
m.online_status = 0;
reg.registration_date = DateTime.Now;
dc.members.InsertOnSubmit(m);
dc.SubmitChanges();
return new DefaultRespons(1, "Activated", Activation.getResponse(m));
}
else
{
return new DefaultRespons(1, "Failed", "");
}
}
Here is My code from which i am creating new Member_id . when i Enter following parameter and i activate from code then in response there is new Member_id id creating and it return . now i want when i register with same Phone number and country code whose Member id is already create i want to return same member_id it should not update new Member id please help me how to check the Phone number and country code already exist in database and return same member id. please help me i am not able to do this how to check .
Hi Anil try this sample code:
make required changes as per your code
public int CheckUser(int countrycode, long mobileno)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int id = from b in dc.registrations
where b.country_code.Equals(countrycode) && b.mobile_number.Equals(mobileno)
select b.registration_id;
return id;
}
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int reg_id = CheckUser(country_code, mobile_no);
if (reg_id == 0)
{
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("AC3c23fee017f23f5061a6b5d3be6f74da", "6fe81560f88f3850c5ad5d4a7b8a5f50");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK", Registration.getResponse(reg));
}
else
{
//your code what you want to do with the reg_id
}
}
#Arijit - For best practice, please make sure to not include your auth token in your code examples, or at least make sure to reset it any time you share it. Thanks!

Getting Error When saving changes in database in asp.net mvc4

This my one method primaryKey of my model is 'PlanetKey'
Graph graph = new Graph();
long lastGraphID = 1000;
//graph.GraphID = lastGraphID;
graph.ItemType = enumType;
graph.GraphItemTitle = title;
graph.GraphItemDescription = statusMessage;
graph.GraphItemUserFullName = null;
graph.GraphItemURL = url;
graph.ItemSummary = title + ": " + statusMessage; ;
graph.ItemCreatedOn = DateTime.UtcNow.ToLocalTime();
//graph.GraphID = lastGraphID;
graph.GraphCustomURL = null;
graph.DbType = "OFFLINE";
graph.ItemOwnerGraphID = ItemOwnerGraphID;
graph.ItemUserID = userInfoId;
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedCareerTreeNodeId = 0;
graph.PRIMARYTaggedCareerTreeSerialNumber = "1";
graph.PRIMARYTaggedSkillTreeNodeId = 0;
graph.PRIMARYTaggedSkillTreeSerialNumber = "1";
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedToolTreeNodeId = 0;
graph.PRIMARYTaggedToolTreeSerialNumber = "1";
graph.CountReactions = 0;
graph.CountResponses = 0;
graph.CountRatings = 0;
graph.AverageRating = 0;
graph.CountRatings = 0;
graph.CountUses = 0;
graph.CountViews = 0;
graph.isReported = false;
graph.isPSKverified = false;
graph.isPSKbanned = false;
graph.isPSKresource = false;
graph.AccessAllowedCode = 0;
graph.AgeRestrictionCode = loginUserCurrentAge;
graph.isHidden = false;
GraphsController GraphsControllerObject = new GraphsController();
long returnGraphId = GraphsControllerObject.CreateGraphIdByModel(graph);
this is another what i am calling to
public long CreateGraphIdByModel(Graph graph)
{
try
{
if (ModelState.IsValid)
{
db.Graphs.Add(graph);
db.SaveChanges();
return graph.GraphID;
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return graph.GraphID;
}
this is showing me eeror in db.SaveChanges()
what m i doing wrong with this code i just wanna pass my parameter using model as crud of mvc4
To know what the error is: You need to look at the inner exception, it will tell you precisely what the problem is.
You can inspect the exceptions innerException property. It will be an EF exception with a list of errors.
The error says, Error converting datetime2 to datetime
Entity framework handles all the dates as a Datetime2, so, if you fields in the database are Datetime, this could be a problem. Populating all the date fields and changing the datatype, are the most commom solutions
Copied from here: 'datetime2' error when using entity framework in VS 2010 .net 4.0

I am getting An Error with c# and Docusign How Do i resolve this error

I am getting the error
Unable to load template. Unable to load template from TemplateReference(0). Error: Data at the root level is invalid. Line 1, position 1.
below is a simplified version of the code i am using...
If i don't use the template reference type of the code everything works fine. But when i start using a template reference.. Nothing works and i get this error. Anyone have a suggestion?
TemplateReference _tempRef = new TemplateReference();
TemplateReference[] _tempRefs = new TemplateReference[] { };
TemplateReferenceRoleAssignment[] _roleAssignmentArray = new TemplateReferenceRoleAssignment[] { };
Recipient[] _recipientsArray = new Recipient[] { };
EnvelopeInformation envelope = new EnvelopeInformation();
Recipient recipient = new Recipient();
recipient.ID = "1";
recipient.Email = "someemail#somewhere.com";
recipient.UserName = "Some Person";
recipient.Type = RecipientTypeCode.Signer;
recipient.RequireIDLookup = false;
Array.Resize(ref _roleAssignmentArray, 1);
Array.Resize(ref _recipientsArray, 1);
_recipientsArray[0] = recipient;
var saRoleAssignment = new TemplateReferenceRoleAssignment
{
RecipientID = "1",
RoleName = "SA"
};
_roleAssignmentArray[0] = saRoleAssignment;
var reference = new Docusign.TemplateReference();
reference.Template = "49C0BE2B-48F7-4F38-B44A-19EB8E6A1A38";
reference.Document = new Docusign.Document();
reference.Document.PDFBytes = new byte[0];
reference.Document.ID = Convert.ToString(1);
reference.Document.Name = "please work";
reference.RoleAssignments = _roleAssignmentArray;
Array.Resize(ref _tempRefs, 1);
_tempRefs[1 - 1] = reference;
//.NET
//.NET
envelope.AccountId = "accountID";
envelope.Subject = "Sample Application";
envelope.EmailBlurb = "You can add a personal message here.";
APIServiceSoapClient apiService = new APIServiceSoapClient();
apiService.ClientCredentials.UserName.UserName = "userhere";
apiService.ClientCredentials.UserName.Password = "pass";
var status = apiService.CreateEnvelopeFromTemplates(_tempRefs, _recipientsArray, envelope, true);
If you're using DocuSign's SOAP api instead of REST then you should definitely familiarize yourself with the SOAP SDK on GitHub:
https://github.com/docusign/DocuSign-eSignature-SDK
There's an MS.NET (C#) version which has sample code that works out of the box, you only need to enter your api credentials. I suggest you use that as your project base, especially since it was updated recently.
Since you have not identified which line the error is stemming from it's a little hard to debug, but if you look at SendTemplate.aspx.cs in the SDK you'll see that the template reference is instantiated like this:
// Construct the template reference
var templateReference = new DocuSignAPI.TemplateReference
{
TemplateLocation = DocuSignAPI.TemplateLocationCode.Server,
Template = TemplateTable.Value,
RoleAssignments = CreateFinalRoleAssignments(recipients)
};
where CreateFinalRoleAssignments() is defined as:
protected DocuSignAPI.TemplateReferenceRoleAssignment[] CreateFinalRoleAssignments(DocuSignAPI.Recipient[] recipients)
{
// Match up all the recipients to the roles on the template
return recipients.Select(recipient => new DocuSignAPI.TemplateReferenceRoleAssignment
{
RecipientID = recipient.ID, RoleName = recipient.RoleName
}).ToArray();
}

Object reference not set to an instance of an object

I've searched through many threads and websites looking for this problem. So far, I haven't been able to find anything wrong with this code.
The "bad" code is this: request.AddComment(v, c);
Also, I don't know what a stack trace is.
Thanks for all your help in advance.
Here is my code:
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a =
new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);
The only way this snippet might throw a NullReferenceException is if request.Retrieve returned null and request.AddComment throws an exception if either parameter is null.
The solution is to test v:
Video v = request.Retrieve<Video>(uri);
if(v != null)
{
Comment c = new Comment();
c.Content = "asdf";
request.AddComment(v, c);
}
else
{
// something went wrong when getting the video...
}
Null check the objects that are being referenced. The video request definately should be checked. Code below does a video null check.
string devkey = "1";
string username = "2";
string password = "3";
YouTubeRequestSettings a = new YouTubeRequestSettings("test", devkey, username, password);
YouTubeRequest request = new YouTubeRequest(a);
Uri uri = new Uri("b");
Video v = request.Retrieve<Video>(uri);
Comment c = new Comment();
c.Content = "asdf";
if (v!= null)
{
request.AddComment(v, c);
}
else
{
//Handle the null, try to get the video again, report to user, etc.
}

Categories

Resources