Unrecognized configuration section system.net - c#

Hi i'll try to do the TournamentTracker and it works fine until when im stocked with the mailing lesson.
Got problems in app.config when i add the lines: <system.net> and <mailsettings>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="filePath" value="C:\Users\gertl\Source\Repos\TournamentTracker\TextData"/>
<add key="greaterWins" value="1"/>
<add key="senderEmail" value="me#outlook.com "/>
<add key="senderDisplayName" value="TournamentTracker "/>
</appSettings>
<connectionStrings>
<add name="Tournaments" connectionString="Server=xxx;Database=Tournaments;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="127.0.0.1" userName="Tim" password="testing" port="25" enableSsl="false"/>
</smtp>
</mailSettings>
</system.net>
<!--<startup>
<supportedRuntime version="v4.0" sku=".NETFrameWork,Version=v4.5.2"/>
</startup>-->
</configuration>
When i comment away the system.net section the connectionString works again.

See if the following helps.
Reads email settings
Reads connection string
Reads one AppSetting value
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="mailSettings">
<section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
<section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="filePath" value="C:\Users\gertl\Source\Repos\TournamentTracker\TextData"/>
<add key="greaterWins" value="1"/>
<add key="senderEmail" value="me#outlook.com "/>
<add key="senderDisplayName" value="TournamentTracker "/>
</appSettings>
<connectionStrings>
<add name="Tournaments" connectionString="Server=xxx;Database=Tournaments;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<mailSettings>
<smtp_1 from="someone#gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="MssGMail"
password="!#45cow"
defaultCredentials="false" />
<specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
</smtp_1>
<smtp_2 from="karenpayneoregon#gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="oregon#gmail.com"
password="password"
defaultCredentials="false" />
<specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
</smtp_2>
</mailSettings>
<system.net>
<mailSettings>
<smtp from="Someone#comcast.net">
<network
host="smtp.comcast.net"
port="587"
enableSsl="true"
userName="MissComcast"
password="d#45cat"
defaultCredentials="true" />
<specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Class for getting email settings
using System;
using System.Configuration;
using System.IO;
using System.Net.Configuration;
namespace SmtpConfigurationExample.Classes
{
public class MailConfiguration
{
private readonly SmtpSection _smtpSection;
public MailConfiguration(string section = "system.net/mailSettings/smtp")
{
_smtpSection = (ConfigurationManager.GetSection(section) as SmtpSection);
}
public string FromAddress => _smtpSection.From;
public string UserName => _smtpSection.Network.UserName;
public string Password => _smtpSection.Network.Password;
public bool DefaultCredentials => _smtpSection.Network.DefaultCredentials;
public bool EnableSsl => _smtpSection.Network.EnableSsl;
public string PickupFolder
{
get
{
var mailDrop = _smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation;
if (mailDrop != null)
{
mailDrop = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
_smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
}
return mailDrop;
}
}
/// <summary>
/// Determine if pickup folder exists
/// </summary>
/// <returns></returns>
public bool PickupFolderExists() => Directory.Exists(PickupFolder);
/// <summary>
/// Gets the name or IP address of the host used for SMTP transactions.
/// </summary>
public string Host => _smtpSection.Network.Host;
/// <summary>
/// Gets the port used for SMTP transactions
/// </summary>
public int Port => _smtpSection.Network.Port;
/// <summary>
/// Gets a value that specifies the amount of time after
/// which a synchronous Send call times out.
/// </summary>
public int TimeOut => 2000;
public override string ToString() => $"From: [ {FromAddress} ]" +
$"Host: [{Host}] Port: [{Port}] " +
$"Pickup: {Directory.Exists(PickupFolder)}";
}
}
Form code
using System;
using System.Text;
using System.Windows.Forms;
using SmtpConfigurationExample.Classes;
using static System.Configuration.ConfigurationManager;
namespace SmtpConfigurationExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetEmailSettingsButton_Click(object sender, EventArgs e)
{
var mc = new MailConfiguration();
var builder = new StringBuilder();
builder.AppendLine($"User name: {mc.UserName}");
builder.AppendLine($"From: {mc.FromAddress}");
builder.AppendLine($"Host: {mc.Host}");
builder.AppendLine($"Port: {mc.Port}");
ResultsTextBox.Text = builder.ToString();
}
private void GetConnectionButton_Click(object sender, EventArgs e)
{
ResultsTextBox.Text = ConnectionStrings["Tournaments"].ConnectionString;
}
private void FilePathButton_Click(object sender, EventArgs e)
{
ResultsTextBox.Text = AppSettings["filePath"];
}
}
}

