Change provider connectionstring of sessionState aspnet at runtime - asp.net

in order to change the connection string of the providers in aspnet membership with
custom provider(nauckit) I use this:
var connectionStringField = Membership.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);
var roleField = Roles.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);
var profileField = ProfileManager.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
Where connectionstring is the connectionstring I want.
But I cannot change for the sessionState.
My webconfig is like this:
<membership defaultProvider="PgMembershipProvider">
<providers>
<clear />
<add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="myConnection1" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" maxInvalidPasswordAttempts="100" passwordFormat="Hashed" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25">
<providers>
<clear />
<add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="myConnection1" />
</providers>
</roleManager>
<profile enabled="true" defaultProvider="PgProfileProvider">
<providers>
<clear />
<add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="myConnection1" />
</providers>
<properties>
<add name="property1" type="long"/>
</properties>
</profile>
<sessionState mode="Custom" customProvider="PgSessionStateStoreProvider">
<providers>
<clear />
<add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="myConnection1" />
</providers>
</sessionState>
Any help?
Thanks!

Just call global.SetStore in any IHttpModule that you have on your website.
DAMN i'm so happy this worked.
Global.asax.cs:
private FieldInfo StorePrivateMemberInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
public void SetStore()
{
var store = StorePrivateMemberInfo.GetValue(this.Modules["Session"]);
if (store == null || !(store is Microsoft.Web.SessionState.SqlInMemoryProvider))
{
var config = new NameValueCollection();
var cnn = "Your connection string";
config.Add("connectionString", cnn);
config.Add("timeout", "30");
simp = new Microsoft.Web.SessionState.SqlInMemoryProvider();
simp.Initialize("SqlInMemoryProvider", config);
StorePrivateMemberInfo.SetValue(this.Modules["Session"], simp);
}
Session["GLOBAL_ASAX_CHECK"] = true;
}

Related

Not working login with roles (web forms)

I want create a authentication module with 3 roles in asp.net web forms.
I created a simple database with one table user (id, login, password, role).
I have a 3 roles: user, user2 and admin.
I would like to users with specific roles were redirected to individual pages.
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication6
{
public partial class Login : System.Web.UI.Page
{
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbtestConnectionStrings"].ConnectionString;
SqlConnection _connection= new SqlConnection(DatabaseConnectionString);
protected void Page_Load(object sender, EventArgs e) {
}
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select * from user where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
var rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd["login"].ToString();
string role = rd["role"].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
}
}
Result:
web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<connectionStrings>
<add name="dbtestEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ROG-KOMPUTER\SQLEXPRESS;initial catalog=dbtest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="dbtestConnectionString" connectionString="Data Source=ROG-KOMPUTER\SQLEXPRESS;Initial Catalog=dbtest;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Can see two flaws
User is a keyword and you are using that as a table name
When assigning parameter value you are specifiying #
try below code
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
SqlCommand comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
Its look like that:
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
Label1.Text = exception.Message;
}
}

Uploaded website does not sent emails

