mvc如何应用nuget包_本周#2的NuGet软件包-MvcMailer使用ASP.NET MVC Razor视图和脚手架发送邮件...

mvc如何应用nuget包

mvc如何应用nuget包

Have you implemented the NuGet Action Plan? Get on it, it'll take only 5 minutes: NuGet Action Plan - Upgrade to 1.1, Setup Automatic Updates, Get NuGet Package Explorer.

您是否执行了NuGet行动计划 马上开始,只需5分钟: NuGet行动计划-升级到1.1,设置自动更新,获取NuGet软件包资源管理器

The Backstory: I was thinking since the NuGet .NET package management site is starting to fill up that I should start looking for gems (no pun intended) in there. You know, really useful stuff that folks might otherwise not find. I'll look for mostly open source projects, ones I think are really useful. I'll look at how they built their NuGet packages, if there's anything interesting about the way the designed the out of the box experience (and anything they could do to make it better) as well as what the package itself does.

背景:自从NuGet .NET程序包管理站点开始填充以来,我一直在思考,我应该开始在其中查找gem(无双关语)。 您知道的,否则人们可能找不到真正有用的东西。 我会寻找大多数开源项目,这些项目我认为真的很有用。 我将看看他们如何构建他们的NuGet软件包,如果关于开箱即用体验的设计方式(以及他们可以做得更好的任何方式)以及软件包本身的功能有什么有趣的事情。

MvcMailer使用ASP.NET MVC Razor视图和脚手架发送邮件 (MvcMailer sends mails with ASP.NET MVC Razor Views and Scaffolding)

I just love the idea behind this NuGet package. This is effectively a port/reimagining of the Rails ActionMailer with an ASP.NET twist. It's wonderful for a number of reasons.

我只是喜欢这个NuGet软件包背后的想法。 这实际上是通过ASP.NET转换对Rails ActionMailer的移植/重新构想。 出于多种原因,这是很棒的。

First, because (and this is an ingredient for all great pieces of software) we've all had this idea but never implemented it! I've been talking about writing this for six months. Of course, Talk is Cheap, Show Me The Code. I'm thrilled I never wrote it because it wouldn't have been this good.

首先,因为(这是所有优秀软件的组成部分),我们所有人都有这个主意,但从未实现过! 我已经谈论六个月了。 当然,谈话便宜,给我看代码 我从来没有写过,这让我很激动,因为它不会那么好。

Second, because the way that the author, Sohan, has implemented this really builds on existing technologies in a very "LEGO" way. Great open source apps often build on other great ones cleanly. He's really avoided duplication by separating concerns and focused on just the new functionality MvcMailer adds.

其次,因为作者Sohan实施此方法的方式实际上以非常“乐高”的方式建立在现有技术的基础上。 优秀的开源应用程序通常会干净利落地构建在其他出色的应用程序上。 通过分离关注点并专注于MvcMailer添加的新功能,他确实避免了重复。

clip_image002

There comes a time in every project when you need to email a user. Traditionally it (almost always sucks). As Sohan points out, it usually looks like this:

每个项目中都有一段时间需要向用户发送电子邮件。 传统上,它(几乎总是很烂)。 正如Sohan所指出的,通常看起来像这样:

StringBuilder mailBody = new StringBuilder();
mailBody.Append("<html><head><style type=\"text\css\">...</style></head>");
mailBody.Append("<body>")
mailBody.AppendFormat("Hi {0}<br/>", user.FirstName);
...
... XX lines of similar Appending unless it its done!
...
mailBody.Append("</body></html>");

If you're special, maybe you put a template text file somewhere and do a .Replace("{token}") but it still sucks.

如果您很特殊,也许您将模板文本文件放在某个地方,然后执行.Replace(“ {token}”),但它仍然很烂。

Additionally, you want the ability to send not only rich HTML email but also plain text (or more likely, multipart) emails. Fortunately, with ASP.NET MVC we are already creating nice HTML template for output the user, just over HTTP. Why can't we do the same with email?

此外,您希望不仅能够发送丰富HTML电子邮件,而且还可以发送纯文本(或更可能是多部分)电子邮件。 幸运的是,使用ASP.NET MVC,我们已经创建了不错HTML模板,用于通过HTTP输出用户。 为什么我们不能对电子邮件做同样的事情?