This is what I did to resolve the exact same issue when building the Tournament Tracker.
I commented out or removed the <system.net>, from the
appconfig file: [app.config file][1] [1]:
https://i.stack.imgur.com/8pMoW.png
I installed Fluentemail SMTP NuGet Package: [Fluentemail SMTP
NuGet][2] [2]: https://i.stack.imgur.com/nsttr.png
Email Logic.cs
namespace TrackerLibrary {
public class EmailLogic
{
public static void SendEmail(string sender, string recpient, string to, string subject, string body)
{
var client = new SmtpSender(() => new SmtpClient(host: "localhost")
{
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Port = 25
});
Email.DefaultSender = client;
var mail = Email
.From(emailAddress: sender)
.To(emailAddress: to, name: recpient)
.Subject(subject)
.Body(body)
.Send();
}
}
TournamentLogic.cs
public static void AlertPlayerToNewRound(PlayersModel p, string teamName, MatchupEntryModel competitor)
{
if (p.EmailAddress.Length == 0)
{
return;
}
string sender = "";
string to = "";
string recpient = "";
string subject = "";
StringBuilder body = new StringBuilder();
if (competitor != null)
{
subject = $"You have a new matchup with { competitor.TeamCompeting.TeamName } !";
body.Append("Hello ");
body.Append(p.FirstName);
body.AppendLine(", ");
body.AppendLine();
body.AppendLine("You have a new matchup !");
body.Append("Competitor: ");
body.Append(competitor.TeamCompeting.TeamName);
body.AppendLine();
body.AppendLine();
body.AppendLine("Have a great tournament !");
body.AppendLine("~Tournament Tracker");
}
else
{
subject = "You have a bye this round !";
body.Append("Hello ");
body.Append(p.FirstName);
body.AppendLine(", ");
body.AppendLine();
body.AppendLine("Enjoy your bye round. ");
body.AppendLine("~Tournament Tracker");
}
sender = GlobalConfig.AppKeyLookup("senderEmail");
recpient = p.FullName;
to = p.EmailAddress;
EmailLogic.SendEmail(sender, recpient, to, subject, body.ToString());
After these changes, I was able to successfully send email and receive in Papercut SMTP. I hope this helps.

Related

How to Pass App Settings to Mail Method in C#

I'm trying to pass the App Settings keys listed into the Send Email function so they can be customized by the user, but for some reason I can't get it to work. I've been testing with the "Body" key to see if I can even get 1 to work.
App Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MailHost" value="smtp.gmail.com" />
<add key="PortNumber" value="587" />
<add key="MailPassword" value="**********" />
<add key="Recipient" value="*************appspotmail.com" />
<add key="Body" value="Sent from WOX Mail Plugin." />
<add key="MailUser" value="**********#gmail.com" />
</appSettings>
</configuration>
Main.CS File
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wox.Plugin;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace Wox.Plugin.Version1
{
public class Main :IPlugin
{
public void Init(PluginInitContext context)
{
}
public List<Result> Query(Wox.Plugin.Query query)
{
var subject = query.Search;
string emailbody = ConfigurationManager.AppSettings.Get("Body");
return new List<Result>()
{
new Result()
{
Title = string.Format("Add: {0}", subject),
IcoPath = "Images\\icon.png",
SubTitle = "Send New Task to Marvin",
Action = (Func<ActionContext, bool>) (c =>
{
Main.SendEmail(subject, emailbody);
return true;
})
}
};
}
public static void SendEmail(string inputsubject, string body)
{
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("****************");
message.To.Add("********************8");
message.Subject = inputsubject;
message.Body = body;
message.IsBodyHtml = false;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.Credentials = (ICredentialsByHost)new NetworkCredential("*************", "************");
smtpClient.EnableSsl = true;
smtpClient.Send(message);
}
}
}
}
}
It feels like I've tried placing the ConfigurationManager line in every perceivable spot to make it happen, and nothing has worked. The subject goes through fine, but not the body.
The email always sends successfully, but the information in the body doesn't send. I've also tried appending it to the subject line, but it doesn't show up there either.

Web Api call using IHTTP Module

