Cannot add user+role record in aspnet Identity - asp.net

Web Forms project / VB / ASP 4.5.2 / VS2015
EntityFramework 6.1.3 / Identity.EntityFramework 2.2.1
Other packages in NuGet all show current versions
I have a webapp using the VS template which includes pages that create users etc. I have created users and they can/can not access folders according to the web.config in the various folders.
Now I need to add roles and attach roles to users.
I can create roles using
Dim createRole As String = RoleTextBox.Text
Dim RoleManager = New RoleManager(Of IdentityRole)(New RoleStore(Of IdentityRole)(New ApplicationDbContext()))
Try
If RoleManager.RoleExists(createRole) Then
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' already exists. Please specify a different role name."
Return
End If
RoleManager.Create(New IdentityRole(createRole))
etc
Next I need to attach roles to users, for which I have got:
Public Class admin_superadmin
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim UserManager = New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(New IdentityDbContext()))
UserManager.AddToRole(DropDownList5.SelectedValue, DropDownList6.SelectedValue)
Label1.Text = DropDownList5.SelectedItem.Text + " Was added to the " + DropDownList6.SelectedValue + " Role."
End Sub
However when run this fails at the line usermanager.addtorole with the message:
System.InvalidOperationException: UserId not found.
The DB tables were created by the app. In table AspNetUserRoles are fields UserID, RoleID.
Much appreciated if someone could help identify the problem.

Coming to this as a front-end designer wanting to authenticate users but having never used Identity or MVC, in the end I figured it out and these would have been a ten minute way to get a simple web app up and running with authentication and roles, using a remote db:
File > New Project > Web > ASP.NET web application > Web forms
In web.config, change the DefaultConnection to point to my existing remote MSSQL db
In the solution explorer Account > Register.aspx > View in Browser
in the browser, register a new User: in the remote database, all needed authentication tables are set up for me and I can now add and modify users from the VS template project pages in the Account folder. But I cannot use Roles yet.
Project > Add New Item > VB (for me) > Data > ADO.NET Entity Data model > EF Designer from database > make it refer to DefaultConnection > tick all tables
I can now create an admin folder and in it a page with a few controls and the code
UserManager.AddToRole(user.Id, ) will succeed and not give the error reported in my original question.
Hope these steps might help another beginner.

Related

Understanding Directory Securities with an ASP.NET Web Application

I have a requirement to create a directory on my applications server which is secure to all, but the application itself.
I have read this article
System.IO.Directory.CreateDirectory with permissions for only this current user?
Converting to VB, the code it suggests is:
Dim ds As New DirectorySecurity()
Dim sid As New SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, Nothing)
Dim ace As New FileSystemAccessRule(sid,
FileSystemRights.FullControl,
AccessControlType.Allow)
ds.AddAccessRule(ace)
Directory.CreateDirectory(Dir, ds)
But when I follow that code instruction there, I cannot add files to the directory I have created.
I am guessing I should change the value of WellKnownSidType but I do not know what to!
To recap - what I need is a directory which my application can read and write to, but a user cannot access from a web browser to download any content.
Any help much appreciated!

Using Multiple Config files for a shared MVC Project

I have an MVC application that consists of a directory with all the necessary files to run except the css and master view. In IIS, I have several sites set up that all use the same directory, but then have virtual directories set up for each site's unique css and template. This works very well, although I am now wanting to have a separate config for each unique site (for basic settings like site id to query my db, etc). I created new virtual directories for each site and added a config.xml in each, added the following to my global.asax.cs file in the application start method:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
//read in all the application variables from the config file on startup
XmlDocument Doc = new XmlDocument();
Doc.Load(Server.MapPath("/Config/Config.xml"));
XmlNodeList VarLst = Doc.DocumentElement.SelectNodes("//AppVars/*");
foreach (XmlNode VarNod in VarLst)
{
RecursiveDescent(VarNod, "");
}
string[] AppVars = new string[Application.Count];
AppVars = Application.AllKeys;
//How do I now use Application.AllKeys from a controller?
}
Now, I have my keys, but can't seem to figure out how to use them in a controller. Normally, if I was using the app settings in the web config and wanted to set my siteId, I'd just use:
int siteId = Convert.ToInt16(WebConfigurationManager.AppSettings["SiteId"]);
but now I want to use
Application["SiteId"];
but it's not like a webforms code behind that inherits from the page class and I'm not getting the concept on how to get the Applications settings in an MVC controller.
As per this other question: Access "Application" object in ASP.Net MVC to store application wide variables
this.HttpContext.Application["SiteId"]

