How to prevent users to add entries for a given time using ASP NET MVC? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have this scenario:
Add a product but block adding for 1 minute for other users. After 1 min they can normally add one.
Adding a product it is not blocked for the user itself who added it
but for others.
I have this and it is working like a charm:
public async Task<JsonResult> AddProducts(string citaId, string paciente, string medico, string modalidad)
{
var usuario = System.Web.HttpContext.Current.User.Identity.GetUserName();
if (Session["User"] != null)
{
if(Session["User"].ToString() != usuario)
{
var med = await _context.MEDICOS.FindAsync(medico);
var objetoerrr1 = new
{
type = "error",
message = $"you cannot add a product, WAIT 1 MIN."
};
return Json(objetoerrr1, JsonRequestBehavior.AllowGet);
}
}
... the rest of the code for adding a product
// create a session
Session["User"] = usuario;
Session.Timeout = 1;
But my problem is that it is not working when using different browsers or PCs and It is like session is empty in different devices.
Well I have never worked with sessions in ASP NET MVC5 before so when I heard this requeriment, sessions came to my mind so I used them.
How can I achieve such thing? Should I use database to store the session or something? Or should not I be using sessions for this approach?

You should save the sessions into database, not only for this, also for security reasons. And give that session an unique identifier (and save it inside the cookie and retrieve and check it everytime) in order to know login timestamp, logout timestamp, prevent cookie-copy between browsers, prevent cookie-copy after log out, prevent browser-copy, duplicated sessions, if roles changes meanwhile the user is logged in, etc.
Of course there are a lot of ways to do this without database, but this is my answer. I use only database for this because I save user logins into database, as their roles.

Related

Calculate lines of code change for a commit? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is there a way to calculate lines of code in a Pull Request API in Azure Devops for each file. I have gone through below two links and but was not of much help.
Is there a way to get the amount of lines changed in a Pull Request via the Dev Ops Service REST API?
Lines of Code modified in each Commit in TFS rest api. How do i get?
Thank you.
Steps:
a. Get the commit IDs for the specified pull request
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/commits?api-version=6.1-preview.1
b. Get commit path via the commit ID
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits/{commitId}/changes?api-version=5.0
c. Get parents commit ID via commit ID
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits/{commitId}?api-version=5.0
d. Get the result via below API and request body.
POST https://dev.azure.com/{Org name}/_apis/Contribution/HierarchyQuery/project/{Project name}?api-version=5.1-preview
Request Body:
{
"contributionIds": [
"ms.vss-code-web.file-diff-data-provider"
],
"dataProviderContext": {
"properties": {
"repositoryId": "{Repo ID}",
"diffParameters": {
"includeCharDiffs": true,
"modifiedPath": "{Commit path}",
"modifiedVersion": "GC{Commit ID}",
"originalPath": "{Commit path}",
"originalVersion": "GC{parents commit ID}",
"partialDiff": true
}
}
}
}
Result:

Get name of currently logged in user [duplicate]

This question already has answers here:
_userManager.GetUserAsync(User) returns null
(3 answers)
Closed 3 years ago.
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().
If the login was successful, I would like to get the currently logged in user's data using the userManager.
The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.
var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);
if (result.Succeeded)
{
//var loggedUser = mUserManager.GetUserName(HttpContext.User);
var userData = mUserManager.GetUserAsync(HttpContext.User);
var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
return Redirect("/createpost");
}
To me it looks like you are logging the user in and immediately trying to access the user info. The httpContext has not had the chance to update and still reflects the time when there was no user logged in. Try moving your user info retrieval logic to "createpost" where it gets executed on the next http roundtrip.
public async Task<IActionResult> createpost()
{
var userData = await mUserManager.GetUserAsync(HttpContext.User);
Debug.WriteLine(userData.Id);
Debug.WriteLine(userData.UserName);
Debug.WriteLine(userData.Email);
return View();
}
You've got two issues. First, GetUserAsync relies on the principal being set in HttpContext, which hasn't occurred yet, so that method will fail. There must be an intervening request before you can access the user that way.
What you can do is pull the user out directly using something like FindByIdAsync, which you're attempting to do already. However, you're trying to find the user based on the id of the user instance you tried to retrieve via GetUserAsync. Since that failed, there will be no user, and thus no id to use in this lookup, causing it to fail as well. It doesn't even make sense to do this, as if you had the user already to get the id from, there'd be no point in looking that user up by its id.
So, what you need to do is look the user up by information you actually do have, which based on your code, is username. Therefore, do:
var user = await mUserManager.FindByNameAsync(username);
The reason is that the user will be available for next request, you could not get the user in this current request,let alone user's name.

Controller Post - Duplicate Records - Mozilla Firefox

