【发布时间】:2015-12-04 00:52:14
【问题描述】:
我正在开发一个部署在 IIS 7.0 中的 asp.net mvc5 Web 应用程序 + Entity framework 6.0。目前我有一个 NetworkScanning 服务器,我将其实现为正常操作方法,可以通过 2 种方式启动:-
1.基于 global.asax 中定义的时间表:-
static void ScheduleTaskTrigger()
{
HttpRuntime.Cache.Add("ScheduledTaskTrigger",
string.Empty,
null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(Double.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["ScanInMinutes"])), // as defined inside the web.config
CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(PerformScheduledTasks));
}
static void PerformScheduledTasks(string key, Object value, CacheItemRemovedReason reason)
{
//Your TODO
HomeController h = new HomeController();
var c = h.ScanNetwork("***", "allscan");
ScheduleTaskTrigger();
}
2.或者从用户浏览器手动调用action方法。
现在 action 方法如下所示(我删除了很多代码,因为这个想法是为了提示我在 action 方法中所做的事情):-
public async Task<ActionResult> ScanNetwork(string token, string FQDN)
{
string TToken = System.Web.Configuration.WebConfigurationManager.AppSettings["TToken"];//get the T token from the web.config, this should be encrypted
var cccc = Request == null ? System.Web.Configuration.WebConfigurationManager.AppSettings["TIP"] : Request.UserHostAddress;
if (token != TToken || cccc != System.Web.Configuration.WebConfigurationManager.AppSettings["TIP"])
{
if (FQDN != "allscan")
{ return Json(new { status = "fail", message = "Authintication failed." }, JsonRequestBehavior.AllowGet); }
return new HttpStatusCodeResult(403, "request failed");
}
try
{
scaninfo = await repository.populateScanInfo(false); // get the info for all the servers from the database
using (WebClient wc = new WebClient())
{
string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
var json = await wc.DownloadStringTaskAsync(url);
resourcesinfo = JsonConvert.DeserializeObject<ResourcesInfo>(json);
}
foreach (var c in scaninfo) //loop through all the hypervisot server/s
{
if (passwordmanagerResource.Count() == 0) // if there is not any record for the resource on the password manager
{
await repository.Save();
continue;
}
else if (passwordmanagerResource.Count() > 1) // if more than on record is defined for the same resource on PM
{
await repository.Save();
continue;
}
else
{
using (WebClient wc = new WebClient()) // call the PM API to get the account id
{
string url = currentURL + "resources/" + passwordmanagerResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
var json = await wc.DownloadStringTaskAsync(url);
resourceAccountListInfo = JsonConvert.DeserializeObject<ResourceAccountListInfo>(json);
}
using (WebClient wc = new WebClient()) // call the PM API to get the password for the account id under the related resource
{
string url = currentURL + "resources/" + passwordmanagerResourceID + "/accounts/" + passwordmanagerAccountID + "/password?AUTHTOKEN=" + pmtoken;
var json = await wc.DownloadStringTaskAsync(url);
resourceAccountPasswordListInfo = JsonConvert.DeserializeObject<ResourceAccountPasswordInfo>(json);
}
var shell = PowerShell.Create();
var shell2 = PowerShell.Create();
var shell3 = PowerShell.Create();
//Powercli script to get the hypervisot info
string PsCmd = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;
PsCmd = PsCmd + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;
PsCmd = PsCmd + "Get-VMHost " + System.Environment.NewLine;
string PsCmd2 = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;
PsCmd2 = PsCmd2 + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;
PsCmd2 = PsCmd2 + " Get-VMHost " + vCenterName + "| Get-VMHostNetworkAdapter -VMKernel" + System.Environment.NewLine;
shell.Commands.AddScript(PsCmd);
shell2.Commands.AddScript(PsCmd2);
dynamic results = shell.Invoke(); // execute the first powercli script
dynamic results2 = shell2.Invoke();//execute the second powercli script
if (results != null && results.Count > 0 && results[0].BaseObject != null) // the powercli executed successfully
{
// call the service desk API to update the hypervisor info
var builder = new StringBuilder();
XmlDocument doc = new XmlDocument();
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
//code goes here
string xml = await client.DownloadStringTaskAsync(url.ToString());
doc.LoadXml(xml);
status = doc.SelectSingleNode("/operation/operationstatus").InnerText;
message = doc.SelectSingleNode("/operation/message").InnerText;
}
else//if the powershell script return zero result..
{
c.TServer.ScanResult = "Scan return zero result";
scan.Description = scan.Description + "<span style='color:red'>" + c.TServer.ScanResult + "</span><br/>";
await repository.Save();
continue;
}
if (FQDN == "allscan")
{
//code goes here
}
catch (WebException ex)
{
errormessage = "Password manager or manage engine can not be accessed";
errorstatus = "fail";
}
catch (Exception e)
{
errormessage = "scan can not be completed. Message" + e.InnerException;
errorstatus = "fail";
}
scan.EndDate = System.DateTime.Now;
using (MailMessage mail = new MailMessage(from, "*****"))
{
mail.Subject = "scan report generated";
// mail.Body = emailbody;
mail.IsBodyHtml = true;
System.Text.StringBuilder mailBody = new System.Text.StringBuilder();
mailBody.AppendLine("<span style='font-family:Segoe UI'>Hi, <br/>");
mailBody.AppendLine(scan.Description);
mailBody.AppendLine("<br/><br/><div style='color:#f99406;font-weight:bold'>T scanning Management </div> <br/> <div style='color:#f99406;font-weight:bold'>Best Regards</div></span>");
SmtpClient smtp = new SmtpClient();
smtp.Host = System.Web.Configuration.WebConfigurationManager.AppSettings["smtpIP"];
smtp.EnableSsl = true;
mail.Body = mailBody.ToString();
smtp.UseDefaultCredentials = false;
smtp.Port = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["smtpPort"]);
S
smtp.Send(mail);
}
}
return Json(new { status = errorstatus, message = errormessage }, JsonRequestBehavior.AllowGet);
}
现在如上面的动作方法所示,它包含许多操作,例如;从数据库中检索对象,保存数据库更改,在第三方应用程序上调用 Web 客户端,运行 powercli 脚本等。现在我在 IIS 上部署了应用程序,无论是由用户手动运行还是根据计划运行,它似乎都运行良好时间。但从我自己的阅读来看,运行上述操作方法等长时间运行的任务被认为是有风险的,我需要使用不同的方法。那么任何人都可以提出为什么上述方法被认为是有风险的以及我该如何改进它? 第二个问题。现在我读到 Quartz.NET 是一种可以遵循的方法,但不确定我是否仍然可以从 Web 浏览器调用 Quartz.NET 方法并且不确定我是否可以在 Quartz.NET 中调用 webclient、执行 powercli 脚本等?
谢谢
【问题讨论】:
-
@haim770 但我不明白如果我将该方法作为操作方法或作为挂火方法运行会有什么区别?现在,如果我从 global.asax 及时调用 action 方法,它与使用 hangfire 调用它会有所不同吗?第二个问题,如果我使用hangfire,我还能从网络浏览器中调用该方法吗?请您提供更多信息?
-
Hangfire 是为这类问题而构建的,我不会在
global.asax中添加定时操作... Hangfire 可以带有一个用户界面,您可以去启动一个计划任务。查看文档,您就会明白为什么要这样做。 -
@JamieRees 现在假设我使用hangfire 或quartz.net 将网络扫描方法定义为一个及时的工作.. 然后我部署我的asp.net mvc(其中包含quartz.net 工作)在 IIS 中,quartz.net 作业会在 iis 下运行吗?或者它将在自己的二进制文件上运行?如果它将在 iis 下运行,那么我将面临与调用操作方法相同的风险,这是正确的吗?
-
我对 quatz 不熟悉,所以无法回答。但是是的,Hangfire 将在 IIS 中的 w3wp 下运行。使用这些工具的全部意义在于您不必构建自己的调度程序。他们已经为您完成了工作并整理了警告,例如作业失败,重试循环。为什么要重新发明轮子
-
目前在 global.asax 文件中,我定义了每 3 小时调用一次 action 方法的时间表。如果我能很好地理解您的回复,即使使用 quatz 和 hangfire 之类的工具,他们的工作也将在 iis 下运行,但这些工具相对于使用 global.asax 的优势在于它们已经为失败的工作、重试周期提供了功能。?第二个问题回到我原来的问题,在我的情况下,我有什么被认为是一种长期运行的网络扫描方法,那么使用 hangfire 或 global.asax 及时调用此方法是否被认为是一种好方法?
标签: asp.net asp.net-mvc iis asp.net-mvc-5 quartz.net