0

I am developing a setup program (EXE file) which will deploy and configure an ASP.NET website and corresponding ASP.NET membership database.

I have a console app with the following app.config, which includes a system.web section:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="LocalSqlServer1" connectionString="Server=.\NAME;Database=aspnetdb;Integrated Security=true" />
  </connectionStrings>
  <system.diagnostics>
    <sources>
      <!-- This section defines the logging configuration for My.Application.Log -->
      <source name="DefaultSource" switchName="DefaultSwitch">
        <listeners>
          <add name="FileLog" />
          <!-- Uncomment the below section to write to the Application Event Log -->
          <!--<add name="EventLog"/>-->
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
      <add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
      <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
      <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    </sharedListeners>
  </system.diagnostics>
  <system.web>
    <roleManager defaultProvider="SqlProvider1"
      enabled="true"
      cacheRolesInCookie="true"
      cookieName=".ASPROLES"
      cookieTimeout="30"
      cookiePath="/"
      cookieRequireSSL="false"
      cookieSlidingExpiration="true"
      cookieProtection="All" >
      <providers>
        <add
          name="SqlProvider1"
          type="System.Web.Security.SqlRoleProvider"
          connectionStringName="LocalSqlServer1"
          applicationName="SampleApplication" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

However, I can't seem to get Roles or Membership to work, no matter what I do to app.config. It's as if the whole system.web section is invalid or missing. Mostly I am getting the below error message, sometimes I get "Roles are not enabled".

Error reading system.web roleManager

Is it possible to utilize ASP.NET Membership and Roles in a console app? and configured the normal way via system.web section? If so, how? Please note the Visual Studio project is saved on a network share.

Update - Compiler Settings as requested

enter image description here

Update - Please note it is being run from a network share

The exception has an inner exception which is a security exception, caused because the solution is on a network share, anyone who can provide a fix for running solutions from network share will get the bounty!

Update - Exception details as requested

System.Configuration.ConfigurationErrorsException was unhandled
  BareMessage=An error occurred creating the configuration section handler for system.web/roleManager: Request failed.
  Filename=L:\InternetSharePointRepository\InternetSharePointSolution\InternetSharePointConsoleApplication1\bin\Debug\InternetSharePointConsoleApplication1.vshost.exe.Config
  Line=34
  Message=An error occurred creating the configuration section handler for system.web/roleManager: Request failed. (L:\InternetSharePointRepository\InternetSharePointSolution\InternetSharePointConsoleApplication1\bin\Debug\InternetSharePointConsoleApplication1.vshost.exe.Config line 34)
  Source=System.Web
  StackTrace:
       at System.Web.Security.Roles.Initialize()
       at System.Web.Security.Roles.EnsureEnabled()
       at System.Web.Security.Roles.CreateRole(String roleName)
       at InternetSharePointConsoleApplication1.Module1.Main() in L:\InternetSharePointRepository\InternetSharePointSolution\InternetSharePointConsoleApplication1\Module1.vb:line 7
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Security.SecurityException
       GrantedSet=""
       Message=Request failed.
       PermissionState=<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Level="Minimal"/>
</PermissionSet>

       RefusedSet=""
       Source=mscorlib
       Url=""
       StackTrace:
            at System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)
            at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
            at System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(ConstructorInfo ctor)
            at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
            at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
            at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
            at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
       InnerException: 

enter image description here

Chris Cannon
  • 1,157
  • 5
  • 15
  • 36

2 Answers2

1

Change the TargetFramework to the normal .Net Framework 4 instead of Client. Client does not include System.Web. If that's not the issue add the System.Web.dll to your project as a reference. You may have to browse to it.

Also, you'll need to add the Membership section to system.web, something like:

<membership defaultProvider=”AspNetSqlProvider”>
 <providers>
 <clear/>
 <add name=”AspNetSqlProvider” connectionStringName=”SqlConnection” type=”System.Web.Security.SqlMembershipProvider”
enablePasswordRetrieval=”false”
enablePasswordReset=”true”
requiresQuestionAndAnswer=”true”
passwordFormat=”Hashed”
applicationName=”TestApp”/>
 </providers>
 </membership>

