locked
asp.net webforms c# OWIN authentication, cannot create ROLE manager? Not supported by OWIN? RRS feed

  • Question

  • User2142845853 posted

    This is sort of a continuation of a different thread,  https://forums.asp.net/t/2150884.aspx?How+to+get+UserNames+User+assigned+Roles+and+modify+from+c+Webforms+net+4+5

    But Now its all about using a custom built interface to show users, set roles, define roles.  Should be simple right?  It doesnt work. It never did work.  There is IdentityManager 1.0 that doesnt work completely. Found that it has flaws and was not supported or really promoted. The UI for managing roles does work but its in Angular.

    Using VS2017 and webforms with MVC folders, Individual User accounts, it has authentication built in and running out of the box. Creating the method to show users is now simple. But not roles.  Users are defined by OWIN, apparently NOT roles?

     protected void Unnamed1_Click(object sender, EventArgs e)
            {
                var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                GridView1.DataSource = manager.Users.ToList();
                GridView1.DataBind();
            }

    Make a webform, add button and gridview, add this code and right away it lists all the users in the grid.  In startup.cs

                app.CreatePerOwinContext(ApplicationDbContext.Create);
                app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
                app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
                app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

    Its fine, no errors.  but

     protected void Button1_Click(object sender, EventArgs e)
            {
                var Roles = Context.GetOwinContext().g   .GetUserManager  

    Go hit the "." dot after getowincontext() ??  And only GetUserManager is defined within OWIN.  Search for this?  others posting how: 

    No ApplicationRoleManager class in my MVC 5 template

    https://stackoverflow.com/questions/25417024/no-applicationrolemanager-class-in-my-mvc-5-template

    The answer still didnt fix this in my project, no RoleManager.  How to display roles or modify them?

    thanks

    Tuesday, February 5, 2019 5:33 PM

All replies

  • User475983607 posted

    I provided RoleManager sample code in your other thread on the same subject.  

    https://forums.asp.net/post/6244297.aspx

    Tuesday, February 5, 2019 7:26 PM
  • User2142845853 posted

    ok I searched for this thread and couldnt find it.  Thought it was gone.  Will apply this and reply again thanks

    Tuesday, February 5, 2019 9:40 PM
  • User2142845853 posted

    ok that worked, had it running in 10 minutes.  Dont know why the need for this kind of cast 

      private ApplicationRoleManager roleManager;
            public ApplicationRoleManager RoleManager
            {
                get
                {
                    return roleManager ?? Context.GetOwinContext().Get<ApplicationRoleManager>();
                }
    
                private set { this.roleManager = value; }
            }

    wish I'd gone this way in december.

    Now the next part, showing what roles each user has and setting them

    Wednesday, February 6, 2019 4:29 AM
  • User475983607 posted

    Now the next part, showing what roles each user has and setting them

    And you can find this example code in the same link...

    Wednesday, February 6, 2019 11:50 AM
  • User2142845853 posted

     protected void PopulateUsersGrid()
            {
                var users = (from u in UserManager.Users
                             select new UserGridVm()
                             {
                                 Username = u.UserName,
                                 RoleId = u.Roles.FirstOrDefault().RoleId
                             }).ToList();
    
                UserGrid.DataSource = users;
                UserGrid.DataBind();
            }

    Just what is UserGridVm() ???? 

    Is it a custom model? is it a typo?

    Wednesday, February 6, 2019 8:01 PM
  • User475983607 posted

    Just what is UserGridVm() ???? 

    Is it a custom model? is it a typo?

    It's just a class.

    public class UserGridVm {
    	public string UserName {get; set;}
    	public int RoleId {get; set;}
    }

    This is syntax for populating the class.

    UserGridVm myVm = new UserGridVm()
    		{
    		 Username = u.UserName,
    		 RoleId = u.Roles.FirstOrDefault().RoleId
    		}

    The class syntax is covered in the C# programming guide.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

    This construct is referred to as a projection query.

    var users = (from u in UserManager.Users
    			 select new UserGridVm()
    			 {
    				 Username = u.UserName,
    				 RoleId = u.Roles.FirstOrDefault().RoleId
    			 }).ToList();

    The linq docs cover the syntax.

    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/queries-in-linq-to-entities

    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/query-expression-syntax-examples-projection

    Wednesday, February 6, 2019 9:03 PM
  • User2142845853 posted

    Thanks, I had added just a class and it runs.  but what it doesnt do is SHOW the current role

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <asp:GridView ID="UserGrid" runat="server" AutoGenerateColumns="False" OnRowDataBound="UserGrid_RowDataBound" OnRowEditing="UserGrid_RowEditing" OnRowUpdating="UserGrid_RowUpdating" OnRowCancelingEdit="UserGrid_RowCancelingEdit" Width="476px">
            <Columns>
                <asp:TemplateField HeaderText="Username">
                    <EditItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                       <%-- <asp:DropDownList ID="DropDownList1" runat="server" Enabled="false" >
                        </asp:DropDownList>--%>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
        </asp:GridView>

    Took out the empty unused dropdown, but in the HiddenField changed it to

      <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                       <%-- <asp:DropDownList ID="DropDownList1" runat="server" Enabled="false" >
                        </asp:DropDownList>--%>
                        <%--<asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />--%>
    
                            <%# Eval("Role") %>
                     </ItemTemplate>

    and modified the UserGridVm to contain a Role and Id.  but it will not show the current role.  Trying to show what the current role is

    Wednesday, February 6, 2019 9:18 PM
  • User475983607 posted

    Try viewing the entire thread.

    Wednesday, February 6, 2019 9:57 PM
  • User2142845853 posted

    Ive read every single word, letter, symbol of that entire thread repeatedly. over/over, and will look again

    Thursday, February 7, 2019 4:07 AM
  • User475983607 posted

    Ive read every single word, letter, symbol of that entire thread repeatedly. over/over, and will look again

    I ran the code from the link.  The grid shows the user and role.  Of course you must have roles and users in the database.  The manage roles page let's you add role.  I did not code an Add User page as you can use the registration.

    Keep in mind, this is very basic Web Forms programming.  All you're doing is populating a dropdown and binding a grid.

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ManageUsers.aspx.cs" Inherits="WebFormsIdentityRoleManager.Admin.ManageUsers" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <asp:GridView ID="UserGrid" runat="server" AutoGenerateColumns="False" OnRowDataBound="UserGrid_RowDataBound" OnRowEditing="UserGrid_RowEditing" OnRowUpdating="UserGrid_RowUpdating" OnRowCancelingEdit="UserGrid_RowCancelingEdit">
            <Columns>
                <asp:TemplateField HeaderText="Username">
                    <EditItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server" Enabled="false" >
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
        </asp:GridView>
    </asp:Content>
    
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WebFormsIdentityRoleManager.Models;
    
    namespace WebFormsIdentityRoleManager.Admin
    {
        public partial class ManageUsers : System.Web.UI.Page
        {
    
            public List<IdentityRole> Roles { get; set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                Roles = RoleManager.Roles.ToList();
    
                if (!Page.IsPostBack)
                {  
                    PopulateUsersGrid();
                }
            }
    
            protected void PopulateUsersGrid()
            {
                var users = (from u in UserManager.Users
                             select new UserGridVm()
                             {
                                 Username = u.UserName,
                                 RoleId = u.Roles.FirstOrDefault().RoleId
                             }).ToList();
    
                UserGrid.DataSource = users;
                UserGrid.DataBind();
            }
    
    
            private ApplicationUserManager userManager;
            public ApplicationUserManager UserManager
            {
                get
                {
                    return userManager ?? Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                }
    
                private set { this.userManager = value; }
            }
    
    
            private ApplicationRoleManager roleManager;
            public ApplicationRoleManager RoleManager
            {
                get
                {
                    return roleManager ?? Context.GetOwinContext().Get<ApplicationRoleManager>();
                }
    
                private set { this.roleManager = value; }
            }
    
            protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DropDownList roleSelect = e.Row.FindControl("RoleSelect") as DropDownList;
                    HiddenField roleId = e.Row.FindControl("RoleId") as HiddenField;
    
                    if (null != roleSelect)
                    {
                        roleSelect.DataSource = Roles;
                        roleSelect.DataValueField = "Id";
                        roleSelect.DataTextField = "Name";
    
                        if(Roles.Any(f => f.Id == roleId.Value))
                        {
                            roleSelect.SelectedValue = roleId.Value;
                        }
                        
                        roleSelect.DataBind();
                        roleSelect.Items.Insert(0, new ListItem("--Select--", String.Empty));
                    }
    
                }
            }
    
            protected void UserGrid_RowEditing(object sender, GridViewEditEventArgs e)
            {
                UserGrid.EditIndex = e.NewEditIndex;
                PopulateUsersGrid();
            }
    
            protected void UserGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                UserGrid.EditIndex = -1;
                PopulateUsersGrid();
            }
    
            protected void UserGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                //Get the new role
                GridViewRow row = UserGrid.Rows[e.RowIndex];
                string username = ((Label)row.FindControl("Username")).Text;
                string roleId = ((DropDownList)(row.FindControl("RoleSelect"))).SelectedValue;
                if(roleId != "0")
                {
                    var role = RoleManager.FindByIdAsync(roleId).Result;
    
                    //Get the user and roles
                    var user = UserManager.FindByNameAsync(username).Result;
                    var roles = UserManager.GetRolesAsync(user.Id).Result;
                    //Remove any old roles as there can be only one role per user
                    var results = UserManager.RemoveFromRolesAsync(user.Id.ToString(), roles.ToArray()).Result;
                    //Add the new role
                    results = UserManager.AddToRoleAsync(user.Id.ToString(), role.Name).Result;
    
                    UserGrid.EditIndex = -1;
                    PopulateUsersGrid();
                }
                else
                {
                    //User must select a value from the dropdown.
                }
    
            }
    
    
        }
    }
        public class UserGridVm
        {
            public string Username { get; set; }
            public string RoleId { get; set; }
        }

    Thursday, February 7, 2019 11:28 AM
  • User2142845853 posted

    Ok now 'THIS' asp code will show the user roles, but set within a  dropdown list thats disabled.  The other code from before has NOTHING in the Role column, and yes I have several users and some have assigned roles which show up in this.  This .cs code shows the role.  but I cannot extract the role from the dropdown list. without LINQ dont know how to get the NAME of the role unless the OWIN rolemanager provides this?  

    Now just need to display the role, apart from a disabled dropdownlist.  I can show the hash of the role just not the name

    Thanks

    Thursday, February 7, 2019 5:41 PM
  • User475983607 posted

    rogersbr

    Ok now 'THIS' asp code will show the user roles, but set within a  dropdown list thats disabled.  The other code from before has NOTHING in the Role column, and yes I have several users and some have assigned roles which show up in this.  This .cs code shows the role.  but I cannot extract the role from the dropdown list. without LINQ dont know how to get the NAME of the role unless the OWIN rolemanager provides this?  

    Now just need to display the role, apart from a disabled dropdownlist.  I can show the hash of the role just not the name

    Thanks

    It's the same code...

    Click the edit button to edit the record.  This will enable the dropdown.

    I don't get the hash comment. If the role is hashed how will the user know which one to select?

    Thursday, February 7, 2019 7:39 PM
  • User2142845853 posted

    rogersbr

    Now just need to display the role, apart from a disabled dropdownlist.  I can show the hash of the role just not the name

    Thanks

    It's the same code...

    Click the edit button to edit the record.  This will enable the dropdown.

    I don't get the hash comment. If the role is hashed how will the user know which one to select?

    Well the difference I see is in the asp/html code for the role, and then a different .cs method for filling the grid.  If I show the hash its worthless. I want to show the role, would draw out the role and thought I was passing that to the gridview but its not. 

    wish I could sit and do this for hours at a time, 20 minutes here, have to drive/gone 4 hours, come back work 43 minutes, phone rings and have to drive and gone for an hour. look forward to being able to sit and just read it all, Ive read it and applied it but its only showing the role within the dropdown list thats disabled?  I try to pass similar code into just text adding another item to the model, but its blank.  click edit? THEN it shows the role in the active dropdown, saves just fine  afterwards in one code group all roles are empty until clicking edit; in another the recent one you posted, the role stays in a disabled dropdown.    

    Thursday, February 7, 2019 9:08 PM
  • User475983607 posted

    Ive read it and applied it but its only showing the role within the dropdown list thats disabled?

    Correct, you have to click the edit link to put the grid in edit mode.  Then select a role and click save.

    I try to pass similar code into just text adding another item to the model, but its blank.

    I have no idea what you're referring to.

    click edit? THEN it shows the role in the active dropdown, saves just fine  afterwards in one code group all roles are empty until clicking edit;   

    Correct, if there is a new user account and a role has not been assigned then the role is empty.  You must click edit and assign the user to a role.

    in another the recent one you posted, the role stays in a disabled dropdown.    

    Correct, you can change this behavior if clicking edit, selecting a role, and clicking save are too many clicks.

    Thursday, February 7, 2019 9:30 PM
  • User2142845853 posted

    How can the ROLE be displayed without being inside of the disabled dropdown list?

    I try to pass similar code into just text adding another item to the model, but its blank.

    I have no idea what you're referring to.

    internal class UserGridVm
        {
            public UserGridVm()
            {
            }
    
            public string Username { get; set; }
            public string RoleId { get; set; }
            public string Role { get; set; }
            public string Id { get; set; }
            public string RoleId2 { get; set; }
        }

    Just want to display the role without having to click edit.  this could also be put into MVC if its not possible for a Gridview to accept the specific role value

    Thursday, February 7, 2019 11:47 PM
  • User2142845853 posted

    Why does the role have to be within an inactive drop down?  Is that the only property that can be written to?  tried using just text and it wont work.  Will seek another solution that works fully

    Friday, February 8, 2019 4:59 PM
  • User475983607 posted

    rogersbr

    Why does the role have to be within an inactive drop down? 

    You want to replace the select with a label?

        public class UserGridVm
        {
            public string Username { get; set; }
            public string RoleId { get; set; }
            public string RoleName { get; set; }
        }
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WebFormsIdentityRoleManager.Models;
    
    namespace WebFormsIdentityRoleManager.Admin
    {
        public partial class ManageUsers : System.Web.UI.Page
        {
    
            public List<IdentityRole> Roles { get; set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                Roles = RoleManager.Roles.ToList();
    
                if (!Page.IsPostBack)
                {
                    PopulateUsersGrid();
                }
            }
    
            protected void PopulateUsersGrid()
            {
                //        var results = UserManager
                //.Users
                //.Where(u => u.mgr == appUser.org || appUser.org == "corp")
                //.Include(m => m.Roles.Select(r => r.Role));
                var users = (from u in UserManager.Users 
                             select new UserGridVm()
                             {
                                 Username = u.UserName,
                                 RoleId = u.Roles.FirstOrDefault().RoleId
                             }).ToList();
    
                foreach(var u in users)
                {
                    u.RoleName = RoleManager.Roles.FirstOrDefault(r => r.Id == u.RoleId).Name;
                }
    
                UserGrid.DataSource = users;
                UserGrid.DataBind();
            }
    
    
            private ApplicationUserManager userManager;
            public ApplicationUserManager UserManager
            {
                get
                {
                    return userManager ?? Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                }
    
                private set { this.userManager = value; }
            }
    
    
            private ApplicationRoleManager roleManager;
            public ApplicationRoleManager RoleManager
            {
                get
                {
                    return roleManager ?? Context.GetOwinContext().Get<ApplicationRoleManager>();
                }
    
                private set { this.roleManager = value; }
            }
    
            protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                    {
                        DropDownList roleSelect = e.Row.FindControl("RoleSelect") as DropDownList;
                        HiddenField roleId = e.Row.FindControl("RoleId") as HiddenField;
    
                        if (null != roleSelect)
                        {
                            roleSelect.DataSource = Roles;
                            roleSelect.DataValueField = "Id";
                            roleSelect.DataTextField = "Name";
    
                            if (Roles.Any(f => f.Id == roleId.Value))
                            {
                                roleSelect.SelectedValue = roleId.Value;
                            }
    
                            roleSelect.DataBind();
                            roleSelect.Items.Insert(0, new ListItem("--Select--", String.Empty));
                        }
                    }
    
    
                }
            }
    
            protected void UserGrid_RowEditing(object sender, GridViewEditEventArgs e)
            {
                UserGrid.EditIndex = e.NewEditIndex;
                PopulateUsersGrid();
            }
    
            protected void UserGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                UserGrid.EditIndex = -1;
                PopulateUsersGrid();
            }
    
            protected void UserGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                //Get the new role
                GridViewRow row = UserGrid.Rows[e.RowIndex];
                string username = ((Label)row.FindControl("Username")).Text;
                string roleId = ((DropDownList)(row.FindControl("RoleSelect"))).SelectedValue;
                if (roleId != "0")
                {
                    var role = RoleManager.FindByIdAsync(roleId).Result;
    
                    //Get the user and roles
                    var user = UserManager.FindByNameAsync(username).Result;
                    var roles = UserManager.GetRolesAsync(user.Id).Result;
                    //Remove any old roles as there can be only one role per user
                    var results = UserManager.RemoveFromRolesAsync(user.Id.ToString(), roles.ToArray()).Result;
                    //Add the new role
                    results = UserManager.AddToRoleAsync(user.Id.ToString(), role.Name).Result;
    
                    UserGrid.EditIndex = -1;
                    PopulateUsersGrid();
                }
                else
                {
                    //User must select a value from the dropdown.
                }
    
            }
    
    
        }
    }
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ManageUsers.aspx.cs" Inherits="WebFormsIdentityRoleManager.Admin.ManageUsers" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <asp:GridView ID="UserGrid" runat="server" AutoGenerateColumns="False" OnRowDataBound="UserGrid_RowDataBound" OnRowEditing="UserGrid_RowEditing" OnRowUpdating="UserGrid_RowUpdating" OnRowCancelingEdit="UserGrid_RowCancelingEdit">
            <Columns>
                <asp:TemplateField HeaderText="Username">
                    <EditItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="RoleName" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
        </asp:GridView>
    </asp:Content>
    



    Friday, February 8, 2019 6:10 PM
  • User2142845853 posted

    Thanks so much, in the middle of the .cs code it throws an exception because it finds a user that has no role assigned, 

                foreach (var u in users)
                {
                    u.RoleName = RoleManager.Roles.FirstOrDefault(r => r.Id == u.RoleId).Name;
                }

    System.NullReferenceException
    HResult=0x80004003
    Message=Object reference not set to an instance of an object.

    looking at u.RoleName it has no role

     foreach (var u in users)
                {
                 try
                    {
                        u.RoleName = RoleManager.Roles.FirstOrDefault(r => r.Id == u.RoleId).Name;
                    }
                    catch (Exception exx)
                    {
                        u.RoleName = "none";
                    }
                }
    

    Now fills in the grid with the role or 'none'.  the grid is so aweful how to curve the edges and add good neutral colors to make it look modern and not so primitive?

    Friday, February 8, 2019 9:08 PM
  • User475983607 posted

    rogersbr

    in the middle of the .cs code it throws an exception because it finds a user that has no role assigned, 

    Just add an if... Untested but you should get the idea.  Using a try...catch to control logic flow is not a "good" programming practice.  try...catch should be used for catching exceptions.

    foreach (var u in users)
    {
    	if(u.RoleId != null)
    	{
    		u.RoleName = RoleManager.Roles.FirstOrDefault(r => r.Id == u.RoleId).Name;
    	}
    	else 
    	{
    		u.RoleName = string.Empty;
    	}
    }

    rogersbr

    the grid is so aweful how to curve the edges and add good neutral colors to make it look modern and not so primitive?

    The default Visual Studio templates reference Bootstrap 3.  You can apply Bootstrap styles to the table rather easily.

    https://getbootstrap.com/docs/3.4/css/

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ManageUsers.aspx.cs" Inherits="WebFormsIdentityRoleManager.Admin.ManageUsers" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <div class="table-responsive">
            <asp:GridView CssClass="table table-striped" 
                ID="UserGrid"
                runat="server" 
                AutoGenerateColumns="False" 
                OnRowDataBound="UserGrid_RowDataBound" 
                OnRowEditing="UserGrid_RowEditing" 
                OnRowUpdating="UserGrid_RowUpdating"
                OnRowCancelingEdit="UserGrid_RowCancelingEdit"
                OnPreRender="UserGrid_PreRender"
                GridLines="None">
            <Columns>
                <asp:TemplateField HeaderText="Username">
                    <EditItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="RoleName" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
        </asp:GridView>
            </div>
    </asp:Content>
    
            protected void UserGrid_PreRender(object sender, EventArgs e)
            {
                UserGrid.UseAccessibleHeader = true;
                UserGrid.HeaderRow.TableSection = TableRowSection.TableHeader;
            }

    The Grid View also comes with style templates that you can pick form a list.  I recommend that you spend a bit more time learning the technology.  

    Friday, February 8, 2019 10:07 PM
  • User2142845853 posted

    did a compromise,

     const string NoRoleFound = "  none  ";
            protected void PopulateUsersGrid()
            {
                var users = (from u in UserManager.Users
                             select new UserGridVm()
                             {
                                 Username = u.UserName,
                                 RoleId = u.Roles.FirstOrDefault().RoleId
                             }).ToList();
                foreach (var u in users)
                {
                    try
                    {    // Note - Some users have no role assigned, fetch may return null
                        if (null != u.RoleId)
                        {
                            u.RoleName = RoleManager.Roles.FirstOrDefault(r => r.Id == u.RoleId).Name;
                        }
                        else
                        {
                            u.RoleName = NoRoleFound;
                        }
                    }
                    catch (Exception exx)
                    {
                        u.RoleName = NoRoleFound;
                    }
                }
                UserGrid.DataSource = users;
                UserGrid.DataBind();
            }

    In MVC there is the ViewBag to pass error messages, is there a similar mechanism in webforms to add a message to the exception handler to say to the UI that a database operation failed or some message?

    Saturday, February 9, 2019 4:26 PM
  • User475983607 posted

    In MVC there is the ViewBag to pass error messages, is there a similar mechanism in webforms to add a message to the exception handler to say to the UI that a database operation failed or some message?

    Come on man... Of course.  All you have to do is add a label and assign a value to the Text attribute.  Very simple very basic.

    Saturday, February 9, 2019 5:02 PM
  • User2142845853 posted

    Thanks, with bootstrap its fine now.  Added the other columns

     <asp:TemplateField HeaderText="Role">
                    <EditItemTemplate>
                        <asp:DropDownList Width="200px"  ID="RoleSelect" runat="server">
                        </asp:DropDownList>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </EditItemTemplate>
    
    
    
    
                    <ItemTemplate>
                        <asp:Label ID="RoleName" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>
                        <asp:HiddenField ID="RoleId" runat="server" Value='<%# Bind("RoleId") %>' />
                    </ItemTemplate>
                    <HeaderStyle BackColor="#ECF9FF" />
                    <ItemStyle Width="220px" />
                </asp:TemplateField>

    so this allows the contents to be modified when its in the Edit page or regular display page

    Saturday, February 9, 2019 5:32 PM
  • User2142845853 posted

    Found a problem with the email as username but got a workaround

    Saturday, February 9, 2019 7:45 PM
  • User2142845853 posted

    Now how different is the code to manage the USER and password?  Id tried to make this, can display the user info, but not update it.  is the mechanism exactly the same?

    Saturday, February 9, 2019 9:18 PM
  • User475983607 posted

    Found a problem with the email as username but got a workaround

    I hope so considering you asked this question a few weeks ago.

    https://forums.asp.net/t/2150333.aspx

    All of the formatting is working. but how to you assign parts of the code to the ROLES??  The User/Roles page and setting that must be for an admin only, thats the last step  

    Are they supposed to be put into a folder with web.config showing which roles are allowed?  Isnt that the old way?

    Yes, ASP.NET uses the web.config to authorize access or you can use User.IsInRole("TheRoleName") in code.  These constructs have been around a very long time and information is not hidden.

    https://support.microsoft.com/en-us/help/316871/how-to-control-authorization-permissions-in-an-asp-net-application

    https://support.microsoft.com/en-us/help/306590/info-asp-net-security-overviewhttps://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/

    https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/

    Sunday, February 10, 2019 12:19 PM
  • User2142845853 posted

    yes. finally sinking in.  But I go back to the USERS and whats there is not working. Need to duplicate how you set up the Roles to be modified but for Users.

    can the same code be used?  What will happen is I try a bunch of code and it will not compile or not run, just want to have the same format as Roles but to modify the users info as an admin

    Ackerly gave an example before but its a totally different scheme, Im using the automatically made Identity casts, I dont want to make it all from scratch right now, even though I have, get to the end, and it will not run

    what got done yesterday works perfect, want to keep that style of code but for users

    Sunday, February 10, 2019 5:28 PM
  • User475983607 posted

    yes. finally sinking in.  But I go back to the USERS and whats there is not working. Need to duplicate how you set up the Roles to be modified but for Users.

    can the same code be used?  What will happen is I try a bunch of code and it will not compile or not run, just want to have the same format as Roles but to modify the users info as an admin

    Ackerly gave an example before but its a totally different scheme, Im using the automatically made Identity casts, I dont want to make it all from scratch right now, even though I have, get to the end, and it will not run

    what got done yesterday works perfect, want to keep that style of code but for users

    Honesty, I'm not exactly sure what problem you are trying to solve.  My best guess is the user must be authenticated and in the "Admin" role to to open the ManageUser.aspx and ManageRoles.aspx pages which are within an "Admin" folder.

    Place this web.config in the "Admin" folder.  Only user in the "Admin" role can access files located in the "Admin" folder.

    <?xml version="1.0"?>
    <configuration>
      <system.web>
          <authorization>
            <allow roles="Admin"/>
            <deny users="*"/>
          </authorization>
        </system.web>
    </configuration>

    Please see the docs for more information.

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/roles/role-based-authorization-cs

    Sunday, February 10, 2019 6:02 PM
  • User2142845853 posted
    I'm looking for the code to update the user information including the edit and delete update methods. What I don't get is how to display the user info in the grid and then add the edit feature just like how the user role does it.
    Sunday, February 10, 2019 9:07 PM
  • User475983607 posted

    I'm looking for the code to update the user information including the edit and delete update methods. What I don't get is how to display the user info in the grid and then add the edit feature just like how the user role does it.

    The GridView reference documentation covers the basics.

    https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridview?view=netframework-4.7.2

    Perhaps use the ManageUser GridView as a template.  IMHO, you've been on the forms for a long time and should be able to perform basic tasks.  Write some code and if you get stuck, post your code, expected results, and actual results.

    Sunday, February 10, 2019 10:00 PM
  • User2142845853 posted

    So after looking into the Gridview was able to auto generate the sqldatasource, then pick the rows and have edit features over the users. But was looking to use the methods from the OWIN components.  Mustve forgotten the gridview retains the edit functions. 

    so the grid with edit is there, but now it refuses to accept the BOOTSTRAP parameters. Noticed you utilize separate methods for update, not sure why it throws this error

    Compiler Error Message: CS1061: 'admin_showusers_aspx' does not contain a definition for 'UserGrid_RowDataBound' and no extension method 'UserGrid_RowDataBound' accepting a first argument of type 'admin_showusers_aspx' could be found (are you missing a using directive or an assembly reference?)
    
    Source Error:
    
    
    Line 148:        </div>
    Line 149:        <asp:Panel ID="Panel1" runat="server" Height="307px">
    Line 150:            <asp:GridView CssClass="table  table-hover    table-responsive"
    Line 151:        ID="UserGrid" 
    Line 152:        runat="server"

    Monday, February 11, 2019 2:27 AM
  • User2142845853 posted

    The issue now is the Row Height or padding in the row, and the overall gridview is too narrow, not finding where the GridView height or Bootstrap attributes are modified

    The left margin is about 20% then content is 60% then right margin is 20%  so much wasted space.  Fonts have to be set for each column item, each row item?

    it wastes all that space then has to have a scroll bar at the bottom to show all the items?

    Monday, February 11, 2019 7:08 PM
  • User475983607 posted

    Your question infers that the layout and fonts are caused by some unknown magical force.  That's not the case it's just CSS.

    rogersbr

    The issue now is the Row Height or padding in the row, and the overall gridview is too narrow, not finding where the GridView height or Bootstrap attributes are modified

    Right click on the row and select "Inspect" every single style is applied to the element is shown and you can even interact with the styles real-time.

    rogersbr

    The left margin is about 20% then content is 60% then right margin is 20%  so much wasted space.

    You should fix your bug.

    rogersbr

    Fonts have to be set for each column item, each row item?

    Not true if you learn CSS and CSS selectors.

    rogersbr

    it wastes all that space then has to have a scroll bar at the bottom to show all the items?

    No, your design has a UI bug.  Fix your code.  I strongly recommend learning CSS.

    Monday, February 11, 2019 7:20 PM
  • User2142845853 posted

    Its ok Ill find the answers and post them so others can be helped somehow.  Using CSS and inspect is just part of the process.  Override the CSS locally and GridView does not change

    Monday, February 11, 2019 7:40 PM
  • User475983607 posted

    Override the CSS locally and GridView does not change

    You are doing something wrong.  Post an example that illustrates the issue(s).

    Monday, February 11, 2019 8:58 PM
  • User2142845853 posted

    The problem with position, make sure that your item is not inside another item, so that positioning is affected to that container and not the display itself

    Monday, February 11, 2019 9:03 PM
  • User2142845853 posted

    On the left easily 20% is just blank empty space, then the grid. then on the right 10% or maybe 8% blank. Centering has no effect.   CSS of left:-250px top -150px puts it in the center while its full screen (around 1900 px).  but minimize to a small browser window and it moves to 30 or 40% in from the left

    The other MAIN problem is that the EDIT has no effect.  Add a phone number? Gridview does nothing to save the number. change a click box? Update does not update

    Tuesday, February 12, 2019 4:32 AM
  • User475983607 posted

    On the left easily 20% is just blank empty space, then the grid. then on the right 10% or maybe 8% blank. Centering has no effect.   CSS of left:-250px top -150px puts it in the center while its full screen (around 1900 px).  but minimize to a small browser window and it moves to 30 or 40% in from the left

    I assume you are using the Bootstrap template where the Master page has a "container" div. 

            <div class="container body-content">
                <asp:ContentPlaceHolder ID="MainContent" runat="server">
                </asp:ContentPlaceHolder>
                <hr />
                <footer>
                    <p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>
                </footer>
            </div>

    This element restricts the content width.  You can always change the layout or container CSS.  You can also read the Bootstrap documentation.

    https://getbootstrap.com/docs/3.4/css/#overview-container

    The other MAIN problem is that the EDIT has no effect.  Add a phone number? Gridview does nothing to save the number. change a click box? Update does not update

    Well, if you post the source code we can provide guidance. Otherwise, there's not much we can do.  

    Tuesday, February 12, 2019 12:43 PM
  • User2142845853 posted

    Changing to container-fluid now released that constraint, and its full screen but now its got a Visual Studio flaw,

    table {
        width: 1400px;
        height: 822px;
        border: 1px solid black;
    }

    where???  it says Site.css:: 21

    Ok so one assumes the Site.css file in the ...PROJECT?  Here is the Site.css file,

    /* Move down content because we have a fixed navbar that is 50px tall */
    body {
        padding-top: 50px;
        padding-bottom: 20px;
    }
    
    /* Wrapping element */
    /* Set some basic padding to keep content from hitting the edges */
    .body-content {
        padding-left: 15px;
        padding-right: 15px;
    }
    
    /* Override the default bootstrap behavior where horizontal description lists 
       will truncate terms that are too long to fit in the left column 
    */
    .dl-horizontal dt {
        white-space: normal;
    }
    
    .table th,
    .table td {
        padding: 0.15rem;
        vertical-align: top;
           
    }
    
    /* Set widths on the form inputs since otherwise they're 100% wide */
    input[type="text"],
    input[type="password"],
    input[type="email"],
    input[type="tel"],
    input[type="select"] {
        max-width: 280px;
    }
    
    /* Responsive: Portrait tablets and up */
    @media screen and (min-width: 768px) {
        .jumbotron {
            margin-top: 20px;
        }
        .body-content {
            padding: 0;
            margin-left:1px;
        }
    }
    

    No where is that found.  It was there sometime yesterday, but got deleted. this is after saving, stopping, restarting the project. Still draws a border, thats oversize and it will not change. Searching it shows only 1 site.css file.  Why does VS2017 refuse to apply it?   Lets try firefox.   ok firefox is installing updates and will be back in a while...  will go make coffee, check the mail, walk around and wait for firefox to start..

    Unable to connect

    Firefox can’t establish a connection to the server at localhost:20122.

    The site could be temporarily unavailable or too busy. Try again in a few moments.  

    will try to update it or find another browser to use

    ok it updated, now firefox shows the page without any border, this is the problem. I made alot of CSS changes in chrome and it would not do anything to render the changes. NOW? trying to resolve the oversize grid and all? now the entire grid is tiny covering 1/3 of the screen at 100% resolution.   I should sue CSS for wasted time.  Now have to go back and change all the fonts all the sizes then try to add some kind of container.  so this and the other grids fit in the center of the screen. 

    Too bad there isnt some way to just use formatting that can apply to all 4 grids.  Its a matter of adjusting css numeric settings mostly at random without messing the other one like trying to spin 10 plates on the floor at the same time and hope eventually the grid formats in a reasonable way.  If only a deterministic system existed to format web pages.

    Tuesday, February 12, 2019 4:08 PM
  • User475983607 posted

    rogersbr

    Changing to container-fluid now released that constraint, and its full screen but now its got a Visual Studio flaw,

    table {
        width: 1400px;
        height: 822px;
        border: 1px solid black;
    }

    where???  it says Site.css:: 21

    Ok so one assumes the Site.css file in the ...PROJECT?  Here is the Site.css file,

    You have not clearly defined the new "Visual Studio Flaw" you are trying to solve.  I set the container to fluid and it just worked as documented.  I assume you created a CSS syntax error along the way which is reported on on line 21.  The actual error might be above line 21 like a missing bracket.

    rogersbr

    No where is that found.  It was there sometime yesterday, but got deleted. this is after saving, stopping, restarting the project.

    I'm not sure how a support forum can help if you deleted source code.  I've recommended in past threads that you place your projects under source control.  That way you can revert to a previous version if you accidentally delete something.  I prefer GIT as it runs local and/or remote.

    Anyway,  just create a new project if you need the original CSS file.

    rogersbr

    Still draws a border, thats oversize and it will not change. Searching it shows only 1 site.css file.  Why does VS2017 refuse to apply it? 

    Your browser applies styles not Visual Studio.  If you made a change to a CSS file and you are not seeing the page update then try pressing ctrl+F5 with your browser selected.  This causes the browser to reload all files rather than pulling files from cache.

    rogersbr

    Unable to connect

    Firefox can’t establish a connection to the server at localhost:20122.

    I'm guessing you forgot to start the application.  Try pressing ctrl+F5 in visual studio to start the application without debugging.

    Tuesday, February 12, 2019 4:38 PM
  • User2142845853 posted

    The use of GridView to display then edit the contents of the OWIN roles/users/info as initially created does not work.  The EDIT function does not modify anything, where the code resides? assumed its inside the GridView.

    Does anyone know how the methods need to be generated to edit, update, or delete the gridview contents?  If theyre done internally why are they needed in external methods?

    Tuesday, February 12, 2019 5:40 PM
  • User475983607 posted

    The use of GridView to display then edit the contents of the OWIN roles/users/info as initially created does not work.  The EDIT function does not modify anything, where the code resides? assumed its inside the GridView.

    Not true I provided a perfectly fine working example.  Post your source code if you need help finding the bug(s) in your code.

    Does anyone know how the methods need to be generated to edit, update, or delete the gridview contents?  If theyre done internally why are they needed in external methods?

    You mean writing binding code in the code behind rather than using the GUI?  If so, custom code is more versatility and required if you are using the Identity API(s). 

    Tuesday, February 12, 2019 8:36 PM
  • User2142845853 posted

    rogersbr

    The use of GridView to display then edit the contents of the OWIN roles/users/info as initially created does not work.  The EDIT function does not modify anything, where the code resides? assumed its inside the GridView.

    Not true I provided a perfectly fine working example.  Post your source code if you need help finding the bug(s) in your code.

    Your example worked.  But the literature said the GridView manages all updates to the database.  Your example uses external methods

    rogersbr

    Does anyone know how the methods need to be generated to edit, update, or delete the gridview contents?  If theyre done internally why are they needed in external methods?

    You mean writing binding code in the code behind rather than using the GUI?  If so, custom code is more versatility and required if you are using the Identity API(s). 

    The documentation of the GridView needs to be updated to show that it WILL NOT WORK if using Identity APIs.  Id much rather use the Identity calls, and now get to add this in to all of them. Ok fine.

    What is the standard, where is it called out that here is the method?

    Tuesday, February 12, 2019 9:28 PM
  • User475983607 posted

    Your example worked.  But the literature said the GridView manages all updates to the database.  Your example uses external methods

    Correct.  1) you asked how to use the ASP Identity API.  2) invoking an API or service considered standard and follows SOLID programming principles. Basically a good programming practice.  

    The documentation of the GridView needs to be updated to show that it WILL NOT WORK if using Identity APIs.

    This is common knowledge and a result of following a standard multi-tier/multi-layer design.  You can always connect directly to the Identity tables but this approach combines the UI and data access layer and not a "good" design.

    Id much rather use the Identity calls, and now get to add this in to all of them. Ok fine.

    Right it's better to use the Identity API as it contains business logic.  Binding the results of Identity calls is very simple.  I'm not sure why you are having such difficulty as you have not provided any source code.  

    What is the standard, where is it called out that here is the method?

    ASP.NET Web Forms is event driven.  You place the calls in events.

    Tuesday, February 12, 2019 11:09 PM
  • User2142845853 posted

    Now the problem is getting the current USER ID  and then finding what role they are.  I can see a method for the latter, but not, NOT finding out who is logged in under Identity. 

    All of the methods return NULL.  if I change the authentication type in web.config I can get the windows logged in user, dont want that, it must be who is logged in under this system.  right after the login call, placing the code to request logged in user all return NULL

     var curntuser = System.Environment.UserName;
                            if (manager.IsInRole("Admin", curntuser))
                            {
    

    gets the WINDOWS user

                            if (HttpContext.Current.User.Identity.Name != null)
                            {
                                if (HttpContext.Current.User.Identity.Name.Length != 0)
                                {
                                    var x = HttpContext.Current.User.Identity;
                                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                                    FormsAuthenticationTicket ticket = id.Ticket;
                                    isAuthed = true;
                                    MyUserData = ticket.UserData;
                                }
                            }

    NULL

    Wednesday, February 13, 2019 9:33 PM
  • User475983607 posted

    Now the problem is getting the current USER ID  and then finding what role they are.  I can see a method for the latter, but not, NOT finding out who is logged in under Identity. 

    All of the methods return NULL.  if I change the authentication type in web.config I can get the windows logged in user, dont want that, it must be who is logged in under this system.  right after the login call, placing the code to request logged in user all return NULL

     var curntuser = System.Environment.UserName;
                            if (manager.IsInRole("Admin", curntuser))
                            {

    gets the WINDOWS user

                            if (HttpContext.Current.User.Identity.Name != null)
                            {
                                if (HttpContext.Current.User.Identity.Name.Length != 0)
                                {
                                    var x = HttpContext.Current.User.Identity;
                                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                                    FormsAuthenticationTicket ticket = id.Ticket;
                                    isAuthed = true;
                                    MyUserData = ticket.UserData;
                                }
                            }

    NULL

    I have no idea what you're doing.  This information is not hidden.  

    string username =  User.Identity.GetUserId();

    As a matter of fact the master page generated by the Visual Studio Identity template shows how to get the current logged in user.

    <li><a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetUserName()  %> !</a></li>

    Make sure you add this using statement if not done so already otherwise you can get to the GetUser() extension method.

    using Microsoft.AspNet.Identity;

    Also keep in mind that you are NOT using Forms Authentication you are using OWIN Identity!  

    Wednesday, February 13, 2019 11:25 PM
  • User-943250815 posted

    No offense, but looks a journey to me.
    The good thing, now  I know where to find additional info when I decide to use OWIN Auth

    Wednesday, February 13, 2019 11:52 PM
  • User2142845853 posted

    mgebhard

    rogersbr

    Now the problem is getting the current USER ID  and then finding what role they are.  I can see a method for the latter, but not, NOT finding out who is logged in under Identity. 

    All of the methods return NULL.  if I change the authentication type in web.config I can get the windows logged in user, dont want that, it must be who is logged in under this system.  right after the login call, placing the code to request logged in user all return NULL

     var curntuser = System.Environment.UserName;
                            if (manager.IsInRole("Admin", curntuser))
                            {

    gets the WINDOWS user

                            if (HttpContext.Current.User.Identity.Name != null)
                            {
                                if (HttpContext.Current.User.Identity.Name.Length != 0)
                                {
                                    var x = HttpContext.Current.User.Identity;
                                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                                    FormsAuthenticationTicket ticket = id.Ticket;
                                    isAuthed = true;
                                    MyUserData = ticket.UserData;
                                }
                            }

    NULL

    I have no idea what you're doing.  This information is not hidden.  

    string username =  User.Identity.GetUserId();

    As a matter of fact the master page generated by the Visual Studio Identity template shows how to get the current logged in user.

    <li><a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetUserName()  %> !</a></li>

    Make sure you add this using statement if not done so already otherwise you can get to the GetUser() extension method.

    using Microsoft.AspNet.Identity;

    Also keep in mind that you are NOT using Forms Authentication you are using OWIN Identity!  

    I put these at the Login.aspx.cs  in the switch (result) after the signin is done,

       var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: true);
    
                    switch (result)
                    {
                        case SignInStatus.Success:
                            bool isAuthed = false;
                            string MyUserData = "";
                            string username = User.Identity.GetUserId();
                            string jacoby = Context.User.Identity.GetUserName();

    It just seems like the login page, AFTER the login task is done would be a place to see who just logged in but thats not the case.

    The code you offered returns NULL

    Now the Site Master one, thats great because you can see it works at runtime; but it also returns NULL

    Why would I even care?  because now is the time for putting the ADMIN folder behind an admin only user, and why allow regular users to even try the link to manage users? it should be disabled or not visible at all.

    The only way to tell if the page links to admin tasks should be enabled or hidden? Is the ROLE of the logged in user. Perhaps only Site Master can ascertain who is logged in, why its NULL after the login?   Will try to add a 1 second delay and see if that helps

    But will only put the links in the main Navbar.  I had tried several ways to get the user, they all returned null including both that you suggest which I may have tried, but the site master one is great.  

    will throw in a thread to block for a second and then run the same calls and see if they work.. result NO, has no effect

    and it doesnt seem possible to add c# code to set it up to find the role within site.master code how do you make a variable in the c# side but the name is not available in the html aspx side?  

    Thursday, February 14, 2019 4:04 AM
  • User475983607 posted

    It just seems like the login page, AFTER the login task is done would be a place to see who just logged in but thats not the case.

    The code you offered returns NULL

    Now the Site Master one, thats great because you can see it works at runtime; but it also returns NULL

    Why would I even care?  because now is the time for putting the ADMIN folder behind an admin only user, and why allow regular users to even try the link to manage users? it should be disabled or not visible at all.

    The only way to tell if the page links to admin tasks should be enabled or hidden? Is the ROLE of the logged in user. Perhaps only Site Master can ascertain who is logged in, why its NULL after the login?   Will try to add a 1 second delay and see if that helps

    But will only put the links in the main Navbar.  I had tried several ways to get the user, they all returned null including both that you suggest which I may have tried, but the site master one is great.  

    You're making assumptions about how technology works again.   Identity uses an auth cookie (which is a separate API) to cache an authentication token. The auth token is simply a formatted string that has contains the username, roles, and claims.   The signinManager.PasswordSignIn() is responsible for fetching the username, roles, and claims (from the Identity DB), encrypting the data, adding the data to the auth cookie, and finally adding the auth cookie to the response stream.   The signinManager does NOT set the user principal in the current login request.  The user principal is created in the very next request when the browser sends the auth cookie.

    The auth cookie middleware API looks for the auth cookie in every request.  When when the middleware sees the auth cookie the middleware reads and decrypts the auth token stored within the cookie.  The middleware uses the data to build the user principal and adds the principal to the current request.  At this point, the roles, claims, and username are available globally in the request.  This is why the login logic has a redirect.  You trying to read the user principal the login request which is NOT authenticated.  If you really want the user roles at this point, simply fetch the roles using the UserManager and the username.  Then redirect to whatever page you like depending on the role you find.  Or just redirect to a page of your choice and read the roles from the context.

    and it doesnt seem possible to add c# code to set it up to find the role within site.master code how do you make a variable in the c# side but the name is not available in the html aspx side?  

    This is another example where you are jumping to conclusions. 

    Once the principal is created it is available throughout the current request.  The principal is what allows the web.config authorization to work.  It is also how the [Authorize] attribute in MVC works.

    Cookie Auth reference

    https://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

    https://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application

    Identity Reference

    https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/introduction-to-aspnet-identity

    Principal Reference

    https://docs.microsoft.com/en-us/dotnet/standard/security/principal-and-identity-objects

    Thursday, February 14, 2019 12:01 PM
  • User2142845853 posted

    Thanks useful references , read thru all of them.

    Now trying to still get the claim(s) of the current principal to decide whether to show or hide buttons for admin tasks.  Not very easy to do is it?  Getting the userName for the SiteMaster's Hello (Context...get username) !  is simple, but Roles?  another can of worms.  Why is it so hard to find out whether the logged in user is an admin or not to be able to assign HTML links

    Thursday, February 14, 2019 4:43 PM
  • User475983607 posted

    rogersbr

    Thanks useful references , read thru all of them.

    Now trying to still get the claim(s) of the current principal to decide whether to show or hide buttons for admin tasks.  Not very easy to do is it?  Getting the userName for the SiteMaster's Hello (Context...get username) !  is simple, but Roles?  another can of worms.  Why is it so hard to find out whether the logged in user is an admin or not to be able to assign HTML links

    Again very simple and well documented.  This syntax has not changed for almost 18 years.

    User.IsInRole("Admin");

    Thursday, February 14, 2019 5:33 PM
  • User2142845853 posted

    ok noted, thought that was tried before.  but now? mixing html and c# in the aspx form, maybe it works in Razor only?

                                    <%: if(Context.User.IsInRole("Admin")) 
                                     {%>  
                           <ul class="nav navbar-nav">
                             <li><a runat="server" href="~/">Ho999me</a></li>
                             <li><a runat="server" href="~/About">Ab9999</a></li>
                             <li><a runat="server" href="~/Contact">Con9999t</a></li>
                           </ul> 
                                 <%    } %>

    Thursday, February 14, 2019 7:35 PM
  • User475983607 posted

    rogersbr

    mixing html and c# in the aspx form, maybe it works in Razor only?

    Again, crazy talk; jumping to conclusions.  I have no idea where the markup above is coming from.  You could be showing old-school MVC for all I know.

    Anyway I assume the you are still working on a web forms application and you really need the code blocks that have been in ASP since the mid 90s.

        <div>
            <%
                if (Context.User.IsInRole("Admin"))
                {
            %> 
                        <h1>Hello World</h1>
            <%
                }
            %>
        </div>

    https://support.microsoft.com/en-in/help/976112/introduction-to-asp-net-inline-expressions-in-the-net-framework

    This construct...

    <%: %>

    ... is used in Razor.  Why are you using it in Web Forms?  Are you using Razor in Web Forms?  Otherwise, the compiler is showing you an error, right?

    Thursday, February 14, 2019 8:16 PM
  • User2142845853 posted

    Yes its the same code, had done it in Razor before and thought this syntax was tried but got errors also.  now it runs. thanks

    I have a mixed asp webforms and MVC in the project but this is an aspx webform.  

    and now... what is likely the last thing, making active directory logins work.  If the user has a login on the AD and it returns "success" when sending the username/pwd? then the AD user must log in and be accepted.  Its fine if the admin must enter their info in the Identity database, first but the login has to be authenticated by AD and then by this local system to get access.

    Thought I had that working long ago when trying to implement identitymanager1 but started over about 15 times since then.  Have the AD path but it must authenticate there, then if it does, this system has to also check the identity authentication locally.  So a new user logs in with AD, the system may say hello name, but the admin has to enter them in and after theyre in the local system then if they login with AD it must log them in to this also automatically

    Thursday, February 14, 2019 8:31 PM
  • User475983607 posted

    AD, the system may say hello name, but the admin has to enter them in and after theyre in the local system then if they login with AD it must log them in to this also automatically

    Oh, btw, <%: %> is a single line expression.

    What's the problem exactly?  Once your custom AD login returns a success then sign in the user.  

    var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
    
    //Your AD login logic 
    
    var user = manager.FindByNameAsync(Email.Text).Result;
    if(user != null)
    {
        signinManager.SignIn(user, false, false);
        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
    }

    Thursday, February 14, 2019 9:35 PM
  • User2142845853 posted

    Great, thanks that fits in next.  

    But since switching over the browser to firefox? it looks perfect there.  Went back to Chrome?  Fonts are TOO BIG!  over 2x bigger, and run off the margin geez... another can of worms! 

    Dont recall this problem in other projects but Firefox = PERFECT   internet explorer = slightly large but acceptable   chrome=far too big, have to put zoom to 70% for it to be the same size as firefox at 100%

    Friday, February 15, 2019 1:44 AM
  • User475983607 posted

    rogersbr

    Great, thanks that fits in next.  

    But since switching over the browser to firefox? it looks perfect there.  Went back to Chrome?  Fonts are TOO BIG!  over 2x bigger, and run off the margin geez... another can of worms! 

    Dont recall this problem in other projects but Firefox = PERFECT   internet explorer = slightly large but acceptable   chrome=far too big, have to put zoom to 70% for it to be the same size as firefox at 100%

    The sooner you accept that these bugs are created by you the sooner you'll be able to fix them.  I do not recall ever having a font size issue.  Make sure all your browsers zoom size is 100% and make sure IE is not in compatibility mode.  Also make sure the browser are not overriding fonts or any CSS.  

    If you want help fixing this bug, post code that reproduces this issue.

    Friday, February 15, 2019 11:47 AM
  • User2142845853 posted

    post the code, well its every webform in the project, formname.aspx  and its CHROME that doesnt work, its CHROME showing everything nearly 2x too big

    I can tell the user to only use firefox or IE and deal with this later

    And then the last thing hopefully, is there a wizard to convert a project from c# into vb.net?  I thought I could add an existing vb.net webform into a c# project, no? how can a c# project exist side by side with just one vb.net webform?  

    Friday, February 15, 2019 10:23 PM
  • User475983607 posted

    post the code, well its every webform in the project, formname.aspx  and its CHROME that doesnt work, its CHROME showing everything nearly 2x too big

    I can tell the user to only use firefox or IE and deal with this later

    Every web dev faces browser implementation bugs.  If you want help solving the issue then you'll need to post code that reproduces the issue.  HTML is great. 

    And then the last thing hopefully, is there a wizard to convert a project from c# into vb.net?  I thought I could add an existing vb.net webform into a c# project, no? how can a c# project exist side by side with just one vb.net webform? 

    If it is just one Web Form then convert it to C#.  This is possible with a Web Site project but not a Web Application.

    Friday, February 15, 2019 10:37 PM