MVC Routing Access - asp.net-mvc

Hi I would like to know whether this can be done in MVC.
Lets say we have customer order entry of
Customer ID - 1
Order ID - 2
Let's say when user types /Order/View?id=2
I would like this page can be accessible to customer who has ID 1 only. Let's assume we keep this ID in identity.
Is there easy way to achieve this ?
Thanks,

public ActionResult View(){
var userName = User.Identity.Name;
var id = Request["id"];
if (userName == "1" && id == "2")
return RedirectToAction("Authorized");
else
return RedirectToAction("Unauthorized");
}

Related

Getting Profile ID of User from his Jobs using Sessions and LINQ

As the title says. I have a page with a Job that have an ID. This ID I am storing in a Session and when I am trying to access the Company profile I just test if the Session Variable with Job ID from the tables Jobs and then I am trying to select the User ID and then with this User ID I search in UserManager and try to populate the page with some data.
Code For Company Profile:
public async Task<ActionResult> Details(string id)
{
String JobValID = Convert.ToString(Session["DetailsURL"]);
var UserJobID = context.Jobs.Where(x => x.ID.ToString() == JobValID).OrderByDescending(x => x.UserID).Select(x => x).ToString();
UserJobID = id; //This line is to see what value I got from LINQ and is still the Session value.
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
return View(user);
}
View For this Controller is default scaffolded View from controller.
And like This I get Session["DetailsURL"]
var currentID = Url.RequestContext.RouteData.Values["id"];
Session["DetailsURL"] = currentID;
I guess this is not the standard way to get a User Profile page. But I am using an ActionLink from Job Page to get into the Company Profile.
Here ActionLink to get from JobPage to Company Profile:
#Html.ActionLink("About this company", "Details", "UserAdmin", new { id = Session["UserJobID"] }, null)
My problem is in LINQ statement, when I am trying to select UserID, it doesn't get the right value, and when I am searching in UserManager the value is still the session Value.
Found the solution here
So how I did it:
var UserJobId = (from c in context.Jobs
where c.ID == JobValID
select new { c.UserID }).Single();
var myVal = UserJobId.UserID;
id = myVal;
It has been awhile since I have used C#, but your LINQ statement seems to be getting a list of Job objects and doing ToString on the list. If Job has reference to the UserId associated with it, then the following LINQ statement should work:
var userId = context.Jobs
.SingleOrDefault(x => x.ID.ToString() == jobId)
.?Select(j => j.<accessorToUserId>) // Not sure what your schema is
.?ToString()
Notice the ?. This is just in case SingleOrDefault returns null then the following method calls won't happen. If, for some reason, more than one Job uses that jobId, which is really bad practice, replace SingleOrDefault with FirstOrDefault.
Also, Select is supposed to be used to map from type T to type U. Doing Select(x => x) is pointless since you are simply doing T -> T.

How do i write code in ASP.NET MVC to check whether user accepeted terms and condition

In my ASP.NET MVC project I need to write code to check for users whether they accept terms and condition. I am using Entity framework and Database first approach. I have Table called Appterms, in which I have field called TermsAccepted and Date. I also have other fields in Appterms table such as GatewayUserId and termId. ' GatewayUserID has ID of registered users and termId is primary key. 'Termsaccepted' field is of bit type.
I tried to follow custom attribute function which is posted in this post
MVC 3 How can I make a user view a warning/disclaimer screen but not able to implement as per my needs.
I am using this post Getting current user id to get id of current user. So after this how can i return 0 or 1 to check they accepted terms and condition.
This is the code snippet I am trying to use :
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = false)]
public class AcceptedTermsCheck : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Check if AcceptedTC is set to true
// If set, then do nothing
// Otherwise redirect to TC page
}
}
Here to check if user accepted terms, i should return true, that is '1' in my GatewayUserId field, if not it should return false.But I don't know how to do this. And also I got to know I should create session to achieve this task. But never worked on it before.
Any help??
Thanks..
I think this is what you want to do. you can post back data or use jquery to post to a action to check and if the terms are accepted and then enable the submit button for a better user experience. Whichever way you choose, you can do something like this.
var dataEntityModel = new YoursEntities();
AppTerm currentTerm = dataEntityModel.Appterms.ToList().
where(x=>x.GatewayUserId == yourCurrentUserID
&& x.termid == yourTermId).FirstOrDefault();
if(currentTerm.TermsAccepted == true)
{
}
else
{
RedirectToAction("action","controller");
}
userlogin login = db.userlogins.Where(j => j.email == name && j.password == password && j.status == 1)
.FirstOrDefault();