I have uploaded my website to a known hosting server and i have a contact form, the weird thing is that when i run the website from visual studio (asp.net language) is sending the emails fine on my inbox.From the time that i uploaded it on the hosting server it gives the error: failure sending the email.I am using smtp.gmail.com, port:587,username and pass and ssl enabled.
protected void sendClientMail(string emailto)
{
try
{
var mail = new MailMessage
{
BodyEncoding = Encoding.UTF8,
From = new MailAddress(ConfigurationManager.AppSettings["MAILFROM"])
};
mail.To.Add(emailto);
mail.Bcc.Add(ConfigurationManager.AppSettings["MAILBCC"]); //sends to my email also
mail.Subject=ConfigurationManager.AppSettings["CLIENT-MAILSUBJECT"];
mail.IsBodyHtml = true;
#region //Load Email Control and get HTML string
string mailBody = "";
{
PrintPlaceHolder.Visible = true;
var sb = new StringBuilder();
var writer = new HtmlTextWriter(new StringWriter(sb));
var emailctl = LoadControl("~/Controls/ClientEmail.ascx") as ClientEmail;
if (emailctl != null)
{
emailctl.Name = txtName.Text;
emailctl.IntroName = txtName.Text + " " + txtSurname.Text;
emailctl.Surname = txtSurname.Text;
emailctl.Mobile = txtMobile.Text;
emailctl.Phone = txtPhone.Text;
emailctl.City = txtCity.Text;
emailctl.Street = txtStreet.Text;
emailctl.Message = txtmessage.Text;
emailctl.Email = txtEmail.Text;
emailctl.Country = ddlCountry.SelectedValue;
PrintPlaceHolder.Controls.Add(emailctl);
emailctl.RenderControl(writer);
}
mailBody = sb.ToString();
if (emailctl != null)
{
emailctl.Dispose();
}
writer.Dispose();
sb.Clear();
PrintPlaceHolder.Visible = false;
}
#endregion
mail.Body = mailBody;
//mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential (ConfigurationManager.AppSettings["MAILFROM"], ConfigurationManager.AppSettings["PASS"]);
client.Host = ConfigurationManager.AppSettings["SMTPSERVER"];
client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPORT"]);
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl= false;
//client.UseDefaultCredentials = true;
client.Send(mail);
clearFields();
Response.Write("<script>alert('"+ConfigurationManager.AppSettings["MAILSUCCESS"]+"');</script>");
}
catch (Exception e)
{
Response.Write("<script>alert('"+ ConfigurationManager.AppSettings["MAILFAIL"] +" Error: "+e+"')</script>");
}
}//end method
Web.config file code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="CLIENT-MAILSUBJECT" value="Mario Website - Confirmation Email"/>
<add key="MY-MAILSUBJECT" value="Mario Website - Email Sent"/>
<add key="MAILFROM" value="mariotec#mario26tech.com"/>
<add key="MAILBCC" value="nikolaou_marios#hotmail.com"/>
<add key="SMTPSERVER" value="sns41.win.hostgator.com"/>
<add key="SMTPPORT" value="26"/>
<add key="PASS" value="pass"/>
<add key="MAILSUCCESS" value="Email was sent successfully, thank you for your interest!!!"/>
<add key="MAILFAIL" value="There was an error while sending the email."/>
</appSettings>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear/>
<add value="Index.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
I have contacted the hosting provider without any help.
Thanks in advance.

Folder requests not being handled by ASP.NET

I'm attempting to write a custom HttpHandler in order to handle all of my 404 errors. The handler is catching and handling all file types that I've specified but for some reason it isn't handling requests for folders, i.e. if I put in mysite.com/foo/bar.html or mysite.com/foo/bar.aspx it handles it and shows the right error page, but if I enter mysite.com/foo/ it shows a completely blank page, with no source code or anything. Here's the code for the handler:
public class RedirectHttpModule :IHttpHandler, IHttpModule {
public RedirectHttpModule() {
//
// TODO: Add constructor logic here
//
}
public void Dispose() { }
public void Init(HttpApplication context) {
context.Error += new EventHandler(ErrorHandler);
}
private void ErrorHandler(object sender, EventArgs e) {
HttpApplication application = (HttpApplication)sender;
application.Context.Response.TrySkipIisCustomErrors = true;
Exception lastError = application.Server.GetLastError();
HttpException ex = lastError as HttpException;
ILog _logger = LogManager.GetLogger(typeof(Page));
string page = "~/404.aspx";
if (ex != null) {
application.Server.ClearError();
application.Context.Handler = System.Web.UI.PageParser.GetCompiledPageInstance(page, application.Server.MapPath(page), application.Context);
string username = application.Context.User.Identity.Name;
if (!String.IsNullOrEmpty(username)) _logger.ErrorFormat("HTTP Error {0}: {1} Username: {2}", ex.GetHttpCode().ToString(), ex.Message, username);
else _logger.ErrorFormat("HTTP Error {0}: {1}", ex.GetHttpCode().ToString(), ex.Message);
}
else {
application.Context.Handler = System.Web.UI.PageParser.GetCompiledPageInstance(page, application.Server.MapPath(page), application.Context);
}
}
public bool IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
if (!File.Exists(context.Request.PhysicalPath)) {
throw new HttpException(404, String.Format("The file or directory {0} does not exist.", context.Request.PhysicalPath));
}
else {
context.Response.TransmitFile(context.Request.PhysicalPath);
}
}
}
and here's the relevant sections of the Web.config:
<handlers>
<add name="html-to-aspx-isapi" path="*.html" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="html-to-aspx" path="*.html" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" preCondition="integratedMode" />
<add name="htm-to-aspx-isapi" path="*.htm" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="htm-to-aspx" path="*.htm" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" preCondition="integratedMode" />
<add name="asp-to-aspx-isapi" path="*.asp" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="asp-to-aspx" path="*.asp" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" preCondition="integratedMode" />
<add name="RedirectHttpModule" modules="RedirectHttpModule" preCondition="" path="*" verb="*" resourceType="Either"/>
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<add name="RedirectHttpModule" type="RedirectHttpModule" preCondition="managedHandler"/>
</modules>
For whatever reason, even though it's running Integrated instead of Classic, if I remove the first 6 handlers, it will no longer handle html, htm or asp requests with ASP.NET. I'm beginning to suspect there's some sort of configuration problem. Any ideas?
Thanks in advance for all your help.
In IIS, set the default 404 page to point to your handler. What's happening is that IIS is handling the 404 before it ever makes it to the .net worker process.