I am providing a link via Mail to the Users. When they click on link Page Opens & as they hit Submit button, Controller Post Method runs.
saveRecords()
{
-- business logic
-- code validation for checking duplicates
-- saving records
}
All was working well. But suddenly it was found that duplicate records are being entered. There is no problem in Code logic.
After tracing it was found that it is happening when browser is Mozilla. And scenario is User clicks on Mail link twice so 2 tabs open & if he hits Submit button on each tab then Duplicates are being inserted.
Note - if same Page we hit submit it validates properly.
Problem occurs when 2 tabs are open & Submit button is clicked in both tabs & Browser is Firefox.
Can you suggest me a solution?
This is summary of Code :-
var obj = ctx.tblDuty.FirstOrDefault(m => m.Id == recordId);
if (obj.EntryStatus == Status.Approved)
msg = "Duty already Approved.!";
else if (obj.EntryStatus == Status.Rejected)
msg = "Duty already Rejected.!";
var data = service.saveDuty(model, userRole);
Why don't you introduce a lock around the method (if you can't figure out why Mozilla sends two POST calls) and wrap the code in there:
static object _lock = new object();
saveRecords()
{
lock(_lock)
{
-- business logic
-- code validation for checking duplicates
-- saving records
}
}
EDIT 1 [Blocking Collection with working rows]:
This is not the best solution, but it will get it done for you. Maybe consider using Monitor if you wanna do it in a better\more optimal way.

object reference not set to an instance of an object, when using session variable in MVC4

NOTE
it is not duplicate question I am asking, I have read 3 different links from stack as showed below, but none of them shows resolution for my question (or) reason, so please let me know what i am doing wrong
link1
link2
link 3
I developed MVC application, where username from login page taken to controller to pull the data, where it loads up the value of that username, so I want that Username to be exist until i quit my application, so what I did was did some R&D what to use to store and save the data and pass it to another page,
first I used "TempData" which works fine to my scenario , where it pulls the data as I needed, but the error occurs when application is idle for 5 min then, if i press the Refresh button or F5, I get the above error, username is null generating error message "object reference not set to instance of an object" I know why this error generates.
later I searched it again, used session variable to store and send it, even it does works fine same as tempdata but after few mins like 5 mins and more, if page refreshes generates same message, I believe the syntax used in tempdata and session are correct since it works fine, I am posting code of the way I am using it in MVC, please let me know any mistakes I have done, or let me know what should I do to fix this problem, which should work for longer duration of idle, unless I use session time to quit the application.
NOTE
I have not used any session time, like if application is idle for 5 mins it should quit the application.
CODE
public ActionResult ValidateLogIn(FormCollection postedFormData)
{
LoginViewModel.LoginDataModel.UserName = Convert.ToString(postedFormData["UserName"]);
LoginViewModel.LoginDataModel.Password = Convert.ToString(postedFormData["Password"]);
// ViewBag.Message = LoginViewModel.LoginDataModel.UserName;
// TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;
TempData.Keep();
Session["UsrName"] = LoginViewModel.LoginDataModel.UserName;
// with some code..........
}
public ActionResult LandingPage()
{
//////ViewData["message"] = TempData["UsrName"].ToString();
Session["message"] = Session["UsrName"].ToString();
ViewData["person"] = Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
String PatID = Convert.ToString(Session["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
PatientDetailsViewModel = PatientDetailsDataAccessService.LogInEnquiry(PatID);
return View("../PatientDetails/PatientDetailsView", PatientDetailsViewModel.ServiceList.AsEnumerable());
}
and this is the error which generates when refreshed
You can use User.Identity.Name once the user has logged to get the user name. This way you dont have to mess about with temp data, viewbag or viewdata.

NetSuite Service Login with SessionID (can not retrieve sessionID from current service) in C#

For the life of me I can no figure out where to get the SessionID out of the service so that I can use it in a future call to recreate the same session.
I am currently using the 2013_1_0 version of the wsdl in C#
When referencing the older documents SuiteTalkWebServicesPlatformGuide_2011.1.pdf on page 78 (Reusing Session IDs During Login) they talk about this.
Any Suggestions?
Here is my sample code for logging into NetSuite without using a previous SessionID...
// invoke the login operation
Passport passport = new Passport();
passport.account = _sNetSuiteAccount;
passport.email = _sNetSuiteUserName;
RecordRef role = new RecordRef();
role.externalId = _sNetSuiteRole;
passport.role = role;
passport.password = _sNetSuitePassword;
status = service.login(passport).status;
// Confirm login was a success
// Process response
if (status.isSuccess == true)
{
_bIsNetSuiteAuthenticated = true;
}
Additionally I have yet to find sample code for using the SessionID to re-create the service. So any suggestion there would also be welcomed.
Thank you!
In talking with NetSuite what I desire to do is impossible and the SessionID is stored as a private variable and handled by the .NET code.
I am currently seeking an alternative to a persistent session so when code base is called multiple times that the user will not need to be prompted for each iteration to enter their NetSuite cridentials. I will update this answer as more details come available on this.

Categories

Resources