Retrieve Session variables into ASP.NET MVC 4 (razor, view)

I wrote many websites with PHP. Now, I have to create website with ASP MVC 4 (c#) and I am stuck with Sessions.
I.E. the user should go to login page, enter his/her login and password. If they are correct, in controller, I set the session with UserId, like this:
Session["UserId"] = 10
This UserId value is used for showing PartialViews (login form or (after login) some application menus). How can I get this UserId inside Razor view ?
After this in View:
if (Session.UserId == 10) { #Html.Partial("LoggedMenu") }
i've got exception with StackOverflow. :/
you're doing it wrong...
Session[<item name>] returns a string, you should compare with a string as well, or cast it, so, either (int)Session["UserId"] == 10 or Session["UserId"] = "10".
you also are invoking a property that does not exist Session.UserId will not exist as Session is like an NameValueCollection, you call it by request it's item name.
at the end, you should write
#if (Session["UserId"] == "10") {
Html.Partial("LoggedMenu");
}
You say your are learning, so I would like to point out 2 quick things:
You should take advantage of the ASP.NET MVC Course that is available for free in the home page http://asp.net/mvc (right side when you read "Essential Videos")
Create an MVC3 project and see how they do it as it comes ready out of the box with Membership
#if (Session["UserId"] != null && Session["UserId"] == 10 ) {
Html.Partial("LoggedMenu");
}
Apart from that: for identity management better use the out of the box membership system
Below is a an example:
Controller:
if (Session["pageInitCounter"] == null)
{
Session["pageInitCounter"] = 1;
}
else
{
int counter = Convert.ToInt32(Session["pageInitCounter"]);
counter++;
Session["pageInitCounter"] = counter;
}
View:
#Html.Hidden("pageInitCounter", Session["pageInitCounter"])
Javascript:
alert($("#pageInitCounter").val());

Getting all ids and usernames from membership Asp Net MVC

I have no doubt on how to retrieve membership id from 1 single user:
currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
but I can´t find a way to retrieve all users id and usernames.
I tried this way:
MembershipUserCollection AllUsers;
AllUsers = GetAllUsers();
From that point I can´t find a way to retrieve Ids and Usernames from AllUsers.
Could I get some help from here?
I think you're looking for Membership.GetAllUsers()
var users = Membership.GetAllUsers();
foreach (MembershipUser membershipUser in users)
{
// membershipUser.UserName;
}
http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.getallusers.aspx

SimpleMembership MVC 4 get data from UserProfile having role in webpages_Roles

I have the following code. But there must be a more database efficient way to do this, because, correct me if Im wrong the number of database queries is
(1 + (qty of users with admin role))
With a new MVC 4 project the membership defaults are the tables UserProfile, webpages_Roles and webpages_UsersInRoles. I see lots of built in methods for Roles.Get*. If I want to avoid writing code like what I have below do I need to explicitly create a model for webpages_Roles and webpages_UsersInRoles as well as all the code first properties? Getting just the username from Roles.Get* doesnt suffice, I need the full UserProfile.
FYI the "UserRole" object below is just an enum
public ActionResult Admins()
{
var dbContext = new UsersContext();
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = new List<UserProfile>();
foreach (string username in usernames)
{
var adminUser = dbContext.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == username);
adminUser.Roles.Add(UserRole.SiteAdministrator);
adminUsers.Add(adminUser);
}
return View(adminUsers);
}
Yes, you don't want to do it that way. That's a very inefficient way.
Instead, use the tools as they were designed. For example, something like this:
var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
var adminUsers = dbContext.UserProfiles
.Where(x => usernames.Contains(x.Username)).ToList();
return View(adminUsers);

Resources