Login control doesn't redirect the user to another page

I am developing VS2010. this is my problem:I have a Form that authenticate user and then redirect them to another page .the redirection is not working If I write username and password system say nothing and two textboxes being empty :
here is a part of my login control
<asp:Login ID="LoginUser" runat="server" EnableViewState="false"
RenderOuterTable="false" DestinationPageUrl="~/verwaltung.aspx" MembershipProvider="AspNetSqlMembershipProvider">
and also in my web.config I have:
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
how can I solve this problem?
You said your codebehind is empty, actually when you use login control you need to write login handler like this.
protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Online"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FirstName, LastName FROM Account WHERE Username=#Username AND Password=#Password", conn);
SqlDataReader rdr = null;
SqlParameter Username = new SqlParameter();
Username.SqlDbType = SqlDbType.VarChar;
Username.ParameterName = "Username";
Username.Value = Login1.UserName.ToString().ToLower().Trim();
SqlParameter Password = new SqlParameter();
Password.SqlDbType = SqlDbType.VarChar;
Password.ParameterName = "Password";
Password.Value = Login1.Password;
cmd.Parameters.Add(Username);
cmd.Parameters.Add(Password);
try
{
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
e.Authenticated = true;//User was found in the database
Session["Username"] = Login1.UserName.ToString();
Session["Name"] = rdr[0].ToString() + " " + (rdr[1].ToString() == null ? "" : rdr[1]);
}
}
finally
{
if (conn != null)
conn.Close();
if (rdr != null)
rdr.Close();
if (e.Authenticated)
Response.Redirect("profile.aspx");//Do whatever needs to be done when user gets authenticated
}
}

Asp.net Membership password

I am using sql server and custom database to store membership provider tables. In my webconfig file I decreased the password strength but members still needs to apply default password strength. The following is the webconfig settings
<membership>
<providers>
<add name = "AspNetSqlProvider"
type = "System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName = "LocalSqlServer"
enablePasswordRetrieval = "false"
enablePasswordReset = "true"
requiresQuestionAndAnswer = "true"
applicationName = "/"
requiresUniqueEmail = "false"
passwordFormat = "Hashed"
maxInvalidPasswordAttempts = "5"
minRequiredPasswordLength = "6"
minRequiredNonalphanumericCharacters = "0"
passwordAttemptWindow = "10"
passwordStrengthRegularExpression = "" />
</providers>
</membership>
You need to set your membership provider as the default provider. Otherwise it will use the membership provider defined in Machine.Config.
<membership defaultProvider="AspNetSqlProvider" userIsOnlineTimeWindow="30">
<providers>
<clear/>
<add name = "AspNetSqlProvider"
type = "System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName = "LocalSqlServer"
enablePasswordRetrieval = "false"
enablePasswordReset = "true"
requiresQuestionAndAnswer = "true"
applicationName = "/"
requiresUniqueEmail = "false"
passwordFormat = "Hashed"
maxInvalidPasswordAttempts = "5"
minRequiredPasswordLength = "6"
minRequiredNonalphanumericCharacters = "0"
passwordAttemptWindow = "10"
passwordStrengthRegularExpression = "" />
</providers>
</membership>

Resources