How can I configure ASP.Net membership providers through code? - c#

We're using ASP.Net membership providers (the SQL Server provider), and I want to be able to set up an Admin user account as part of our installer. To do this, I need the ASP.Net membership provider configured so that my installer can use it - but I don't want to have to set up a config file for the installer.
So is there a way of configuring an ASP.Net membership through code without writing a custom provider?

Ok, following the solution they conjured up here: http://forums.asp.net/p/997608/2209437.aspx
I created a class which, in the parameterless constructor (which you need) just gets the server and port from the command line arguments. Such that I can go "MembershipInitializer.exe "SomeSqlServer\Instance" 51000.
public class CustomSQLMembershipProvider : SqlMembershipProvider {
private readonly string _server;
private readonly string _port;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.Security.SqlMembershipProvider"/> class.
/// </summary>
public CustomSQLMembershipProvider() {
string[] args = System.Environment.GetCommandLineArgs();
// args[0] is the exe name
_server = args[1];
_port = args[2];
}
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
// Update the private connection string field in the base class.
string connectionString = string.Format(#"Data Source={0},{1};Initial Catalog=aspnetdb;UID=NICCAMembership;PWD=_Password1;Application Name=NICCA;Connect Timeout=120;", _server, _port);
// Set private property of Membership provider.
FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringField.SetValue(this, connectionString);
}
}
In the app.config of your console app (or windows app)
<configuration>
<connectionStrings>
<clear/>
<add name="MembershipDB"
connectionString="Some Bogus String here that gets overrided in the custom class"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?"/>
</authorization>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
connectionStringName="MembershipDB"
applicationName="NICCA"
type="MyInitializeMembershipDB.CustomSQLMembershipProvider, MyInitializeMembershipDB"
requiresUniqueEmail="false"
requiresQuestionAndAnswer="false"/>
</providers>
</membership>
</system.web>
</configuration>
If you are in need of the role provider bit as well, you probably have to override SqlRoleProvider in much the same way.
If you are creating a program to automatically initialize your membership database to a specific state based but the sql server address and port name aren't known until someone enters them into a install wizard, this will do the trick..
Does this help?

