Modifying ProfileBase ConnectionString dynamically - c#

I have the following code, which I want to use to modify the ProfileBase connectionString:
ProfileBase profile = ProfileBase.Create(username);
string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
FieldInfo connectionStringField = profile.Providers["MySqlProfileProvider"].GetType().BaseType.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);
profile["FirstName"] = firstName;
profile["Surname"] = surname;
profile.Save();
First of all the connectionStringField always comes back as null, however I can see that profile.Providers does contain MySqlProfileProvider. This is specified within my Web.Config:
<profile defaultProvider="MySqlProfileProvider">
<providers>
<clear/>
<add name="MySqlProfileProvider" connectionStringName="MyApp" applicationName="MyApp" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
<properties>
<add allowAnonymous="false" defaultValue="" name="FirstName" readOnly="false" serializeAs="String" type="System.String"/>
<add allowAnonymous="false" defaultValue="" name="Surname" readOnly="false" serializeAs="String" type="System.String"/>
</properties>
</profile>
My question is how come connectionStringField is coming back as null? Does this mean I cannot modify the connection string like I normally would with a custom MembershipProvider by overriding its Initialize method?

You went one too many basetypes down:
.Providers["MySqlProfileProvider"].GetType()**.BaseType**.GetField
.Providers["MySqlProfileProvider"].GetType().GetField
The following code should work:
string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
Type type = profile.Providers["MySqlProfileProvider"].GetType();
FieldInfo connectionStringField = type.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);

Related

Initializing Membership Provider by code

I am trying to Initialize SQL Membership Provider by code and everything is working fine in the first request only!. When the code below executes again (after refreshing the page for example) I get the following error:
The attribute 'connectionStringName' is missing or empty.
Page Load Code:
MembershipSection membershipSection = (MembershipSection)ConfigurationManager.GetSection("system.web/membership");
string sqlProviderName = "AspNetSqlMembershipProvider";
NameValueCollection providerConfig;
providerConfig = membershipSection.Providers[sqlProviderName].Parameters; // returning empty list in the second request
var _SqlProvider = new SqlMembershipProvider();
_SqlProvider.Initialize(sqlProviderName, providerConfig);
Web.config:
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ConnectionString" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Encrypted" maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" applicationName="/" />
</providers>
</membership>
Any Advice?
how about just keep your data/connectionstring/obj at static level (as like singleton)?
it's not like connectionstring is going to be change throughout the web instance, does it?
static string/dataType _DataToBeRead1timeOnly = null;
static string/dataType DataToBeRead1timeOnly
{
get {
if (_DataToBeRead1timeOnly == null) { _DataToBeRead1timeOnly = .... }
return _DataToBeRead1timeOnly;
}
}

Edit app.config values dynamically

I want to change a value is my app.config dynamically from my project.
This is my app.config:
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<system.web>
<membership defaultProvider="SqlProvider">
<providers>
<clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MySqlConnection"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false"
applicationName="app1" requiresUniqueEmail="false"
passwordFormat="Hashed" maxInvalidPasswordAttempts="6545"
minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers>
</membership>
</system.web>
</configuration>
I want to change the value of 'applicationName' key inside the 'sqlProvider'.
All i could find on the net is people using:
ConfigurationManager.AppSettings["key"]
But this doesnt work for me.
ConfigurationManager.AppSettings["key"] usually works with the setting defined under "AppSettings" section. you may try out the following code-
public class MembershipSetting
{
/// <summary>
/// Gets or sets the name of the setting.
/// </summary>
public string SettingName { get; set; }
/// <summary>
/// Gets or sets the setting value.
/// </summary>
public string SettingValue { get; set; }
}
private List<MembershipSetting> GetMembershipSetting()
{
List<MembershipSetting> settings = new List<MembershipSetting>
{
new MembershipSetting {SettingName = "Dafult Membership Provider", SettingValue = Membership.Provider.ToString() },
new MembershipSetting {SettingName = "Minimum Required Password Length", SettingValue = Membership.MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture) },
new MembershipSetting {SettingName = "Minimum Required Non Alphanumeric Characters",SettingValue = Membership.MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture)},
new MembershipSetting {SettingName = "Password reset enabled", SettingValue = Membership.EnablePasswordReset.ToString()},
new MembershipSetting {SettingName = "Maximum Invalid Password Attempts",SettingValue = Membership.MaxInvalidPasswordAttempts.ToString(CultureInfo.InvariantCulture) },
new MembershipSetting {SettingName = "Attempt windows",SettingValue = Membership.PasswordAttemptWindow.ToString(CultureInfo.InvariantCulture)},
new MembershipSetting {SettingName = "applicationName",SettingValue = Membership.ApplicationName.ToString(CultureInfo.InvariantCulture)}
};
return settings;
}
This article is originally posted here.

Can't use Session in InitializeCulture

When I try to use a Session veriable in InitializeCulture, I get the folowing error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
This is the code where the error is thrown
public class BasePage : Page
{
public string Lang { get; set; }
protected override void InitializeCulture()
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["lang"]))
{
Session["lang"] = Request.QueryString["lang"].ToLower();
}
if (Session["lang"] != null && !string.IsNullOrEmpty((string)Session["lang"]))
{
Lang = (string)Session["lang"];
string selectedCulture = Lang == "nl" ? "nl-BE" : "fr-BE";
UICulture = selectedCulture;
Culture = selectedCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture);
}
base.InitializeCulture();
}
}
}
I changed my Web.Config, as sugested in the error. But It keeps throwing the same error.
<pages enableSessionState="true">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpModules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionStateModule" />
<add type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" name="UrlRewriter"/>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Does anyone has a solution? Thanks!!!
Try to set enableSessionState=true in the pages section.
<system.web>
<pages enableSessionState="true">
</system.web>
Also, if you're using IIS7 on Windows 2008, your modules should be inside the <system.webServer> section, instead of <system.web>.