ApplicationPoolIdentity user cannot modify files in shared folder in Windows Server 2008

I am creating directories, and writing files to a shared folder within my web application that is being hosted on Windows Server 2008. I am running the application pool with an identity of ApplicationPoolIdentity.
To give you an idea of my setup so far.. I've set permissions to the root of my web application root directory to two different users: "IUSR" and "IIS APPPOOL\MYPOOL". I'm using the name "MYPOOL" as the name of my application pool, so it's easy to reference.
The application is unable to modify and write to a shared folder. I right clicked the shared folder that I'm creating directories in and writing to, and clicked on the "Security" tab. Then I clicked "Edit". Under objects, I checked "Computer". Then under LOCATION, I've tried the machine/server running my web application. I wasn't able to find my "MYPOOL" user however under the users. I tried to follow this link, but it wasn't very complete. I don't know which user to use. I continue to get a System.IO exception because it doesn't have permissions. Once I know which user to use, I will have to give "Modify" permissions to the "ExportPath" directory.
http://grekai.wordpress.com/2011/05/23/permissions-for-shared-folder-for-iis-7-application-pool-identity-across-domain/
For a quick test, I made a dummy page called FilePermissionsTest.aspx, and put some code to write a file to create a directory and write a file in my Page_Load event of the code behind. But I haven't gotten far enough to test it.
...
<div>
Check to see if the file "_File_Permissions_Test.txt" was written to <% Response.Write(Data.ConfigurationHelper.ValueFromConfiguration("ExportPath", Nothing))%>
</div>
...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim exportPath As String = Data.ConfigurationHelper.ValueFromConfiguration("ExportPath", Nothing)
If exportPath = String.Empty Then Return
Dim exportDirectory As DirectoryInfo = Directory.CreateDirectory(exportPath)
Dim writer As StreamWriter = File.CreateText(Path.Combine(exportDirectory.FullName, "_File_Permissions_Test.txt"))
writer.WriteLine("TESTING... " + DateTime.Now().ToString)
writer.Flush()
writer.Close()
End Sub
as I've written at my post :
GreKai.WordPress.com
You should have entered the computer name and not the ApplicationPoolIdentity. That was your problem.Try it out ! It should work.
The steps are :
Go to the Shared Folder –> right click –> properties -> security –>edit –> add (so far as usual ) -> choose object types –> check on computers –> now enter the computer name where your application is working from , where you published your application.
To solve this one, our server administrator created a domain user in the domain controller called domainuser. Then I went into the IIS 7 application pool advanced settings, and changed the Identity from ApplicationPoolUser to "{domain name}\domainuser" (under the Custom Account field) and entered the password for the account. Then I set write permissions (under the folder properties > security) on that shared folder for {domain name}\domainuser. It worked great.

ASP.NET loses session data when delete directory on WebApplications