Membership.ApplicationName = "yourfbaApplicationame";
MembershipUser user = Membership.CreateUser("admin,"password","emaiol#g.com");
and Make sure that you have the following entries in the config file.
<connectionStrings>
<add connectionString="server=sqd01-1-cll;database=FBA;Integrated Security=SSPI;" name="FBASqlConnString" providerName="System.Data.SqlClient"/>
If you still wanted to use the complete code and dont need to use the config file. Use the below
SqlMembershipProvider ObjSqlMembershipProvider = new SqlMembershipProvider();
SqlRoleProvider ObjSqlRoleProvider = new SqlRoleProvider();
NameValueCollection ObjNameValueCollRole = new NameValueCollection();
NameValueCollection ObjNameValueCollMembership = new NameValueCollection();
MembershipCreateStatus enMembershipCreateStatus;
ObjNameValueCollMembership.Add("connectionStringName", "Connection String Name");
ObjNameValueCollMembership.Add("applicationName", "ApplicatioNAme");
//these items are assumed to be Default and dont care..Should be given a look later stage.
ObjNameValueCollMembership.Add("enablePasswordRetrieval", "false");
ObjNameValueCollMembership.Add("enablePasswordReset", "false");
ObjNameValueCollMembership.Add("requiresQuestionAndAnswer", "false");
ObjNameValueCollMembership.Add("requiresUniqueEmail", "false");
ObjNameValueCollMembership.Add("passwordFormat", "Hashed");
ObjNameValueCollMembership.Add("maxInvalidPasswordAttempts", "5");
ObjNameValueCollMembership.Add("minRequiredPasswordLength", "1");
ObjNameValueCollMembership.Add("minRequiredNonalphanumericCharacters", "0");
ObjNameValueCollMembership.Add("passwordAttemptWindow", "10");
ObjNameValueCollMembership.Add("passwordStrengthRegularExpression", "");
//hard coded the Provider Name,This function just need one that is present. I tried other names and it throws error. I found this using Reflector ..all the rest are take care by the above
//name value pairs
ObjSqlMembershipProvider.Initialize("AspNetSqlMembershipProvider", ObjNameValueCollMembership);MembershipUser user = ObjSqlMembershipProvider.CreateUser("admin,"password","emaiol#g.com");
One this You need to give the connection string in the Config file no other go. If you want that too to be from the code you need to inherit the class

Related

asp.net web api role based authentication custom attribute check if user in role

I was seeking on the internet a bit, but couldn't find exactly what I meant...
Could you please elaborate what exactly I'm doing wrong here and how can I actually accomplish what I need? Issue explained in code comment just below multiple strings.
um.FindByName(username) - of course gives me an error "The entity type ApplicationUser is not part of the model for the current context"
public class MyNewAuthenticationAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
base.OnAuthorization(actionContext);
}
else
{
string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
string[] usernamePasswordArray = decodedToken.Split(':');
string username = usernamePasswordArray[0];
string password = usernamePasswordArray[1];
// Here is the issue. I need to check whether the user is in admin role....
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new WeatherAppDbEntities()));
var user = um.FindByName(username);
var isInRole = um.IsInRole(user.Id, "Admin");
if (// User is admin)
{
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
UPDATE:
Well it all works fine if i use:
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
in the new authentication attribute that i've created... Not really sure though what's the best practice to use ApplicationDbContext() with Ado.net data model created later
Like Stormcloak mentioned it seems that you have two or more DbContexts and therefore you are using more then one databases or connection strings.When creating Asp.Net MVC projects, tamplate comes with some models and controlers, as well as connection string named "DefaultConnection". Visual studio uses SQL Server Express and with connection string it generates database that will store information about users, so when you create your own database (" WeatherAppDb") you are basically working with two databases.
How to prevent this?
1. When creating MVC project check Web.config file for <connectionStrings> tag, if you find something
like tihs
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyMVCProject-20180127104017.mdf;Initial Catalog=aspnet-MyMVCProject-20180127104017;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="WeatherAppDbConnectionString" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
providerName="System.Data.SqlClient" />
The easiest way would be to delete "Default Connection" connection string and rename your "Weather App DbConnectionString" to "Default Connection", so you would be left with just this
//renamed from WeatherAppDbConnectionString to Default Connection
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
providerName="System.Data.SqlClient" />
2. Once you have done first step, just go to your
WeatherAppDbEntities and as StormCloack stated make sure you have "Default Connection" here
public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
{
public WeatherAppDbEntities()
: base("DefaultConnection")
{
}
}
As far as your code, maybe there could be a problem also but not sure, i've modified a little.
WeatherAppDbEntities db = new WeatherAppDbEntities();
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var user = db.Users.Find(username);
It seems that the ApplicationUser identity isn't part of your current context WeatherAppDbEntities. You should implement it to your context.
public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
{
public WeatherAppDbEntities()
: base("DefaultConnection")
{
}
}

The SMTP Server requires a secure connection. 5.7.1 Client was not authenticated

Good day,
I have a MVC application that send out emails, everything works fine locally, however when deploy the code to Windows Server 2012 with IIS8 it throws error above. I have seen some answers with related postrs, however it doesnt seem to work for me. What I tried was this.UseDefaultCredentials = true; as suggested by many but doesnt work for me. Please see my code below.
public class EMMEmailService : SmtpClient
{
public string UserName { get; set; }
public EMMEmailService() :
base(ConfigurationManager.AppSettings["EmmEmailHost"], Int32.Parse(ConfigurationManager.AppSettings["EMMPort"]))
{
//Get values from web.config file:
this.UserName = ConfigurationManager.AppSettings["EMMUserName"];
this.EnableSsl = false;//Boolean.Parse(ConfigurationManager.AppSettings["EMMSsl"]);
//this.UseDefaultCredentials = false;
this.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EMMUserName"], ConfigurationManager.AppSettings["EMMPassword"]);
}
}
and here is the config file
<!--Smptp Server (confirmations emails)-->
<add key="EMMUserName" value="business#xxxxxx"/>
<add key="EMMPassword" value="xxxxxxxxx"/>
<add key="EmmEmailHost" value="x.x.x.x"/>
<add key="EMMPort" value="25"/>
<add key="EMMSsl" value="true"/>
Please assist as I am stuck with this error.

ASP.NET Directory Authentication

I have a .net 2.0 application using Forms Authentication with AD and have a directory for documents which has been configured using a web.config file -
<system.web>
<authorization>
<deny users="?"/>
<allow roles="Security Alerts - Admin"/>
<deny users="*"/>
</authorization>
</system.web>
When testing locally if I run the app and put the FQDN for a document /site/documents/Document1.pdf I am returned to the login page but when I have the site on a server I am able to open the PDFs without any problem. How can I force this so that if a user was to saves the URL of a document and tried to access it directly they would be forced to the login page to authenticate themselves first?
I have the same config for an ADMIN folder which includes aspx pages and works correctly and directs the users the Login page first, is it something to do with the doc type being a pdf as opposed to aspx pages.
Thanks in advance.
By default, .NET authentication does not work on static files such as pdfs.
You need to implement an HTTP Handler to serve your files if the user is authenticated.
It sound like your current authentication is set up and working correctly, so I won't go over the basics of setting that up.
Below is the relevant code which applies to your scenario taken from Kory Becker's helpful article here:
http://www.primaryobjects.com/2009/11/11/securing-pdf-files-in-asp-net-with-custom-http-handlers
You'll obviously have to alter the paths, namespaces and logic to suit your environment (e.g. IIS version) and/or specific file type requirements.
Step 1 - Create a FileProtectionHandler class which implements IHttpHandler
public class FileProtectionHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
switch (context.Request.HttpMethod)
{
case "GET":
{
// Is the user logged-in?
if (!context.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
return;
}
string requestedFile = context.Server.MapPath(context.Request.FilePath);
// Verify the user has access to the User role.
if (context.User.IsInRole("Security Alerts - Admin"))
{
SendContentTypeAndFile(context, requestedFile);
}
else
{
// Deny access, redirect to error page or back to login page.
context.Response.Redirect("~/User/AccessDenied.aspx");
}
break;
}
}
}
public bool IsReusable { get; private set; }
private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
{
context.Response.ContentType = GetContentType(strFile);
context.Response.TransmitFile(strFile);
context.Response.End();
return context;
}
private string GetContentType(string filename)
{
// used to set the encoding for the reponse stream
string res = null;
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
switch (fileinfo.Extension.Remove(0, 1).ToLower())
{
case "pdf":
{
res = "application/pdf";
break;
}
}
return res;
}
return null;
}
}
Step 2 - Add the following sections to your web.config file (with appropriate path/namespace modifications)
<httpHandlers>
...
<add path="*/User/Documents/*.pdf" verb="*" validate="true" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" />
</httpHandlers>
<system.webServer>
...
<handlers>
<add name="PDF" path="*.pdf" verb="*" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" resourceType="Unspecified" />
...
</handlers>
</system.webServer>