httpModules not working on iis7

I have the following module
public class LowerCaseRequest : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(this.OnBeginRequest);
}
public void Dispose() { }
public void OnBeginRequest(Object s, EventArgs e) {
HttpApplication app = (HttpApplication)s;
if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) {
if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower();
response.SuppressContent = true;
response.End();
}
if (!app.Context.Request.Url.ToString().StartsWith(#"http://zeeprico.com")) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(#"http://zeeprico.com", #"http://www.zeeprico.com");
response.SuppressContent = true;
response.End();
}
}
}
}
the web.config looks like
<system.web>
<httpModules>
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<add name="LowerCaseRequest" type="LowerCaseRequest" />
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
It works grate on my PC running XP and IIS 5.1
but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out.
Thanks
On IIS7 and higher use
<configuration>
<system.webServer>
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
</system.webServer>
</configuration>
Above is correct for IIS 7.5
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
the only problem I got, is that instance of application pool for particular application should be set to managed Pipeline = Integrated, not Classic..
or:
Using Classic Mode
If your application is to use Classic mode, then make sure that your application is configured for that type of pool and your modules are configured in system.web section and not in system.webServer section of web.config file.
In IIS go to feature view select module
double click to module then right click and press (Add Managed Module)
then put name and type as defined in web.config
example:
<httpModules>
<add name="CustomModule" type="WebApplication.Security.CustomModule" />
</httpModules>

Using MySql MySQLMembershipProvider - autogenerateschema="true" not working?

I'm trying to use the MySQLRoleProvider(MySql.Web, Version=6.2.2.0) with Visual Web Developer 2008.
When trying to add a role I get an exception "Table 'test.my_aspnet_applications' doesn't exist"
if (!Roles.RoleExists("TestRole"))
{
Roles.CreateRole("TestRole");
}
Can someone tell me where I went wrong. Or tell me how to generate / find the correct database script to create the role, membership, profile ... MySql tables.
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider"/>
<add autogenerateschema="true" connectionStringName="LocalMySqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</membership>
<profile enabled="true" defaultProvider="MySQLProfileProvider">
<providers>
<remove name="MySQLProfileProvider"/>
<add name="MySQLProfileProvider" autogenerateschema="true" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="true" defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider"/>
<add autogenerateschema="true" connectionStringName="LocalMySqlServer" applicationName="/" name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</roleManager>
Have you used the ASP.Net configuration tool to switch your application's provider to the MySQL provider? I believe this is what triggers the MySQL provider to automatically generate the schema.
Follow this codeproject howto and you'll be fine.
If your database won't generate try this:
Create a custom ContextInitializer and add this to the Global.asax:
Database.SetInitializer(new CreateMySqlDatabaseIfNotExists<MyContext>());
internal class CreateMySqlDatabaseIfNotExists<TContext>: IDatabaseInitializer<TContext> where TContext : MyContext
{
public void InitializeDatabase(TContext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(false))
throw new InvalidOperationException("The model has changed!");
}
else
{
CreateMySqlDatabase(context);
Seed(context);
}
}
private void CreateMySqlDatabase(TContext context)
{
try
{
context.Database.Create();
return;
}
catch (MySqlException ex)
{
// Ignore the parse exception
if (ex.Number != 1064)
{
throw;
}
}
// Manually create the metadata table
using (var connection = ((MySqlConnection) context
.Database.Connection).Clone())
using (var command = connection.CreateCommand())
{
command.CommandText =
#"
CREATE TABLE __MigrationHistory (
MigrationId mediumtext NOT NULL,
CreatedOn datetime NOT NULL,
Model mediumblob NOT NULL,
ProductVersion mediumtext NOT NULL);
ALTER TABLE __MigrationHistory
ADD PRIMARY KEY (MigrationId(255));
INSERT INTO __MigrationHistory (
MigrationId,
CreatedOn,
Model,
ProductVersion)
VALUES (
'InitialCreate',
#CreatedOn,
#Model,
#ProductVersion);
";
command.Parameters.AddWithValue(
"#Model",
GetModel(context));
command.Parameters.AddWithValue(
"#ProductVersion",
GetProductVersion());
command.Parameters.AddWithValue(
"#CreatedOn",
DateTime.Now);
connection.Open();
command.ExecuteNonQuery();
}
}
private byte[] GetModel(TContext context)
{
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(
memoryStream,
CompressionMode.Compress))
using (var xmlWriter = XmlWriter.Create(
gzipStream,
new XmlWriterSettings {Indent = true}))
{
EdmxWriter.WriteEdmx(context, xmlWriter);
}
return memoryStream.ToArray();
}
}
private string GetProductVersion()
{
return typeof (DbContext).Assembly
.GetCustomAttributes(false)
.OfType<AssemblyInformationalVersionAttribute>()
.Single()
.InformationalVersion;
}
protected void Seed(TContext context)
{ // ...
context.SaveChanges();
}
}

Categories