MvcMailer的工作原理以及为何很棒 (How MvcMailer Works and Why It's Cool)

The MvcMailer NuGet Package is clever on a number of levels, truly. I mention this so that we (you and I, Dear Reader) might learn together. It's full of little gems and clever best-practices that we can use in our own NuGet packages.

实际上,MvcMailer NuGet软件包在多个级别上都很聪明。 我提到这一点是为了使我们(您和我,亲爱的读者)可以一起学习。 我们可以在我们自己的NuGet软件包中使用很多小宝石和聪明的最佳实践。

In his install.ps1 - that's the PowerShell script that runs when you install a package - he has a little ReadMe in the form of a series of Write-Host commands. This is a simple, clever and effective way to get my attention. And it did!

在他的install.ps1中(这是安装软件包时运行的PowerShell脚本),他以一系列Write-Host命令的形式有一些自述文件。 这是一种引起我注意的简单,聪明和有效的方法。 它做到了!

Write-Host ---------------------------READ ME---------------------------------------------------
Write-Host
Write-Host Your default Mailer Scaffolder is set to $mailerScaffolder
Write-Host
Write-Host You can generate your Mailers and Views using the following Scaffolder Command
Write-Host
Write-Host "PM> Scaffold Mailer UserMailer Welcome,GoodBye"
Write-Host
Write-Host Edit the smtp configuration at web.config file before you send an email
Write-Host
Write-Host You can find more at: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
Write-Host
Write-Host -------------------------------------------------------------------------------------

He also makes use of the version specific lib folders. There's a 40 folder underneath lib. That's because this package only works on .NET 4 and NuGet knows it because of the named lib folders. You can target Silverlight, etc with these folders.

他还使用特定于版本的lib文件夹。 lib下方有40个文件夹。 这是因为该程序包仅在.NET 4上可用,并且NuGet知道了它,因为它具有命名的lib文件夹。 您可以使用这些文件夹定位Silverlight等。

The MvcMailer makes use of Steve Sanderson's excellent (and prescient) scaffolding system. Steve took the basic MvcScaffolding prototype and turned it into two packages, the MvcScaffolding one, and a base package called T4Scaffolding that isn't MVC specific. You can Get-Scaffolder and Set-Scaffolder and generate whatever you like, and he does.

MvcMailer利用了史蒂夫·桑德森出色的(和有先见之明的)脚手架系统。 史蒂夫(Steve)取得了基本的MvcScaffolding原型,并将其变成了两个软件包,一个是MvcScaffolding,另一个是不是MVC专用的称为T4Scaffolding的基本软件包。 您可以获取Get-Scaffolder和Set-Scaffolder并生成您喜欢的任何内容,而他会这样做。

If I type Get-Scaffolder, I see where MvcMailer has plugged in:

如果键入Get-Scaffolder,我会看到MvcMailer插入的位置:

PM> Get-Scaffolder

Name Description Package
---- ----------- -------
Mailer.Aspx Scaffold ... MvcMailer 1.1
Mailer.Razor Scaffold ... MvcMailer 1.1
T4Scaffolding.CustomScaffolder Creates a... T4Scaffolding 0.9.7
T4Scaffolding.CustomTemplate Allows yo... T4Scaffolding 0.9.7
T4Scaffolding.EFDbContext Makes an ... T4Scaffolding 0.9.7
T4Scaffolding.EFRepository Creates a... T4Scaffolding 0.9.7

Now I can Scaffold out a Welcome and GoodBye mailer (or whatever, like Change Password, etc.

现在,我可以脚手架出一个Welcome和GoodBye邮件(或诸如更改密码之类的东西)。

PM> Scaffold Mailer UserMailer Welcome,GoodBye
Added MvcMailer output 'Mailers\IUserMailer.cs'
Added MvcMailer output 'Mailers\UserMailer.cs'
Added MyScaffolder output 'Views\UserMailer\_Layout.cshtml'
Added MyScaffolder output 'Views\UserMailer\Welcome.cshtml'
Added MyScaffolder output 'Views\UserMailer\GoodBye.cshtml'

Ah, but I need both HTML and Text versions, so I'll do  it again -WithText:

嗯,但是我需要HTMLText版本,所以我会再做一次-WithText:

PM> Scaffold Mailer UserMailer Welcome,GoodBye -WithText
Mailers\IUserMailer.cs already exists! Skipping...
Mailers\UserMailer.cs already exists! Skipping...
Views\UserMailer\_Layout.cshtml already exists! Skipping...
Views\UserMailer\Welcome.cshtml already exists! Skipping...
Views\UserMailer\GoodBye.cshtml already exists! Skipping...
Added MyScaffolder output 'Views\UserMailer\_Layout.text.cshtml' Added MyScaffolder output 'Views\UserMailer\Welcome.text.cshtml' Added MyScaffolder output 'Views\UserMailer\GoodBye.text.cshtml'

Very cool. Now I've got templates nicely organized as if they were Views for both HTML and Text for Welcome and GoodBye. I can take the generated code for my UserMail and extend it. For example, if I want to send some data to my mailer (I likely do) I'll change it to look like this:

很酷。 现在,我已经很好地组织了模板,好像它们既是HTML的视图,又是Welcome和GoodBye的文本。 我可以将生成的代码用于UserMail并进行扩展。 例如,如果我想向邮件发送一些数据(我可能会这样做),则将其更改为如下所示:

public virtual MailMessage Welcome(string firstName, string email)
{
var mailMessage = new MailMessage{Subject = "Welcome"};

mailMessage.To.Add(email);
ViewBag.FirstName = firstName;
PopulateBody(mailMessage, viewName: "Welcome");

return mailMessage;
}

Then I can call this from a regular controller in response to an action. This could certainly be done on one line if you like that.

然后,我可以从常规控制器中调用它来响应操作。 如果您愿意的话,当然可以在一行上完成。

var mailer = new UserMailer();
var msg = mailer.Welcome(firstName: "Scott", email: "scottha@microsoft.com");
msg.Send();

I like named parameters.

我喜欢命名参数。

NOTE: The Send() method is an extension method, and you need to make sure you have using Mvc.Mailer in your namespaces. This slowed me down a smidge until I figured it out.

注意: Send()方法是一个扩展方法,您需要确保已在名称空间中使用Mvc.Mailer。 这使我放慢了脚步,直到我想通了。

Now, I don't want to setup my SMTP mail server, so I'll change the web.config to write emails out to a temp folder:

现在,我不想设置我的SMTP邮件服务器,因此我将更改web.config以便将电子邮件写到临时文件夹中:

<system.net>
<mailSettings>
<!-- Method#1: Configure smtp server credentials -->
<!--<smtp from="some-email@gmail.com">
<network enableSsl="true" host="smtp.gmail.com" port="587" userName="some-email@gmail.com" password="valid-password" />
</smtp>-->
<!-- Method#2: Dump emails to a local directory -->
<smtp from="some-email@gmail.com" deliveryMethod="SpecifiedPickupDirectory">
<network host="localhost" />
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\"/>
</smtp>
</mailSettings>
</system.net>

When I execute /Home/SendWelcomeEmail, I've got a nice email sitting in my temp folder (note the Outlook Icon):

当我执行/ Home / SendWelcomeEmail时,我的临时文件夹中有一封不错的电子邮件(请注意Outlook图标):

MvcMailerTempEmail

And here's my email. Note the user data passed in, in the form of my email and first name.

这是我的电子邮件。 请注意以我的电子邮件和名字的形式传入的用户数据。

Welcome - Message (HTML)  (32)

I just love that this package exists and that it's such a great example of open source building on existing projects and plugging into existing conventions cleanly. It's also a testament to Steve's extensibility points  in T4Scaffolding and Andrew Nurse and friends in Razor as neither team had an idea this project was happening! Kudos to Sohan for this useful and polished project. I hope the community appreciates his work and supports him with bug fixes, improvements and more! Thank him in the comments and follow his project on GitHub!

我只是喜欢这个软件包的存在,并且它是在现有项目上开源构建并干净地插入现有约定的一个很好的例子。 这也证明了史蒂夫(Steve)在T4Scaffolding中的可扩展性点以及安德鲁·奈瑟(Andrew Nurse)和剃刀(Razor)中的朋友,因为两个团队都不知道这个项目正在发生! 感谢Sohan进行这个有用且完善的项目。 我希望社区对他的工作表示赞赏,并通过错误修复,改进等方式为他提供支持! 感谢他的评论,并关注他在GitHub上的项目

另一件聪明的事 (One Other Clever Thing)

Here's one other clever thing that Sohan does (borrowing from Steve Sanderson) He has to determine what your preferred View Engine is, so he counts the number of ASPX files and the number of Razor files and figures the one you have the most of is your preference.

这是Sohan所做的另一项聪明的事情(从Steve Sanderson借来的),他必须确定您首选的View Engine是什么,因此他计算ASPX文件的数量和Razor文件的数量,并计算出您拥有最多的是您的偏爱。

### Copied from MvcScaffolding
function CountSolutionFilesByExtension($extension) {
$files = (Get-Project).DTE.Solution `
| ?{ $_.FileName } `
| %{ [System.IO.Path]::GetDirectoryName($_.FileName) } `
| %{ [System.IO.Directory]::EnumerateFiles($_, "*." + $extension, [System.IO.SearchOption]::AllDirectories) }
($files | Measure-Object).Count
}

function InferPreferredViewEngine() {
# Assume you want Razor except if you already have some ASPX views and no Razor ones
if ((CountSolutionFilesByExtension aspx) -eq 0) { return "razor" }
if (((CountSolutionFilesByExtension cshtml) -gt 0) -or ((CountSolutionFilesByExtension vbhtml) -gt 0)) { return "razor" }
return "aspx"
}

# Infer which view engine you're using based on the files in your project
### End copied

$mailerScaffolder = if ([string](InferPreferredViewEngine) -eq 'aspx') { "Mailer.Aspx" } else { "Mailer.Razor" }
Set-DefaultScaffolder -Name Mailer -Scaffolder $mailerScaffolder -SolutionWide -DoNotOverwriteExistingSetting

Very cool.

很酷。

Related Links

相关链接

翻译自: https://www.hanselman.com/blog/nuget-package-of-the-week-2-mvcmailer-sends-mails-with-aspnet-mvc-razor-views-and-scaffolding

mvc如何应用nuget包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值