DNN 6 Module - How to leverage asynchronous calls

DotNetNuke 6 does not appear to support WebMethods due to modules being developed as user controls, not aspx pages.
What is the recommended way to route, call and return JSON from a DNN user module to a page containing that module?
It appears the best way to handle this problem is custom Httphandlers. I used the example found in Chris Hammonds Article for a baseline.
The general idea is that you need to create a custom HTTP handler:
<system.webServer>
<handlers>
<add name="DnnWebServicesGetHandler" verb="*" path="svc/*" type="Your.Namespace.Handler, YourAssembly" preCondition="integratedMode" />
</handlers>
</system.webServer>
You also need the legacy handler configuration:
<system.web>
<httpHandlers>
<add verb="*" path="svc/*" type="Your.Namespace.Handler, YourAssembly" />
</httpHandlers>
</system.web>
The handler itself is very simple. You use the request url and parameters to infer the necessary logic. In this case I used Json.Net to return JSON data to the client.
public class Handler: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//because we're coming into a URL that isn't being handled by DNN we need to figure out the PortalId
SetPortalId(context.Request);
HttpResponse response = context.Response;
response.ContentType = "application/json";
string localPath = context.Request.Url.LocalPath;
if (localPath.Contains("/svc/time"))
{
response.Write(JsonConvert.SerializeObject(DateTime.Now));
}
}
public bool IsReusable
{
get { return true; }
}
///<summary>
/// Set the portalid, taking the current request and locating which portal is being called based on this request.
/// </summary>
/// <param name="request">request</param>
private void SetPortalId(HttpRequest request)
{
string domainName = DotNetNuke.Common.Globals.GetDomainName(request, true);
string portalAlias = domainName.Substring(0, domainName.IndexOf("/svc"));
PortalAliasInfo pai = PortalSettings.GetPortalAliasInfo(portalAlias);
if (pai != null)
{
PortalId = pai.PortalID;
}
}
protected int PortalId { get; set; }
}
A call to http://mydnnsite/svc/time is properly handled and returns JSON containing the current time.
does anyone else have an issue of accessing session state/updating user information via this module? I got the request/response to work, and i can access DNN interface, however, when i try to get the current user, it returns null; thus making it impossible to verify access roles.
//Always returns an element with null parameters; not giving current user
var currentUser = UserController.Instance.GetCurrentUserInfo();

