Get Mail Setting from Web.Config in SendAsync Method? - asp.net-mvc

I am working on Forgot Password Functionality. In my web.config file I have done the mail settings:
<system.net>
<mailSettings>
<smtp from="email">
<network host="host" port="25" userName="" password="=" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
In my SendAsync method I am trying to read setting from web.config:
SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"],
message.Destination,
message.Subject,
message.Body);
I have no idea what is this: AppSettings["SupportEmailAddr"]
I took this from here.
It is giving me following exception:
Value cannot be null. Parameter name: from

In your web.config file you have a section called: <appSettings>.
That is what ConfigurationManager.AppSettings is referring too.
["SupportEmailAddr"] is looking at a specific setting called SupportEmailAddr.
In your web.config it would look something like this:
<appSettings>
<add key="SupportEmailAddr" value="someone#example.com" />
</appSettings>
You are getting the value cannot be null message because you will not have the setting in your web.config as above.
So to fix the error message find your <appSettings> and add:
<add key="SupportEmailAddr" value="someone#example.com" />
Alternatively, if you have the current value in your AppSettings already then just change the key that you are looking for in the C# code.
ConfigurationManager.AppSettings["CorrectAppSettingKey"]
Note: if you plan on using any of the web.config inheritance features you should WebConfiguratonManger.AppSettings instead of ConfigurationManager.AppSettings. See the difference between the two here: What's the difference between the WebConfigurationManager and the ConfigurationManager?

Related

How to override Elmah applicationname set in Web.config

We have a multi-tenanted MVC app, meaning that exactly the same app is published to multiple IIS virtual directories / applications, and then the app its self works out who it is, and skins its self (css) accordingly.
This is all very well, but anything logged by ELMAH in our elmah database gets logged under the same applicationName, as this is pulled out of Web.Config elmah section below where everything would be logged as "MyappName" :
<configuration>
[...]
<elmah>
<security allowRemoteAccess="false" />
<errorLog
type="Elmah.SqlErrorLog, Elmah"
connectionStringName="elmah"
applicationName="MyappName" />
</elmah>
</configuration>
The question is therefore how to override the applicationName setting from web.config with something specific so we can distinguish errors for a given tenant web site.
As this is configurable within the web.config, ELMAH are already providing you with a way to specify the application name when the application is deployed to different locations - it's just a case of making use of it.
This would generally be something that you would manipulate as part of your deployment steps. If you are doing it manually then it's going to be a pain, but it could be easily manipulated by using a web.config transform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<elmah>
<errorLog applicationName="MyappName" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</elmah>
</configuration>
I wonder if the following might work, if you put the following into your Global.asax:
var service = ServiceCenter.Current;
ServiceCenter.Current = context =>
{
var connectionString = "YOUR CONNECTION STRING";
var container = new ServiceContainer(service(context));
var log = new SqlErrorLog(connectionString) { ApplicationName = "APP NAME HERE" };
container.AddService(typeof(ErrorLog), log);
return container;
};

Elmah code-first SQL Server logging

I installed Elmah via nuget. It usually works will if I use an .edmx. However I am using a code-first DbContext. Elmah seems to be sending the emails but it doesn't log to the database.
Any idea what could be going wrong?
It will work just fine with code first. You do not need the ELMAH_ERROR table as a part of your context. As long as you ran the elmah SQL in your database and setup your config correctly it WILL log to the database. Please share your config code, it should look something like this (a small portion of the config):
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sqlserver" applicationName="YOUR_APPLICATION" />
<security allowRemoteAccess="yes" />
</elmah>
<connectionStrings>
<add name="elmah-sqlserver" connectionString="Data Source=YOUR_SERVER;User ID=YOUR_USER_ID;Password=YOUR_PASSWORD;Initial Catalog=YOUR_CATALOG;" providerName="System.Data.SqlClient" />
</connectionStrings>

Intercept elmah logging ASP.NET MVC [duplicate]

This question already has an answer here:
elmah error handling - store in database
(1 answer)
Closed 6 years ago.
I would like to try to intercept and do some other processing ( export a database ) when elmah raises an error.Is there a way to do that?
ELMAH exposes two events in order to do this: ErrorLog_Filtering and ErrorLog_Logged. ErrorLog_Filtering is called just before logging to the configured error log and ErrorLog_Logged is called just after. You will find documentation about error filtering on the ELMAH site. ErrorLog_Logged isn't really documented, but you can see an example of it in this article: Logging to multiple ELMAH logs.
With that said, you probably don't want to execute any long running tasks as part of ErrorLog_Logged and ErrorLog_Filtering. It will slow down your system. I'm not sure on what you are trying to achieve here by exporting a database on every error?
Yes there is way around
1.Lets Create a Project Name ElmahMvc
2.Install nuget package nuget
Install-Package Elmah.MVC
3. Raise an Exception .There you go access error log by your local url/elmah
http://localhost:20351/elmah
The saving database and Emailing is bit of configuration to take ....
Lets look at it
1.Download ELMAH script form official site
ELMAH
2.add a database named log and run the script
3.add a connection string in web.config
<connectionStrings>
<add name="elmah" connectionString="Data Source=.;Initial Catalog=log;Persist Security Info=True;User ID=sa;Password=pass" providerName="System.Data.SqlClient" />
</connectionStrings>
4.Add a elmah element in web.config
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah" />
<!--For Addtional Mail Config .Remove it if not need for mail on every error-->
<errorMail from="waltoncrm#waltonbd.com"
to="mrahman.cse32#waltonbd.com"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="YourServer"
userName="uName"
password="pass">
</errorMail>
</elmah>
and mail additional
under System.WebServer
<system.net>
<mailSettings>
<smtp deliveryMethod ="Network">
<network host="smtp.gmail.com" port="587" userName="yourgmailEmailAddress" password="yourGmailEmailPassword" />
</smtp>
</mailSettings>
</system.net>
Download my sample project and Elmah script with Visual Studio 2013
akash365.com
Note:if you donot want to crash your program or use it in asp.net web form Static [WebMethod]
This seems perfect
try
{
//some web method code
}
catch(Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}