I'm creating a web application in asp.net mvc2 and I'm having a little problem in an interesting situation that I assume is a default behaviour on webapplications. (sessionstate= inproc)
When i delete a directory inside the webapplication root Directory, my session data is cleaned.
I've read some questions from people asking for a solution, but not much about the problem, does anyone know how to prevent this behaviour?
Note: I don't want to move directory for other "subdomain" served by other instance of IIS, and don't want to change sessionstate for sqlserver
Thanks in advance for your help.
THANKS GUYS, FOUND THE SOLUTION SOMEWHERE ON A LINK OF THAT ARTICLE.
i've added on my global.asax Application_Start the folowing code:
Dim p As System.Reflection.PropertyInfo = GetType(HttpRuntime).GetProperty("FileChangesMonitor", Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
Dim o As Object = p.GetValue(Nothing, Nothing)
Dim f As System.Reflection.FieldInfo = o.GetType.GetField("_dirMonSubdirs", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
Dim monitor As Object = f.GetValue(o)
Dim m As System.Reflection.MethodInfo = monitor.GetType.GetMethod("StopMonitoring", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
m.Invoke(monitor, New Object() {})
THANKS.
http://dotnetslackers.com/Community/blogs/haissam/archive/2008/11/12/disable-session-expiration-when-using-directory-delete.aspx
Most likely relates to this one: ASP.NET Deleting a directory results in application restart.
this blog post might clarify things a bit for you: Deleting Directory in ASP.net 2.0
My suggestion would be to create a virtual directory and manipulate the contents of that directory (instead of touching app directory itself).

ASP.net DAL DatasSet and Table Adapter not in namespace - Northwind Tutorial

I've been attempting to walk through the "Creating a Data Access Layer" tutorial found http://www.asp.net/learn/data-access/tutorial-01-cs.aspx
I create the DB connection, create the typed dataset and table adapter, specify the sql, etc.
When I add the code to the presentation layer (in this case a page called AllProducts.aspx) I am unable to find the NorthwindTableAdapters.ProductsTableAdapter class. I tried to import the NorthwindTableAdapters namespace, but it is not showing up. Looking in the solution explorer Class View confirms that there is a Northwind class, but not the namespace I'm looking for.
I've tried several online tutorials that all have essentially the same steps, and I'm getting the same results.
Can anyone give me a push in the right direction?
I'm getting error: Namespace or type specified in the Imports 'NorthwindTableAdapters' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member.
I think I might need to add a reference OR they may be creating a separate class and importing it into their main project. If that's the case, the tutorials do not mention this.
SuppliersTest2.aspx.vb:
Imports NorthwindTableAdapters
Partial Class SuppliersTest2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim suppliersAdapter As New SuppliersTableAdapter
GridView1.DataSource = suppliersAdapter.GetAllSuppliers()
GridView1.DataBind()
End Sub
End Class
I also had the same problem and finally found the solution. try followings;
1) Right click on your DataSet and select properties
2) Under the dataset properties, set a name for Prifix property.
3) debug your application.
4) in your application(C#.net) import the namesapce as
using DALexample.MyTableAdapters;
DALexample is your project name...
You need to compile the code after creating the xsd file, but before you add code to the use the table adapter.
So, looking at the tutorial, before you create the AllProducts.aspx, you need to build the code. This will auto-generate the NorthwindTableAdapters namespace and the code behind it you will need to continue on with the tutorial
Your web project must have been duplicated for some reson. Create an entirely new web project and copy all your current code to it. Then try to run. it will work.
I got stumped on this for a bit also - the problem is likely that you created the project using New Project->ASP.NET Web Application. An Application project isn't the same thing as a Web Site project. Create a project using New Web Site->ASP.NET Web Site. Then drop all tutorial files into the root folder in Solution Explorer overwriting all.
I noticed something was up when I tried to recreate the DataSet and the wizard didn't autostart asking me to put it the App_Code folder. The App_Code folder must be specific to ASP.NET Web Sites and not Applications.
Go to the web.config file and under Pages - namespaces, see if there is a clear command, try removing the clear command:
<pages styleSheetTheme="DataWebControls">
<namespaces>
<clear/>
For me, instead of needing to create a new website and copying all of the source files (except the web.config file) to it, I was just able to make a backup of my web.config file, then delete the web.config file, then go to add new item and add a new web.config file, that created a new file with the defaults I needed, then I just copyed the custom entries from my old web.config file to the new one, and I was good to go.
I was also struggling with this but solved it by closing down Visual Studio, reopening my project, and finally building the solution (CTRL+SHIFT+B).

Resources