Hi I am using an HttpModule to call WebAPI. Currently the solution is working locally in the system but once i published the code in Server,it fails to make the API call.Here is the Sample Code:
public class AppModule: IHttpModule
{
public void Init(HttpApplication httpApp)
{
httpApp.BeginRequest += OnBeginRequest;
httpApp.EndRequest += OnEndRequest;
httpApp.PreSendRequestHeaders += OnHeaderSent;
}
public void OnBeginRequest(Object sender, EventArgs e)
{
try
{
var httpApp = (HttpApplication)sender;
if (httpApp.Request.Path.StartsWith("/media/")) return;
string a = httpApp.Request.ServerVariables["ID"];
if (String.IsNullOrEmpty(a))
{
a = System.Configuration.ConfigurationManager.AppSettings["ID"];
}
var absolutepath = httpApp.Request.Url.AbsolutePath;
var values = new Dictionary<string, object>
{
{ "ID", a },
{ "Browser",httpApp.Request.Browser["Type"] },
{ "Url",httpApp.Request.Url.Scheme + "://" + httpApp.Request.Url.Authority + absolutepath},
{ "OperatingSys",httpApp.Request.Headers["User-Agent"] },
{ "IPAddss",httpApp.Request.UserHostAddress },
{ "LDate",System.DateTime.Now.ToString() },
};
var serializer = new JavaScriptSerializer();
var appData = serializer.Deserialize<DataVO>(serializer.Serialize(values));
AppModuleVO objAppModuleVO = new AppModuleVO();
//AppModuleVo has all the properties.
objAppModuleVO.WebUrl = System.Configuration.ConfigurationManager.AppSettings["APIURL"] + MethodCall;
objAppModuleVO.objDataVo = appData;
ThreadPool.QueueUserWorkItem(new WaitCallback(HandlePostRequest), objAppModuleVO);
}
catch (Exception ex)
{
}
}
}
I have registered the same in Web.Config as
<system.web>
<httpModules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</modules>
</system.webServer>
I am not sure whether any changes or registration needs to be made in the IIS server after publishing the code in server.Note: I have also deployed the API in the server and provided the correct path and since other methods can call the same API that is ruled out. Please help .The problem seems to be because of the IIS currently I am using IIS 7.0 in Managed Pipeline mode as CLASSIC.Any workarounds for this issue.
To long for a comment so... try this in your web.config:
....
<system.webServer>
<modules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Having said that you should consider using IntegratedMode.

Moving email setting to web config

I am try to move my email settings to web config, but i don't know how to call the setting from web config.
This is my newpassword web-config setting:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from=""testo" <admin#test.com>" >
<network host="mail.test.com" userName="admin#test.com" password="waiff75E-" port="25"/>
</smtp>
</mailSettings>
</system.net>
And this is my previous code
const string username = "test#smartguroo.com";
const string password = "password";
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("admin#test.com", loggedinUser.Text + "test");
smtpclient.Host = "mail.test.com";
smtpclient.Port = 25;
mail.From = fromaddress;
mail.To.Add(userEmail.Text);
mail.Subject = ("New post on your wall from " + loggedinUser.Text + " ");
// mail.Attachments.Add(new mail);
mail.IsBodyHtml = true;
mail.Body = "";
Remove the following lines lines since you want your settings in the web.config file to drive it from the configuration point of view.
smtpclient.EnableSsl = false;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
And just call the Send method on the SmtpClient
smtpclient.Send(mail);
All the previous concerns are configured into your web.config file, as you have done so. (Copied verbatim)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from=""testo" <admin#test.com>" >
<network host="mail.test.com" userName="admin#test.com" password="password" port="25"/>
</smtp>
</mailSettings>
</system.net>
In your webconfig
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<!-- Markup removed for clarity. -->
<add key="mailAccount" value="xyz" />
<add key="mailPassword" value="password" />
</appSettings>
<system.web>
Reference in c# via
var credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
This was using this identity tutorial

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.

correct code for sending an email, asp.net

I have a form that allows a user to send an email to everyone on a mailing list (linq table). I'm having trouble with the correct code and syntax for linking to the smtp server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Web.Security;
using System.Web.Mail;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
public partial class MassEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
mailingListClassDataContext Class = new mailingListClassDataContext();
var emaillist = from emails in Class.mailinglistMembers select emails.email;
foreach (var subcriber in emaillist)
{
MailMessage objMail = new MailMessage();
objMail.From = "test#test.com";
objMail.To = subcriber;
objMail.BodyFormat = MailFormat.Html ;
//The subject of the message
objMail.Subject = "test email that i hope works" ;
//he message text
objMail.Body = Editor1.Content;
//need help in this area
SmtpClient client = new SmtpClient();
SmtpClient.Send(objMail);
}
}
}
The best solution is to put the smtp server details in your web.config
<system.net>
<mailSettings>
<smtp>
<network
host="smtp.emailhost.com"
port="25"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>
using (var db = new mailingListClassDataContext())
{
var client = new System.Net.Mail.SmtpClient();
var recipients = from e in db.mailinglistMembers
select e.email;
foreach (string recipient in recipients)
{
var message = new System.Net.Mail.MailMessage("sender#example.com", recipient);
message.Subject = "Hello World!";
message.Body = "<h1>Foo bar</h1>";
message.IsBodyHtml = true;
client.Send(message);
}
}
Try setting up configuration in your web.config or machine.config. Make sure you've specified the correct address and port of the SMTP server.
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network" from="me#example.com">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
You can pass the SMTP server IP or name in the constructor to SmtpClient or set it explicity through the Host property.
You probably want to set the Host (and possibly the Credentials) property on the SmptClient. The server (host) defaults to localhost.
Also consider creating the client instance outside of the loop.

Categories