asp.net mvc: disabled RoleManager is still executed

I have a web site where configured with:
<roleManager enabled='false'></roleManager>
But I still can see roleManager being executed in the pipeline (by looking at traces, also I am getting exception when roleManager tries to load roles from SQL providers configured in machine.config)
How can I disable roleManager?
fix
add enableSimpleMembership with value false app setting to your web.config.
cause
<roleManager enabled="false" />
will cause Roles.Enabled flag to be set to false, as expected,
but there is WebMatrix.WebData.WebSecurity that says:
internal static void PreAppStartInit()
{
if (!ConfigUtil.SimpleMembershipEnabled)
return;
...
Roles.Enabled = true;
...
}
this will override roleManager setting (this code is executed before RoleManager module is).
to disable SimpleMembership you can add app setting enableSimpleMembership with value="false" (web.config):
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="enableSimpleMembership" value="false" />
</appSettings>
</configuration>
this will prevent webmatrix from enabling RoleManager.
Another solution (hack) is to remove RoleManager module from the list of modules:
....
<system.webServer>
<modules>
<remove name="RoleManager"/>
</modules>
....
no... I don't think it's correct, even with enableSimpleMembership=false, you'd still need to implement a Dummy RoleProvider, otherwise, exception "The Role Manager feature has not been enabled."
Here's how to implement a dummy RoleProvider:
Turning off only the Role Provider in SimpleMembership

Run WIF without LoadUserProfile = True is throwing null error

I am using WIF SSO for authentication in my website. Everything works perfect in development environment. But on deployment I got issue
Message: The data protection operation was unsuccessful. This may have
been caused by not having the user profile loaded for the current
thread's user context, which may be the case when the thread is
impersonating. ExceptionStackTrace: at
System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
Byte[] optionalEntropy, DataProtectionScope scope) at
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Encode(Byte[]
value)
Searching abt this issue leads me to this stackoverflow question
Is it possible to run WIF without LoadUserProfile = True
I added the code mentioned but now I am getting
Value cannot be null
I am getting e.ServiceConfiguration.ServiceCertificate ServiceCertificate null. My question is what kind of certificate is this and where can I define this in my config. Do I need to place the same certificate on ACS.
here is my config section
<microsoft.identityModel>
<service>
<audienceUris>
<add value="http://localhost:9494/" />
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="https://devworks-sb.accesscontrol.appfabriclabs.com/v2/wsfederation" realm="http://localhost:9494" requireHttps="false" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
<applicationService>
<claimTypeRequired>
<!--Following are the claims offered by STS 'https://devworks-sb.accesscontrol.appfabriclabs.com/'. Add or uncomment claims that you require by your application and then update the federation metadata of this application.-->
<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" optional="true" />
<claimType type="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" optional="true" />
<!--<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" optional="true" />-->
<!--<claimType type="http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider" optional="true" />-->
</claimTypeRequired>
</applicationService>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="BE9D0A516BEC2BC820C23D5C2EA79F068C094382" name="https://devworks-sb.accesscontrol.appfabriclabs.com/" />
</trustedIssuers>
</issuerNameRegistry>
</service> </microsoft.identityModel>
thanx
First thing you mentioned that the problem occurred after deployment, is that right? In your web.config have you changed the audienceUris to http://whatever_service_name.cloudapp.net?
<audienceUris>
<add value="http://localhost:9494/" /> <== This is wrong
</audienceUris>
Next your question about certificate is NULL at e.ServiceConfiguration.ServiceCertificate, please verify the following:
A. Endpoint is added in your application Service Definition:
B. Certificate thumbprint is set in Service Configuration
C. Certificate is set in web.config which is correct above
D. Finally added the following in your web.config so certificate can be search by thumbprint:
<serviceCertificate>
<certificateReference x509FindType="FindByThumbprint" findValue="CERT_THUMB" />
</serviceCertificate>
Study these two resources which will be very helpful:
http://www.jimandkatrin.com/CodeBlog/post/Troubleshooting-Azure-issues.aspx
http://blogs.msmvps.com/marcelmeijer/blog/2012/05/04/windows-azure-wif-access-control-acs/
The root cause is likely to be you’re using DPAPI (the default configuration of WIF). Please try to do a few modifications for the application to work in Windows Azure. I would like to suggest you to check http://msdn.microsoft.com/en-us/IdentityTrainingCourse_WIFonWAZLab2010 for a tutorial.
Best Regards,
Ming Xu.

Resources