Administer asp.net website (create new users, assign users to roles, etc.) from a windows app

I have an asp.net web app that uses forms-based authentication, a SqlMembershipProvider (using an encrypted password format), and a SqlRoleProvider. I need to know if it's possible to administer the users (create new users, assign them to roles, etc.) from a windows application - the powers that be don't want any administrative functionality in the web app itself.
Here is the membership provider definition from web.config:
<membership defaultProvider="MyProvider">
<providers>
<add name="MyProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MyConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/MyWebApp"
requiresUniqueEmail="true"
passwordFormat="Encrypted"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
And the role manager definition:
<roleManager enabled="true" defaultProvider="MyRoleManager">
<providers>
<add name="MyRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyConnectionString"
applicationName="/MyWebApp" />
</providers>
</roleManager>
And here is the machineKey definition (necessary to be able to use encrypted passwords):
<machineKey
validationKey="BC50A82A6AF6A015C34C7946D29B817C00F04D2AB10BC2128D1E2433D0E365E426E57337CECAE9A0681A2C736B9779B42F75D60F09F142C60E9E0E8F9840DB46"
decryptionKey="122035576C5476DCD8F3611954C837CDA5FE33BCDBBF23F7"
validation="SHA1"
decryption="AES"/>
So, obviously, I have a Sql Server database that contains the users and roles for the web app. I'd like to create a separate windows app that references the web app assembly, and use the configured MembershipProvider, RoleProvider, and machineKey to create users, assign users to roles, etc. If that's not possible, I can duplicate the configuration settings from web.config within the windows app. But I don't know how to do this either.
Am I way out of line thinking that this is possible? I've tried googling for a solution, but the signal-to-noise ratio is really bad.
Some options:
You could use the Web Site
Administration Tool, which isn't
Windows-Forms-based, but isn't part
of your Web app, either. It comes
with Visual Studio and can be
accessed by clicking the ASP.NET
Configuration icon in the Solution
Explorer.
It's possible to directly manipulate
the provider database used by a
SqlMembershipProvider from a Windows
Forms app, but you might have to be
careful not to break things.
If you were to create a custom
membership provider, you'd be in
control of how membership and role
data is persisted. If you did that
you could create a reusable library
that could be used in the Web app and
a Windows Forms app, too.
I don't think trying to use a SqlMembershipProvider from a Windows Forms app is a practical approach.
I've come up with a solution, based on the other answers (who both got +1), and some other sites out there.
First, I created Application Config file (app.config). It mirrors exactly what is found in web.config from the web app, with the exception of how the connection string was handled:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyConnectionString"
connectionString ="SERVER=abc;UID=def;PWD=hij;Initial Catalog=klm;MultipleActiveResultsets=True"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<add name="MySqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MyConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/MyWebApp"
requiresUniqueEmail="true"
passwordFormat="Encrypted"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MySqlRoleManager">
<providers>
<add name="MySqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyConnectionString"
applicationName="/MyWebApp" />
</providers>
</roleManager>
<machineKey
validationKey="BC50A82A6AF6A015C34C7946D29B817C00F04D2AB10BC2128D1E2433D0E365E426E57337CECAE9A0681A2C736B9779B42F75D60F09F142C60E9E0E8F9840DB46"
decryptionKey="122035576C5476DCD8F3611954C837CDA5FE33BCDBBF23F7"
validation="SHA1"
decryption="AES"/>
</system.web>
</configuration>
Then I created a helper class that provides access to two singletons: a MembershipProvider and a RoleProvider. This turned out to be easier than I thought, once I knew how to do it:
using System.Configuration;
using System.Reflection;
using System.Web.Security;
namespace WebAdminViaWindows
{
internal static class Provider
{
private static readonly string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
static Provider()
{
Membership = CreateMembershipProvider();
Role = CreateRoleProvider();
}
public static MembershipProvider Membership { get; private set; }
public static RoleProvider Role { get; private set; }
private static MembershipProvider CreateMembershipProvider()
{
var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);
var systemWebGroup = config.SectionGroups["system.web"];
if (systemWebGroup == null)
{
throw new ConfigurationErrorsException("system.web group not found in configuration");
}
var membershipSection = systemWebGroup.Sections["membership"];
if (membershipSection == null)
{
throw new ConfigurationErrorsException("membership section not found in system.web group");
}
var defaultProviderProperty = membershipSection.ElementInformation.Properties["defaultProvider"];
if (defaultProviderProperty == null)
{
throw new ConfigurationErrorsException("defaultProvider property not found in membership section");
}
var defaultProviderName = defaultProviderProperty.Value as string;
if (defaultProviderName == null)
{
throw new ConfigurationErrorsException("defaultProvider property is not a string value");
}
var providersProperty = membershipSection.ElementInformation.Properties["providers"];
if (providersProperty == null)
{
throw new ConfigurationErrorsException("providers property not found in membership section");
}
var providerCollection = providersProperty.Value as ProviderSettingsCollection;
if (providerCollection == null)
{
throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
}
ProviderSettings membershipProviderSettings = null;
foreach (ProviderSettings providerSetting in providerCollection)
{
if (providerSetting.Name == defaultProviderName)
{
membershipProviderSettings = providerSetting;
}
}
if (membershipProviderSettings == null)
{
if (providerCollection.Count > 0)
{
membershipProviderSettings = providerCollection[0];
}
else
{
throw new ConfigurationErrorsException("No providers found in configuration");
}
}
var provider = new SqlMembershipProvider();
provider.Initialize("MySqlMembershipProvider", membershipProviderSettings.Parameters);
return provider;
}
private static RoleProvider CreateRoleProvider()
{
var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);
var systemWebGroup = config.SectionGroups["system.web"];
if (systemWebGroup == null)
{
throw new ConfigurationErrorsException("system.web group not found in configuration");
}
var roleManagerSection = systemWebGroup.Sections["roleManager"];
if (roleManagerSection == null)
{
throw new ConfigurationErrorsException("roleManager section not found in system.web group");
}
var defaultProviderProperty = roleManagerSection.ElementInformation.Properties["defaultProvider"];
if (defaultProviderProperty == null)
{
throw new ConfigurationErrorsException("defaultProvider property not found in roleManager section");
}
var defaultProviderName = defaultProviderProperty.Value as string;
if (defaultProviderName == null)
{
throw new ConfigurationErrorsException("defaultProvider property is not a string value");
}
var providersProperty = roleManagerSection.ElementInformation.Properties["providers"];
if (providersProperty == null)
{
throw new ConfigurationErrorsException("providers property not found in roleManagerSection section");
}
var providerCollection = providersProperty.Value as ProviderSettingsCollection;
if (providerCollection == null)
{
throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
}
ProviderSettings roleProviderSettings = null;
foreach (ProviderSettings providerSetting in providerCollection)
{
if (providerSetting.Name == defaultProviderName)
{
roleProviderSettings = providerSetting;
}
}
if (roleProviderSettings == null)
{
if (providerCollection.Count > 0)
{
roleProviderSettings = providerCollection[0];
}
else
{
throw new ConfigurationErrorsException("No providers found in configuration");
}
}
var provider = new SqlRoleProvider();
provider.Initialize("MySqlRoleManager", roleProviderSettings.Parameters);
return provider;
}
}
}
At this point all that's needed is to access the Membership and Role properties of the Provider class. As an example, the following prints out the first 10 users and their roles:
int total;
foreach (MembershipUser user in Provider.Membership.GetAllUsers(0, 10, out total))
{
var sb = new StringBuilder();
sb.AppendLine(user.UserName);
foreach (var role in Provider.Role.GetRolesForUser(user.UserName))
{
sb.AppendLine("\t" + role);
}
Console.WriteLine(sb.ToString());
}
I'm not sure what "best-practice" would be here, but a simple way that should work is this.
Make a new windows app
Add an Application Config file
(app.config)
Copy the appropriate settings into
the app.config (settings from above
^)
Add a reference to System.Web
And copy the code from your web app
that uses the above settings to
connect to the database
That should do what you want.

Categories