how to update a section in Web.Config using transforms? - asp.net

In my Web.Config I have the following
<configuration>
<configSections>
/*some code*/
</configSections>
<appSettings>
<add key="KeyName" value="KeyValue"/>
</appSettings>
</configuration>
And I have used below code when deploying a web application project.
{
"QA": {
"ConfigChanges": [
{
"KeyName": "/configuration/appSettings/add[#key='KeyName']",
"Attribute": "value",
"Value": "NewKeyValue"
}
]
}
}
Above code finds the configuration with appkey name and overwrites it.
But how do we configure if it doesn't have any key, like smtp settings?
<system.net>
<mailSettings>
<smtp from="" deliveryMethod="Network">
<network host="smtp.gmail.com" port="57" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
I tried like below like using key, but I got the error.
{
"KeyName":"/configuration/system.net/mailSettings/smtp/network[#defaultCredentials='true']",
"Attribute": "host",
"Value": "test.com"
}
Failure while updating port of /configuration/system.net/mailSettings/smtp/network[#defaultCredentials='true']: 25
Can you please help me on this.

Related

How does ASP.NET vNext handle Caching, Compression & MimeMap in config.json?

In previous versions all of these settings could be added and tweaked in the Web.Config file using something like the code below:
<staticContent>
<mimeMap fileExtension=".webp" mimeType="image/webp" />
<!-- Caching -->
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="96:00:00" />
</staticContent>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
However, with the Web.Config no longer being around in ASP.NET vNext, how do you adjust settings like this? I have searched the net and the ASP.NET Github repo, but not come across anything - any ideas?
As "agua from mars" states in the comments, if you're using IIS you can use IIS's static file handling, in which case you can use the <system.webServer> section in a web.config file and that will work as it always did.
If you're using ASP.NET 5's StaticFileMiddleware then it has its own MIME mappings that come as part of the FileExtensionContentTypeProvider implementation. The StaticFileMiddleware has a StaticFileOptions that you can use to configure it when you initialize it in Startup.cs. In that options class you can set the content type provider. You can instantiate the default content type provider and then just tweak the mappings dictionary, or you can write an entire mapping from scratch (not recommended).
ASP.NET Core - mime mappings:
If the extended set of file types you are providing for the entire site are not going to change, you can configure a single instance of the ContentTypeProvider class, and then leverage DI to use it when serving static files, like so:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddInstance<IContentTypeProvider>(
new FileExtensionConentTypeProvider(
new Dictionary<string, string>(
// Start with the base mappings
new FileExtensionContentTypeProvider().Mappings,
// Extend the base dictionary with your custom mappings
StringComparer.OrdinalIgnoreCase) {
{ ".nmf", "application/octet-stream" }
{ ".pexe", "application/x-pnal" },
{ ".mem", "application/octet-stream" },
{ ".res", "application/octet-stream" }
}
)
);
...
}
public void Configure(
IApplicationBuilder app,
IContentTypeProvider contentTypeProvider)
{
...
app.UseStaticFiles(new StaticFileOptions() {
ContentTypeProvider = contentTypeProvider
...
});
...
}

Email cron job (asp.net) with Quartz.Net not working

I am trying to send peroidic emails with Quartz.net but with no success. Firstly, the email code portion below is verified to work as I opened a new project to test it out. When I opened the application.log, I can see the Log.DebugFormat messages and not exceptions was catched, however no email was being sent out. Any advice? Thanks.
public void Execute(IJobExecutionContext context)
{
try
{
Log.DebugFormat("{0}****{0}Job {1} fired # {2} next scheduled for {3}{0}***{0} Fired by {4}",
Environment.NewLine,
context.JobDetail.Key,
context.FireTimeUtc.Value.ToString("r"),
context.NextFireTimeUtc.Value.ToString("r"),
"James");
Log.DebugFormat("{0}***{0}Hello World!!!{0}***{0}", Environment.NewLine);
// Try send email
var mail = new Email();
mail.IsBodyHtml = true;
mail.MailAddresses = "ong1980#hotmail.com";
mail.MailSubject = "Test Cron Job";
var mailMessage = mail.CreateMailMessage();
var Th = new Thread(() => Email.Send(mailMessage, 6, 3000, true));
Th.Start();
}
catch (Exception ex)
{
Log.DebugFormat("{0}***{0}Failed: {1}{0}***{0}", Environment.NewLine, ex.Message);
}
}
App.Config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler,
System, Version=1.0.5000.0,Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>
</configSections>
<quartz>
<add key="quartz.scheduler.instanceName" value="ServerScheduler"/>
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
<add key="quartz.threadPool.threadCount" value="10"/>
<add key="quartz.threadPool.threadPriority" value="2"/>
<add key="quartz.jobStore.misfireThreshold" value="60000"/>
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/>
</quartz>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="xxx#hotmail.com">
<network host="smtp.live.com" port="25" userName="xxx#hotmail.com" password="xxxxxxxxx" />
</smtp>
</mailSettings>
</system.net>
</configuration>
Ok happen that inside the /Quartz.Net/Quartz.Server.exe.config which should reside in the program files(x86), I miss out the connectionstring and mailsettings. Hope it can be a help for someone else.