Here's an example of the entire system.web in your config:

  <system.web>   
    <roleManager enabled="true">    
        <providers>    
            <clear/>    
            <add name="AspNetSqlRoleProvider" connectionStringName="MyAspNetDB"     
                applicationName="/SampleRolesApp"     
                type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />    
        </providers>    
    </roleManager>    
    <membership>    
        <providers>    
            <clear/>    
            <add name="AspNetSqlMembershipProvider"     
                connectionStringName="MyAspNetDB"     
                enablePasswordRetrieval="false"     
                enablePasswordReset="true"     
                requiresQuestionAndAnswer="true"     
                applicationName="/SamplesRolesApp"     
                requiresUniqueEmail="false"     
                passwordFormat="Hashed"     
                maxInvalidPasswordAttempts="5"     
                minRequiredPasswordLength="7"     
                minRequiredNonalphanumericCharacters="1"     
                passwordAttemptWindow="10"     
                passwordStrengthRegularExpression=""                          
                type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />    
        </providers>    
    </membership>            
    <authentication mode="Forms" /> 
  </system.web>
TrevorBrooks
  • 3,590
  • 3
  • 31
  • 53
  • I'm pretty sure I've done both of those things, I'll double check though. For example, it wouldn't compile if system.web wasn't already referenced, it would error on imports system.web.security and Roles.CreateRole? – Chris Cannon Jun 14 '14 at 15:01
  • When I created the project I set the target framework to .NET 3.5 because it needs to interface with SharePoint 2010 dlls. – Chris Cannon Jun 14 '14 at 15:05
  • I don't see the Membership section in your app.config, you'll need to add that. – TrevorBrooks Jun 16 '14 at 16:34
  • 1
    Darn it! Just realized it's cuz the solution is on a network share which is causing a security exception. Thanks Microsoft for the clear-as-mud exception message! Your code works by the way, just not when run from a network share. – Chris Cannon Jun 16 '14 at 17:03
  • I award the bounty to someone before it expires, given that no one else has answered, it will probably be you! I still have the problem running it from a network share, this is the root cause of the exception... – Chris Cannon Jun 17 '14 at 07:40
  • Yeah can you give me the exact security exception you're getting? – TrevorBrooks Jun 17 '14 at 14:59
  • Actually, this sounds like what you need: http://stackoverflow.com/questions/6009791/silverlight-project-build-fails-in-vs2010-when-project-is-on-a-mapped-network-dr – TrevorBrooks Jun 17 '14 at 15:49
  • I've added the details of the exception above. – Chris Cannon Jun 18 '14 at 09:33
  • The only resource I could find on this is here: http://msdn.microsoft.com/en-us/library/dd409252(VS.100).aspx – TrevorBrooks Jun 18 '14 at 14:23
1

Many thanks to TrevorBrooks for confirming that Membership and RoleManager sections do work in App.Config and can be used just like in a web application.

However, you may find that exceptions are thrown when debugging or running from a network location - an unusual scenario that was the root cause of my problem. The best workaround I have found is to change the build output path to a path on the local file system - as highlighted in the image below.

enter image description here

Hope this helps someone else!

Chris Cannon
  • 1,157
  • 5
  • 15
  • 36
  • This isn't the answer to your original question which was: "Is it possible to utilize ASP.NET Membership and Roles in a console app? and configured the normal way via system.web section? If so, how?" – TrevorBrooks Jul 01 '14 at 13:23
  • True but it says in bold font shortly after "Update it is being run from a network share". Stack Overflow allows you to edit the question, as I have done so now to be more clear. Don't expect to be down voted by someone I awarded a bounty to! Most people would be glad about receiving a bounty? – Chris Cannon Jul 01 '14 at 18:36
  • Normally two separate questions are two separate posts. – TrevorBrooks Jul 01 '14 at 19:38
  • Don't remember you complaining about that before I awarded you the bounty... You were proposing solutions to the network share issue, with some copying and pasting going on, so why are you giving me a hard time? – Chris Cannon Jul 01 '14 at 21:44
  • Edit your answer and I'll add it back (can't add it back until you make an edit) – TrevorBrooks Jul 02 '14 at 13:21