Search DNN Portal User using custom Module - c#

Hello to all programmers out there!
I am currently developing a module wherein I need to have a search for all users in my DNN portal. And I don't know what is the right way of doing so. I just have to populate a gridview with the users username and UserID with a field populated with a button. So overall. I need to have 3 fields wherein:
1st field = Username
2nd field = UserID
3rd Field = a Button(Which I already know how to include in a gridview)
I also have a textbox and a buttonSearch wherein in the textbox I will search for an existing username else, I shall throw an exception or message perhaps. So whenever there is a username existing prior to what I searched, the gridview will return with the information.
As of now I'm really puzzled here. And I only have this:
public static UserInfo GetUserByName(int portalId, string username)
{
}
And I'm not sure what to do next.
Any response would be really appreciated.

I updated my answer to reflect the function wrap that you originally suggested. I am using the GetUsersBasicSearch function of DotNetNuke.Entities.Users to look for a user by username. I'm not sure what you need a gridview for? If you are searching for a username, it will likely return just 1 user. Are you wanting to partially match the username and show multiple matches in a gridview?
public static UserInfo GetUserByName(int portalId, string username)
{
var foundUsers = UserController.Instance.GetUsersBasicSearch(portalId, 0, 10, "UserID", true, "UserName", username);
if (foundUsers.Any())
{
return foundUsers.FirstOrDefault();
}
else
{
return null;
}
}

Related

how to access session data from layout c#

Good day,
I am trying to pass a user last name into my layout.
In my home index I get my user last name and assign it to my session.
var userId = User.Identity.GetUserId();
var usuerInDb = _user.GetUsuario(userId);
HttpContext.Session["LastName"] = usuerInDb .LastName;
//More code here ....
return view();
What I would like to do is to acess "LastName" from my session and assign it to my layout in some way like the following
//Layout
//....more code
Hello #session["LastName"]
How should I do it? I also accept other approaches.
Thanks
I would suggest using User Claims, to avoid bloating the session with a lot of user information.
https://korzh.com/blogs/net-tricks/aspnet-identity-store-user-data-in-claims
if are usin MVC you can use TempData["LastName"]
replace
HttpContext.Session["LastName"] = usuerInDb .LastName;
to
TempData["LastName"] = = usuerInDb .LastName;
In view..
Hello TempData["LastName"]

Inserting a row into Relational database table