Set two smtp servers in config file

I am trying to set two smtp servers in web.config file but get error
Unrecognized configuration section system.net/mailSettings/smtp_1.
How correctly to do that?
<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>
<system.net>
<mailSettings>
<smtp_1 from="no-reply1#web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
<network host="smtp...." enableSsl="true" userName="..." password="..." port="587" />
</smtp_1>
<smtp_2 from="no-reply2#web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
<network host="smtp...." port="25" />
</smtp_2>
</mailSettings>
</system.net>
</configuration>
MailSettings is not intended for this purpouse: this section is the place in configuration where you can store SMTP params, so you won't need to change them programmatically when you create a new SmtpClient.
If you want you can create your own section but not change the original one, like this:
<configuration>
<configSections>
<sectionGroup name="myMailSettings">
<section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
<section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
</sectionGroup>
</configSections>
<myMailSettings>
<smtp_1 from="no-reply1#web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
<network host="smtp...." enableSsl="true" userName="..." password="..." port="587" />
</smtp_1>
<smtp_2 from="no-reply2#web2pdfconvert.com" deliveryMethod="specifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\Administrator\Projects\temp\wp" />
<network host="smtp...." port="25" />
</smtp_2>
</myMailSettings>
....
and finally don't forget to write some code to use that data!

Adding tracelistener to web.config

I want to use below code with a website. Which config sections I should add to web.config to log the output into a file or windows eventlog ?
using System.Diagnostics;
// Singleton in real code
Class Logger
{
// In constructor: Trace.AutoFlush = false;
public void Log(message)
{
String formattedLog = formatLog(message);
Trace.TraceInformation(formattedLog);
Trace.Flush();
}
}
You should use system.diagnostics section.
Here's example from MSDN for text file:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="TextWriterOutput.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
This is for system events log: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx

How to set the Default Page in ASP.NET?

Is there any section or code which allows us to set default page in web.config?
For example, when people first visit my website, I want them to see CreateThing.aspx rather than Default.aspx.
The solutions I already know:
Put this line of code => Response.Redirect("CreateThings.aspx") in Default.aspx Page_Load event but this method is really naive.
We can use IIS (default page configuration,) but I wanna do the same thing over on my ASP.NET application.
This could be another solution for now:
<defaultDocument>
<files>
<clear />
<add value="Default.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
</files>
</defaultDocument>
If using IIS 7 or IIS 7.5 you can use
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
https://learn.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/
Tip #84: Did you know… How to set a Start page for your Web Site in Visual Web Developer?
Simply right click on the page you want to be the start page and say "set as start page".
As noted in the comment below by Adam Tuliper - MSFT, this only works for debugging, not deployment.
Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.
<add verb="GET" path="default.aspx" type="RedirectHandler"/>
Make sure Default.aspx does not exists
physically at your application root.
If it exists physically the
HttpHandler will not be given any
chance to execute. Physical file
overrides HttpHandler mapping.
Moreover you can re-use this for pages other than default.aspx.
<add verb="GET" path="index.aspx" type="RedirectHandler"/>
//RedirectHandler.cs in your App_Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
public RedirectHandler()
{
//
// TODO: Add constructor logic here
//
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Redirect("CreateThings.aspx");
context.Response.End();
}
#endregion
}
If you are using forms authentication you could try the code below:
<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/">
</forms>
</authentication>
if you are using login page in your website go to web.config file
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="index.aspx" >
</forms>
</authentication>
replace your authentication tag to above (where index.aspx will be your startup page)
and one more thing write this in your web.config file inside
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
</files>
</defaultDocument>
</system.webServer>
<location path="index.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
You can override the IIS default document setting using the web.config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPageToBeSet.aspx" />
</files>
</defaultDocument>
</system.webServer>
Or using the IIS, refer the link for reference http://www.iis.net/configreference/system.webserver/defaultdocument
I had done all the above solutions but it did not work.
My default page wasn't an aspx page, it was an html page.
This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes
Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute(""); // This was the line I had to add here!
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Hope this helps someone, it took me a goodly while to find the answer.
I prefer using the following method:
system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>

Resources