I am very new to c# and asp.net mvc. I'm building a HR portal for our company where a user can submit a leave form among other things... So I'm using mssql as the database server and using Entity Frame work to communicate with it. I have 3 entities, user (Containing user details), permissions (the user permissions for allowing actions in the app) and then the leave form table (where the leave form details are stored). There is a one to many relationship between user - permission and then a one to many relationship between user-leave. I am not fazed about the permissions as that gets created when the user account is being created.
The problem I am facing is, how do I add a leave form for a specific user? Below is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Leave(MasterViewModel model)
{
DocSubViewModel mv = model.DSModel;
int userId = Convert.ToInt32(Session["userID"]);
try
{
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.dateFrom = mv.DateFrom;
leave.dateSubmitted = DateTime.Now;
leave.dateTo = mv.DateTo;
leave.nrDays = mv.NrDays;
leave.reason = mv.SpecialLeave;
leave.TLApproval = null;
leave.TLApprovalDate = null;
leave.TLApprovalID = mv.TeamLeaderID;
leave.DMApprovalDate = null;
leave.DMApprovalID = mv.DepManagerID;
leave.DMApproval = null;
leave.type = mv.Type;
leave.user = userId;
db.leaves.Add(leave);
db.SaveChanges();
}
ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
catch (Exception ex)
{
ViewBag.Message = ex;
//ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
The problem comes in leave.user = userId;. It says:
Cannot implicitly convert int to Portal.Model.user
I can't seem to find out how to do this...
You're telling it to put the UserId where your leave model is asking for a User.
Your relationship requires a User to go in there, so you'll have to update your code a little bit:
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.user = db.users.First(x => x.Id == userId);
}
This will put reference to the actual user in the new leave record. If you go later and check it out you'll see a column in the leave table called user_Id that has an integer value in it and is set as a foreign key to the users table.
Note that this will error if no user exists having the specified Id value. If you anticipate this to be a problem, rather use .FirstOrDefault() instead of .First() and then account for the value being null before you add it to your new leave object.
That's expected since User is a object and not int. What you should be doing probably is leave.user.UserId = userId; instead [Assuming leave.user is of type User which has a UserId property]

Selenium entering invalid text (Half text) in text box

While running multiple test cases, selenium is entering invalid text as shown in the attachment.
Below are the two Examples showing the error:
Instead of entering AutomationTest123_6035633258972, it just enters 6035633258972. .
Instead of Entering AutomationTest123_636010703068635512, it just
enters utomationTest123_636010703068635512. .
Code
//StaticVariable is class which has static values
var username = StaticVariable.username;
var password = StaticVariable.password;
driver.FindElement(By.Id("username")).SendKeys(username); //putting wrong values
driver.FindElement(By.Id("password")).SendKeys(password); //putting wrong values
driver.FindElement(By.Id("login")).Click();
Can anyone help me on this? Any help would appreciated.
first of all make sure that
var username = StaticVariable.username;
is assigning the right value.
use a
print
to check what the value of username after assign.
than try by using the below code:
driver.FindElement(By.Id("username")).click()
driver.FindElement(By.Id("username")).clear()
driver.FindElement(By.Id("username")).SendKeys(username);
There can be a couple of reasons I've seen that this can be an issue. I'd first try to clear out the text input first and make sure it has focus.
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
userElem.click();
userElem.clear();
userElem.sendKeys(userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
passElem.click();
passElem.clear();
passElem.sendKeys(password);
// Click login button
driver.findElement(By.id("login"))
.click();
If, however, that doesn't fix it, I've had situations where splitting the string up and sending keys a few at a time has worked. That does have a performance penalty so I wouldn't do it unless you really really need to.
public void fooTest() {
// Do stuff to get to the correct page, etc
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
sendKeys(userElem, userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
sendKeys(passElem, password);
// Click login button
driver.findElement(By.id("login"))
.click();
// do assertions, etc
}
private void sendKeys(WebElement elem, String keys) {
elem.click();
elem.clear();
for (int i = 0; i < keys.length(); i) {
elem.sendKeys(keys.charAt(i));
}
}
Note : sorry for any syntax / c# errors, I've barely used the language ... I'm much more familiar with Java ;-)
Use the clear method then type the text: driver.findElement(By.cssSelector("").clear();
It may help.
Rather than using 'var' , you might want to try putting in the specific type , such as 'string'. The problem has to be in what is being passed to .SendKeys() or how it is being received by the function.
string username = StaticVariable.username;
string password = StaticVariable.password;

How to store login user id in asp.net?

i am new to asp.net. my question is that how one can save login userid in asp.net webform?
code i am writing in asp.net webform is:
foreach (var s in db.Users)
{
if (tbUserName.Text==s.user_name && tbPassword.Text == s.user_password)
{
if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
Response.Redirect("~/");
}
else
{
FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
}
flag = 1;
break;
}
else
flag=0;
}
if(flag==0)
{
tbUserName.ErrorText = "Invalid user";
tbUserName.IsValid = false;
}
}
As Tim said, you can get the authenticated user with
User.Identity.Name
You can also get the AuthenticationType and IsAuthenticated properties from the same object.
A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.
Based off of what you wrote, it looks like the passwords are in clear text and not encrypted, which is a huge security issue. Being new to .Net, take a look at the .Net Membership Providers or SimpleMembership or a comparable pattern.
Good luck!
I would suggest you look at using the Session object to store the user ID. A Session will be available throughout that user's session on the site. Thus, you can call Session anywhere in your site's code to reference that user ID.
For example, to store the id, simply do this, pretend we're in Page_Load()
Session["UserId"] = userID // Or wherever you get the ID from.
then in your code behind, you can do this:
string userId = Session["UserId"]
If the user ID is a number, say an int, then you will need to cast the userID:
int userId = 0;
int.TryParse(Session["UserID"], out userID)
Quick dirty link to a Session example :
http://asp.net-tutorials.com/state/sessions/

could not find new column in aspnet_Membership table

I had added in a new column called "ForgotPasswordDate" into aspnet_Membership table. When a user hit the submit button in the Password Recovery Control, it would store the timing that user hit the button into the "ForgotPasswordDate" column by using the getDate() method.
After which, user would receive an email which contain an URL directing them into ChangePassword.apsx.
I wanted to make the ChangePassword.aspx page expired after 1 day the user had requested for new password. This would be done by using the time in "ForgotPasswordDate" column and using the AddDay() method.
However, the code gave me a problem. Which I think they could not recognize the "ForgotPasswordDate" column inside the Membership table.
This is the code which had an error:
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3))
for testing purposes, currently I just set the logic as 3 minutes.
And the error message is:
System.Web.Security.MembershipUser' does not contain a definition for 'ForgotPasswordDate' and no extension method 'ForgotPasswordDate' accepting a first argument of type 'System.Web.Security.MembershipUser' could be found (are you missing a using directive or an assembly reference?
Here is the whole code:
protected void Page_Load(object sender, EventArgs e)
{
//if the id is in the query string
if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
{
//store the user id
Guid userId = new Guid(Request.QueryString["ID"]);
//attempt to get the user's information
MembershipUser user = Membership.GetUser(userId);
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3)) //here is the part
{
//Page not expire yet.
hidden.Text = user.ProviderUserKey.ToString();
Server.Transfer("~/ChangePassword.aspx");
}
else
{
//Expired; direct to Page Expired Page
Server.Transfer("~/PageExpired.aspx");
}
}
}
is there anyway that the system could recognize the new column in aspnet_membership table?
I would find out which stored procedure the membership uses, modify and include the new columns. Then you may have to override the current membership class to include the new properties.

Categories