做一个MVC4的项目时留下的经验--增加IPrange

 /*
CR#1796870 modify by v-yangwu, add a js file to control the page controls.
*/
$(document).ready(function () {
$('#radioExtranet').on('click', function () { showProjectInformation() });
$('#radioCorp').on('click', function () { hideProjectInformation() });
$('.add').on("click", function () { addServerIP(this) });
$('.remove').on("click", function () { removeServerIP(this) }); $("form").submit(function () {
var trAccount = $("#iptable").find("tr").length - 1;
var isvalid = true;
var isNuNorNull = true;
for (var account = 0; account < trAccount; account++) {
var currentIp1 = $("#ServerIPs_" + account + "__Ip1").val();
var currentIp2 = $("#ServerIPs_" + account + "__Ip2").val();
var currentIp3 = $("#ServerIPs_" + account + "__Ip3").val();
var currentIp4 = $("#ServerIPs_" + account + "__Ip4").val();
var currentIp5 = $("#ServerIPs_" + account + "__Ip5").val(); var accountNext = account + 1;
for (accountNext; accountNext < trAccount; accountNext++) {
var ip1Next = $("#ServerIPs_" + accountNext + "__Ip1").val();
var ip2Next = $("#ServerIPs_" + accountNext + "__Ip2").val();
var ip3Next = $("#ServerIPs_" + accountNext + "__Ip3").val();
var ip4Next = $("#ServerIPs_" + accountNext + "__Ip4").val();
var ip5Next = $("#ServerIPs_" + accountNext + "__Ip5").val(); if (currentIp1 == ip1Next && currentIp2 == ip2Next && currentIp3 == ip3Next && currentIp4 == ip4Next && currentIp5 == ip5Next) {
$("#ServerIP\\[" + accountNext + "\\]").find(".isSameRowValid").html("The IPs are the same with others.");
$("#ServerIP\\[" + accountNext + "\\]").find(".isSameRowValid").css("color", "red");
$("#ServerIPs_" + accountNext + "__Ip4").attr("class", "input-validation-error wide");
$("#ServerIPs_" + accountNext + "__Ip5").attr("class", "input-validation-error wide");
isvalid = false;
break;
}
else {
$(".isSameRowValid").html("");
$("#ServerIPs_" + accountNext + "__Ip4").attr("class", "wide");
$("#ServerIPs_" + accountNext + "__Ip5").attr("class", "wide");
}
}
for (currRowIps = 1; currRowIps <= 5; currRowIps++)
{
var currIp = $("#ServerIPs_" + account + "__Ip" + currRowIps).val();
//Valid if the value is an int type or negative number
if (!(/^(\+|-)?\d+$/.test(currIp)) || currIp < 0) {
if (currIp == "") {
$("#ServerIP\\[" + account + "\\]").find(".field-validation-error").html("");
$("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").html("The IP" + currRowIps + " field is required.");
$("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").css("color", "red");
$("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "input-validation-error wide");
isNuNorNull = false;
break;
}
else {
$("#ServerIP\\[" + account + "\\]").find(".field-validation-error").html("");
$("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").html("The value '" + currIp + "' is not valid for IP" + currRowIps);
$("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").css("color", "red");
$("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "input-validation-error wide");
isNuNorNull = false;
break;
}
}
else {
$(".isNanOrisNull").html("");
$("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "wide");
}
}
if (!isvalid) {
break;
}
if (!isNuNorNull)
{
break;
} }
if (isvalid&&isNuNorNull)
{
return true;
}
else {
return false;
} });
}
); function hideProjectInformation() {
$("#tabProjectInformation").hide();
}
function showProjectInformation() {
$("#tabProjectInformation").show();
} function addServerIP(el) {
var serverIPIndex = $('#iptable').find("tr").length-1;
var newServerIP = "<tr class='ip' id='ServerIP[" + serverIPIndex + "]'>\
<td></td>\
<td><input name='ServerIPs[" + serverIPIndex + "].Ip1' title='Enter IP xxx.xxx.xxx.xxx' class='wide' id='ServerIPs_" + serverIPIndex + "__Ip1' style='width: 28px;' type='text' maxlength='3' value='0' data-val-required='The IP field is required.' data-val-number='The field IP must be a number.' data-val='true'></td>\
<td><label>. </label><input name='ServerIPs[" + serverIPIndex + "].Ip2' class='wide' id='ServerIPs_" + serverIPIndex + "__Ip2' style='width: 28px;' type='text' maxlength='3' value='0' data-val-required='The IP field is required.' data-val-number='The field IP must be a number.' data-val='true'></td>\
<td><label>. </label><input name='ServerIPs[" + serverIPIndex + "].Ip3' class='wide' id='ServerIPs_" + serverIPIndex + "__Ip3' style='width: 28px;' type='text' maxlength='3' value='0' data-val-required='The IP field is required.' data-val-number='The field IP must be a number.' data-val='true'></td>\
<td><label>. </label><input name='ServerIPs[" + serverIPIndex + "].Ip4' class='wide' id='ServerIPs_" + serverIPIndex + "__Ip4' style='width: 28px;' type='text' maxlength='3' value='0' data-val-required='The IP field is required.' data-val-number='The field IP must be a number.' data-val='true'></td>\
<td><label>-&nbsp; </label><input name='ServerIPs[" + serverIPIndex + "].Ip5' title='Enter ending range' class='wide' id='ServerIPs_" + serverIPIndex + "__Ip5' style='width: 28px;' type='text' maxlength='3' value='0' data-val-required='The IP range field is required.' data-val-number='The field IP range must be a number.' data-val='true'></td>\
<td><a href='#'><img title='add' class='add' style='width: 20px; height: 20px; margin-top: 0px; vertical-align: top;' alt='add' src='/Content/Images/Add.png'></a></td>\
<td><span class='field-validation-error'></span><span class='field-validation-error'></span><span class='isSameRowValid'></span><span class='field-validation-error isNanOrisNull'></span></td>\
</tr>"
$("#iptable").append(newServerIP); var serverIPPrevious = serverIPIndex - 1;
$("#ServerIP\\[" + serverIPPrevious + "\\]").find("img").attr("src", "/Content/Images/Remove.png");
$("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("title", "remove");
$("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("alt", "remove");
$("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("class", "remove");
$('.add').off("click");
$('.add').on("click", function () { addServerIP(this) });
$('.remove').off("click");
$('.remove').on("click", function () { removeServerIP(this) }); CreatePoshyTip('#Ip1, #Ip5, #Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name$=\'Ip1\'],input[name$=\'Ip5\']'); } function removeServerIP(el) {
//if remove the first row, we must add the "Server IP" to the second row.
if ($(el).closest('#ServerIP\\[0\\]').attr("id")=="ServerIP[0]")
{
$('#ServerIP\\[1\\]').find("td").first().append("<label class=\"labServerIP\"><strong>Server IP</strong></label>");
}
$(el).parent().parent().parent("tr").remove(); $('.remove').off("click");
$('.remove').on("click", function () { removeServerIP(this) });
for(var account=1;account<=$('#iptable').find("tr").length; account++)
{
$('#iptable').find('tr:eq(' + account + ')').attr("id", "ServerIP[" + (account - 1) + "]");
for (var tdAccound = 1; tdAccound <= 5; tdAccound++)
{
$("#ServerIP\\[" + (account - 1) + "\\]").find("td:eq(" + tdAccound + ")").find("input").attr("name", "ServerIPs[" + (account - 1) + "].Ip" + tdAccound + "");
$("#ServerIP\\[" + (account - 1) + "\\]").find("td:eq(" + tdAccound + ")").find("input").attr("id", "ServerIPs_" + (account - 1) + "__Ip" + tdAccound + "");
}
} $('.add').off("click");
$('.add').on("click", function () { addServerIP(this) }); }

jQueryCode

在做Qualys这个MVC4 的项目的时候,亲手写下这块jQuery代码。

包括动态添加元素,绑定到Model中的字段,对所填字段的数字,特殊符号及非空验证等功能。。。

对应的View如下:

 @model Q6.Models.ScanRequestModel
@{
ViewBag.Title = "Qualys Self-Serve";
} @section HeaderContent
{
@Styles.Render("~/Content/tip-yellow.css")
@Scripts.Render("~/Scripts/jquery.poshytip.min.js") @*CR# modify by v-yangwu, Add a java script file named jquery-Q6-scannow.js*@
@Scripts.Render("~/Scripts/jquery-Q6-scannow.js") <script type="text/javascript">
//CR#1796870 modify by v-yangwu, Update parameter for CreatePoshyTip()
//$(document).ready(function () { CreatePoshyTip('#Ip1, #Ip5, #Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name^=\'ServerIPs\']'); });
$(document).ready(function () { CreatePoshyTip('#Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name$=\'Ip1\'],input[name$=\'Ip5\']'); });
</script>
}
<h2>Create a New Scan Request</h2>
@*<p>@Html.ValidationMessageFor(m => m.CreatedDate)</p>*@
@if (!string.IsNullOrWhiteSpace(ViewBag.AddSuccess))
{
<p class="error" style="color: Red">@ViewBag.AddSuccess</p>
} @using (Html.BeginForm("Index", "ScanNow", FormMethod.Post))
{
<div id="mainform">
@*CR# modify by v-yangwu, Insert a section named Scan Type to allow user to select the different scan type*@
<h3>Scan Type</h3>
<table id="scanTypetable" style="border-collapse: collapse; border: 0px solid black;">
<tr>
<td>
<strong>
<label>Select Scan Type: </label>
</strong>
</td>
</tr>
<tr>
<td>
@Html.RadioButtonFor(model => model.ScanType, , new { @id = "radioExtranet", @name = "ScanType", @checked = true }) Extranet Scan
@Html.RadioButtonFor(model => model.ScanType, , new { @id = "radioCorp", @name = "ScanType" })Corp Scan
</td>
</tr>
</table>
<h3>Server information:</h3>
<table>
<tr>
<td><strong>@Html.LabelFor(m => m.Title)</strong></td>
<td>@Html.TextBoxFor(m => m.Title, new { @class = "wide", @title = "Enter a friendly name for the scan. No special characters are allowed in this field.", @maxlength = "" })
@Html.ValidationMessageFor(m => m.Title)
</td>
</tr>
</table> <table id="iptable" class="iptable" style="border-collapse: collapse; border: 0px solid black;">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td colspan="" align="center" style="font-size: 10px"><strong>(range)</strong></td>
<td></td>
</tr>
@*CR# modify by v-yangwu, add a for loop to load multiple IP*@
@for (var i = ; i < Model.ServerIPs.Count; i++)
{
<tr id="ServerIP[@i]" class="ip">
<td style="white-space:nowrap">
@if (i == )
{
<label class="labServerIP"><strong>Server IP</strong></label>
}
</td>
<td>
@Html.TextBoxFor(m => m.ServerIPs[i].Ip1, new { @class = "wide", @maxlength = "", @style = "width:28px;", @title = "Enter IP xxx.xxx.xxx.xxx" })
</td>
<td style="white-space:nowrap">
<label>.</label>
@Html.TextBoxFor(m => m.ServerIPs[i].Ip2, new { @class = "wide", @maxlength = "", @style = "width:28px" })
</td>
<td style="white-space:nowrap">
<label>.</label>
@Html.TextBoxFor(m => m.ServerIPs[i].Ip3, new { @class = "wide", @maxlength = "", @style = "width:28px" })
</td> <td style="white-space:nowrap">
<label>.</label>
@Html.TextBoxFor(m => m.ServerIPs[i].Ip4, new { @class = "wide", @maxlength = "", @style = "width:28px" })
</td>
<td> <label>-&nbsp</label>
@Html.TextBoxFor(m => m.ServerIPs[i].Ip5, new { @class = "wide", @maxlength = "", @style = "width:28px", @title = "Enter ending range" })
</td>
<td>
@if (i < (Model.ServerIPs.Count - ))
{
<a href="#"><img src="~/Content/Images/Remove.png" class="remove" alt="remove" style="vertical-align: top; margin-top: 0px; width: 20px; height: 20px;" title="remove" /></a>
}
else
{
<a href="#"><img src="~/Content/Images/Add.png" class="add" alt="add" style="vertical-align: top; margin-top: 0px; width: 20px; height: 20px;" title="add" /></a>
}
</td>
<td>
@* CR# modify by v-yangwu, add two span elements for the validation of IPs *@
<span class="field-validation-error">
@Model.ServerIPs[i].Errormessage
</span>
<span class="field-validation-error">
@Model.ServerIPs[i].ErrormessageCreateDate
</span>
<span class="field-validation-error isSameRowValid">
</span>
<span class="field-validation-error isNanOrisNull">
</span>
</td>
</tr>
}
</table> </div>
<div id="tabRequestInformation">
<h3>Request information:</h3>
<table> <tr>
<td>
<strong>@Html.LabelFor(m => m.RequestorAlias)</strong>
</td>
<td>
@Html.TextBoxFor(m => m.RequestorAlias, new { @class = "wide", @disabled = "disabled" })
@Html.ValidationMessageFor(m => m.RequestorAlias)
</td>
</tr> <tr>
<td>
<strong>@Html.LabelFor(m => m.NotificationList)</strong>
</td>
<td>
@Html.TextBoxFor(m => m.NotificationList, new { @class = "wide", @title = "Enter Alias of people you want to notify about scan completion. Use ; to separate multiple aliases." })
@Html.ValidationMessageFor(m => m.NotificationList)
</td>
</tr> </table>
</div> @*CR# modify by v-yangwu, add if to show Project Information when select Extranet Scan and hide Project Information when select Corp Scan*@
if (Model.ScanType == "")
{
<div id="tabProjectInformation">
<h3>Project Information:</h3>
<table>
<tr>
<td>
<a target="_blank" href="http://eapm/">Planning IT ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.PitId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://eapm" })
@Html.ValidationMessageFor(m => m.PitId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://engageisrm/">SRA ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.SraId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://engageisrm. " })
@Html.ValidationMessageFor(m => m.SraId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://getsecure/">SDL Track ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.SdlTrackId, new { @class = "wide", @title = "Optional for this request.Required for actual Extranet Sign-off Request for any applications created before April 1st, 2013.See http://getsecure for instructions how to obtain." })
@Html.ValidationMessageFor(m => m.SdlTrackId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://getsecure/">eSDL ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.EsdlId, new { @class = "wide", @title = "Optional for this request.Required for actual Extranet Sign-off Request for any applications created after April 1st, 2013.See http://getsecure for instructions how to obtain." })
@Html.ValidationMessageFor(m => m.EsdlId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://eapm/">MS Apps ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.MsAppId, new { @class = "wide", @title = "Optional for this request. MSApps has been replaced by Planning IT in 2012. An Extranet sign-off request will be denied if a Planning IT identifier has not been provided. Planning IT supports association with your MSAppsID. Obtain your Planning IT identifier and associate it to your MSAppsID from http://eapm." })
@Html.ValidationMessageFor(m => m.MsAppId)
</td>
</tr>
</table>
</div>
}
else
{
<div id="tabProjectInformation" style="display: none;">
<h3>Project Information:</h3>
<table>
<tr>
<td>
<a target="_blank" href="http://eapm/">Planning IT ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.PitId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://eapm" })
@Html.ValidationMessageFor(m => m.PitId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://engageisrm/">SRA ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.SraId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://engageisrm. " })
@Html.ValidationMessageFor(m => m.SraId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://getsecure/">SDL Track ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.SdlTrackId, new { @class = "wide", @title = "Optional for this request.Required for actual Extranet Sign-off Request for any applications created before April 1st, 2013.See http://getsecure for instructions how to obtain." })
@Html.ValidationMessageFor(m => m.SdlTrackId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://getsecure/">eSDL ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.EsdlId, new { @class = "wide", @title = "Optional for this request.Required for actual Extranet Sign-off Request for any applications created after April 1st, 2013.See http://getsecure for instructions how to obtain." })
@Html.ValidationMessageFor(m => m.EsdlId)
</td>
</tr> <tr>
<td>
<a target="_blank" href="http://eapm/">MS Apps ID</a>
</td>
<td>
@Html.TextBoxFor(m => m.MsAppId, new { @class = "wide", @title = "Optional for this request. MSApps has been replaced by Planning IT in 2012. An Extranet sign-off request will be denied if a Planning IT identifier has not been provided. Planning IT supports association with your MSAppsID. Obtain your Planning IT identifier and associate it to your MSAppsID from http://eapm." })
@Html.ValidationMessageFor(m => m.MsAppId)
</td>
</tr>
</table>
</div>
} <h3>Agreement:</h3>
<p>
@Html.CheckBoxFor(m => m.Agreement, new { @class = "left" })
<strong>Read </strong>the @Html.ActionLink("Terms of Agreement", "Agreement", "Home"). By clicking here you attest agreement and compliance with these terms; that you own or have explicit permission of the owner to scan the target(s); that these targets are part of the MSIT extranet; these targets will require, at some point in the near future, either a VIP or SNAT. If your target/host does not meet these requirements, you should not submit the scan request.
<br />
@Html.ValidationMessageFor(m => m.Agreement)
</p> <div class="formright" style="text-align: left"> <input name="submitButton" id="submitButton" type="submit" value="Submit" class="button" />
</div> }

ViewCode

对应的Model如下:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; namespace Q6.Models
{ public class ScanRequestModel
{ /// <summary>
/// Gets or sets the identifier for the scan request.
/// </summary>
public int ScanRequestId
{
get;
set;
} /// <summary>
/// CR#1796870 modify by v-yangwu, create a ServerIPsModel when declare a ScanRequestModel
/// </summary>
public ScanRequestModel()
{
ServerIPs = new List<ServerIPsModel>();
} /// <summary>
/// CR#1796870 modify by v-yangwu, Add a ServerIPsModel list
/// </summary>
public List<ServerIPsModel> ServerIPs { get; set; } /// <summary>
/// CR#1796870 modify by v-yangwu, gets or sets the scan type
/// </summary>
[DisplayName("ScanType")]
public string ScanType { get; set; } /// <summary>
/// Gets or sets the date created.
/// </summary>
[DisplayName("Date Created")]
public DateTime CreatedDate
{
get;
set;
} /// <summary>
/// Gets or sets the ip name.
/// </summary>
[DisplayName("Request Status")]
public string RequestStatus
{
get;
set;
} /// <summary>
/// CR#1796870 modify by v-yangwu, update "Friendly Name" to "Scan Name"
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("Scan Name")]
public string Title
{
get;
set;
} /// <summary>
/// Gets or sets the requestor alias.
/// </summary>
[DisplayName("Requestor Alias")]
public string RequestorAlias
{
get;
set;
} /// <summary>
/// Gets or sets the Pit Id.
/// </summary>
[Required]
[DisplayName("Planning IT ID")]
public string PitId
{
get;
set;
} /// <summary>
/// Gets or sets the Sra Id.
/// </summary>
[Required]
[DisplayName("SRA ID")]
public string SraId
{
get;
set;
} /// <summary>
/// Gets or sets the Sdl Track Id.
/// </summary>
[DisplayName("SDL Track ID")]
public string SdlTrackId
{
get;
set;
} /// <summary>
/// Gets or sets the Esdl Id.
/// </summary>
[DisplayName("eSDL ID")]
public string EsdlId
{
get;
set;
} /// <summary>
/// Gets or sets the Ms App Id.
/// </summary>
[DisplayName("MS Apps ID")]
public string MsAppId
{
get;
set;
} /// <summary>
/// Gets or sets the Ms App Id.
/// </summary>
[CustomValidation(typeof(ValidationHasToBeTrue), "ValidateTrue")]
[DisplayName("Agreement")]
public bool Agreement
{
get;
set;
} /// <summary>
/// Gets or sets the Notification Alias List.
/// </summary>
[DisplayName("Notification List")]
public string NotificationList
{
get;
set;
}
} public class ValidationHasToBeTrue
{
public static ValidationResult ValidateTrue(bool boolHasToBeTrue)
{
if(boolHasToBeTrue)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Agreement must be accepted.");
}
}
}
}

ScanRequestModel

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations; namespace Q6.Models
{
/// <summary>
/// CR#1796870 modify by v-yangwu, Add ServerIPsModel to store IPs
/// </summary>
public class ServerIPsModel
{ /// <summary>
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("IP1")]
public int Ip1
{
get;
set;
} /// <summary>
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("IP2")]
public int Ip2
{
get;
set;
} /// <summary>
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("IP3")]
public int Ip3
{
get;
set;
} /// <summary>
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("IP4")]
public int Ip4
{
get;
set;
} /// <summary>
/// Gets or sets the ip name.
/// </summary>
[Required]
[DisplayName("IP range")]
public int Ip5
{
get;
set;
} /// <summary>
/// gets or sets the errormessage for IP1-IP5
/// </summary>
public string Errormessage
{
get;
set;
} /// <summary>
/// gets or sets the errormessage for the ceate Date
/// </summary>
public string ErrormessageCreateDate
{
get;
set;
} }
}

ServerIPsModel

对应的Controller如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Q6.Services;
using Q6.Models;
using Postal;
using System.Text.RegularExpressions;
using Microsoft.Security.Application; namespace Q6.Controllers
{
public class ScanNowController : Controller
{ private readonly IScanNowService scanNowService; private readonly IActiveDirectoryService activeDirectoryService; public ScanNowController(IScanNowService scanNowService, IActiveDirectoryService activeDirectoryService)
{
this.activeDirectoryService = activeDirectoryService;
this.scanNowService = scanNowService;
} [HttpGet]
[ValidateInput(false)]
public ActionResult Index()
{
ViewBag.Message = "Scan Now.";
ScanRequestModel model = new ScanRequestModel(); //CR#1796870 modify by v-yangwu, add a list for Server Ip by default
ServerIPsModel SIM = new ServerIPsModel();
model.ServerIPs.Add(SIM);
//Extranet Scan is default
model.ScanType = "";
//CR#1796870 End string[] userAlias = User.Identity.Name.Split('\\'); model.RequestorAlias = userAlias[]; return this.View(model);
} [HttpPost]
[ValidateInput(false)]
public ActionResult Index(ScanRequestModel model)
{
model.RequestorAlias = Sanitizer.GetSafeHtmlFragment(model.RequestorAlias); string AceTeamAlias = scanNowService.GetConfigurationByName("AceTeamAlias");
string Q6DevTeam = scanNowService.GetConfigurationByName("Q6DevTeam"); bool isUserAceAnalyst = activeDirectoryService.DoesUserAccountExistInSpecifiedGroup(User.Identity.Name, AceTeamAlias);
bool isUserQ6Dev = activeDirectoryService.DoesUserAccountExistInSpecifiedGroup(User.Identity.Name, Q6DevTeam); string[] userAlias = User.Identity.Name.Split('\\');
model.RequestorAlias = userAlias[]; //CR#1796870 modify by v-yangwu, Add for loop to 1.Combine ip string; 2.validate ips
string ipAll = string.Empty;
for (int ipAccount = ; ipAccount < model.ServerIPs.Count; ipAccount++)
{
#region Combine ip string
int IpDifference = ;
string tempIp = model.ServerIPs[ipAccount].Ip1 + "." + model.ServerIPs[ipAccount].Ip2 + "." + model.ServerIPs[ipAccount].Ip3 + "." + model.ServerIPs[ipAccount].Ip4;
if (model.ServerIPs[ipAccount].Ip5 != )
{
IpDifference = model.ServerIPs[ipAccount].Ip5 - model.ServerIPs[ipAccount].Ip4; for (int count = ; count < IpDifference; count++)
{
tempIp = tempIp + "," + model.ServerIPs[ipAccount].Ip1 + "." + model.ServerIPs[ipAccount].Ip2 + "." + model.ServerIPs[ipAccount].Ip3 + "." + (model.ServerIPs[ipAccount].Ip4 + (count + ));
}
}
if (ipAccount == )
{
ipAll = tempIp;
}
else
{
ipAll = ipAll + "," + tempIp;
}
#endregion #region validate ips
//CR#1796870 modify by v-yangwu
string iperr = string.Empty;
bool isvalidated=false;
if (!isIp1Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev))
{
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip1", "IP1 is out of range.");
iperr = "IP1";
isvalidated=true;
}
if (!isIp2Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev))
{
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip2", "IP2 is out of range.");
iperr = iperr + ", IP2";
isvalidated=true;
}
if (!isIp3Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev))
{
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip3", "IP3 is out of range.");
iperr = iperr + ", IP3";
isvalidated=true;
}
if (!isIp4Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev))
{
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip4", "IP4 is out of range.");
iperr = iperr + ", IP4";
isvalidated=true;
}
if (!isIp5Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev))
{
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip5", "IP5 is out of range.");
iperr = iperr + ", IP5";
isvalidated=true;
}
//CR#1796870 modify by v-yangwu
if (isvalidated)
{
iperr = iperr.Trim(',', ' ');
model.ServerIPs[ipAccount].Errormessage = iperr + " is out of range.";
} #endregion #region DateCreatedValid
if (!isvalidated)
{
if (!isDateCreatedValid(tempIp))
{
//ModelState.AddModelError("CreatedDate", "Can not scan the current IP, it was scanned a few hours ago.");
ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip5", "Can not scan the current IP, it was scanned a few hours ago.");
model.ServerIPs[ipAccount].ErrormessageCreateDate = "Can not scan the current IP, it was scanned a few hours ago.";
}
}
#endregion
}
//CR#1796870 End var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if (model.Title != null)
{
if (!regexItem.IsMatch(model.Title))
{
ModelState.AddModelError("Title", "Invalid Character on the Friendly Name");
}
if (model.Title.Contains('\\') || model.Title.Contains('/'))
{
ModelState.AddModelError("Title", "The Friendly Name can not contain \\ or /");
}
} if (model.NotificationList != null)
{
model.NotificationList = model.NotificationList.Trim();
if (model.NotificationList != string.Empty)
{
if (!isNotificationListValid(model.NotificationList))
{
ModelState.AddModelError("NotificationList", "One or more aliases are not valid");
}
}
} //CR#1796870 modify by v-yangwu, if Scan type is Extranet, the Project Information is required.
if (model.ScanType == "")
{
//Ignore SRAID and PITID if any of the DGs
if (isUserAceAnalyst || isUserQ6Dev)
{
ModelState.Remove("SraId");
ModelState.Remove("PitId");
} try
{
uint tempSraId = Convert.ToUInt32(model.SraId);
int tempintSraId = Convert.ToInt32(model.SraId);
model.SraId = tempSraId.ToString(); }
catch (Exception)
{
ModelState.AddModelError("SraId", "Invalid SRA ID.");
} try
{
uint tempSdl = Convert.ToUInt32(model.SdlTrackId);
int tempintSdlTrackId = Convert.ToInt32(model.SdlTrackId);
model.SdlTrackId = tempSdl.ToString(); }
catch (Exception)
{
ModelState.AddModelError("SdlTrackId", "Invalid SDL Track ID.");
}
try
{
uint tempEsdl = Convert.ToUInt32(model.EsdlId);
int tempintEsdlId = Convert.ToInt32(model.EsdlId);
model.EsdlId = tempEsdl.ToString(); }
catch (Exception)
{
ModelState.AddModelError("EsdlId", "Invalid eSDL ID.");
}
try
{
uint tempMSApp = Convert.ToUInt32(model.MsAppId);
int tempintMsAppId = Convert.ToInt32(model.MsAppId);
model.MsAppId = tempMSApp.ToString(); }
catch (Exception)
{
ModelState.AddModelError("MsAppId", "Invalid MS Apps ID.");
}
}
else
{
ModelState.Remove("SraId");
ModelState.Remove("PitId");
model.MsAppId = null;
model.SdlTrackId = null;
model.EsdlId = null;
}
//CR#1796870 End if (!ModelState.IsValid)
{
return this.View(model);
} //CR#1796870 modify by v-yangwu, Update paramater for CreateRequest
//string result = scanNowService.CreateRequest(model.Ip1, model.Ip2, model.Ip3, model.Ip4, model.Ip5, model.Title, model.RequestorAlias, model.PitId, model.SraId, model.SdlTrackId, model.EsdlId, model.MsAppId, model.NotificationList, User.Identity.Name);
string result = scanNowService.CreateRequest(ipAll, model.Title, model.RequestorAlias, model.PitId, model.SraId, model.SdlTrackId, model.EsdlId, model.MsAppId, model.NotificationList, User.Identity.Name,model.ScanType); if (result == string.Empty)
{
return this.RedirectToAction("Index", "History");
}
else
{
ViewBag.AddSuccess = result;
return this.View(model);
} } [HttpGet]
public ActionResult EditScan(int id)
{
ViewBag.Message = "Scan Now.";
ViewBag.ScanRequestId = id;
string[] userAlias = User.Identity.Name.Split('\\');
ScanRequestModel model = scanNowService.GetRequestDataById(id, userAlias[]);
string[] notificationList = model.NotificationList.Split(';');
ViewBag.NotificationListFlag = false;
foreach (string user in notificationList)
{
if (user.Contains(userAlias[]))
{
ViewBag.NotificationListFlag = true;
}
} if (model.ScanRequestId != )
{
return this.View(model);
}
else
{
return this.RedirectToAction("Index", "History");
} } [HttpGet]
[ValidateInput(false)]
public ActionResult CancelScan(string id)
{
string[] userAlias = User.Identity.Name.Split('\\');
string result = scanNowService.CancelScan(id, userAlias[]);
return this.View();
} [HttpPost]
public void SendEmail(string key, string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress)
{
string[] userAlias = User.Identity.Name.Split('\\');
User.Identity.Name.Split('\\');
string q6svc = scanNowService.GetConfigurationByName("Q6ServiceAccount");
if (key == "Qualys")
{
if (userAlias[] == q6svc)
{
scanNowService.SendEmail(request_id, owner, notification_list, title, PCReportAddress, VMReportAddress);
}
}
} [HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken()]
public ActionResult EditScan(int id, ScanRequestModel model)
{
string[] userAlias = User.Identity.Name.Split('\\');
ScanRequestModel RequestModel = scanNowService.GetRequestDataById(id, userAlias[]);
string[] newNotificationList = null;
string[] oldNotificationList = RequestModel.NotificationList.Split(';');
List<string> emailList = new List<string>(); ViewBag.NotificationListFlag = false; //If the new list is not empty
if (model.NotificationList != null)
{
// Turn on flag for notificationlist in the UI
newNotificationList = model.NotificationList.Split(';');
string tempNotificationList = string.Empty;
//Trim white spaces
for (int count = ; count < newNotificationList.Count(); count++)
{
newNotificationList[count] = newNotificationList[count].Trim();
} foreach (string user in newNotificationList)
{
if (user.Contains(userAlias[]))
{
ViewBag.NotificationListFlag = true;
}
} //Find new emailList
string tempString = string.Empty;
bool found = false;
foreach (string newAlias in newNotificationList)
{
foreach (string oldAlias in oldNotificationList)
{
if (oldAlias.Trim() == newAlias.Trim())
{
found = true;
break;
}
tempString = newAlias.Trim();
}
if (found == false)
{
emailList.Add(tempString);
}
tempString = string.Empty;
found = false;
}
} ViewBag.Message = "Scan Now."; //Update the request with the new notification Alias.
if (model.NotificationList != null)
{
if (model.NotificationList != string.Empty)
{
if (!isNotificationListValid(model.NotificationList))
{
ModelState.AddModelError("NotificationList", "One or more aliases are not valid");
}
}
} ModelState.Remove("Title");
ModelState.Remove("Agreement");
ModelState.Remove("SraId");
ModelState.Remove("PitId");
if (!ModelState.IsValid)
{
return this.View(RequestModel);
}
//Send to DB string result = scanNowService.UpdateNotificationListonOnRequest(id, newNotificationList, userAlias[], emailList, RequestModel.RequestStatus); if (result == string.Empty)
{
ViewBag.AddSuccess = "The Notification List was updated successfully";
return this.View(RequestModel);
}
else
{
ViewBag.AddSuccess = result;
return this.View(RequestModel);
}
} //CR#1796870 modify by v-yangwu, update parameter for isDateCreatedValid()
//private bool isDateCreatedValid(ScanRequestModel model)
private bool isDateCreatedValid(string ip)
{
return scanNowService.isDateCreatedValid(ip);
} private bool isNotificationListValid(string NotificationList)
{
bool isNotificationListValid = true;
IEnumerable<string> tempNotificationList = ParseNotificationList(NotificationList);
foreach (string alias in tempNotificationList)
{
if (!activeDirectoryService.DoesMailEnabledAccountExist(alias))
{
isNotificationListValid = false;
return isNotificationListValid;
}
}
return isNotificationListValid;
} private string[] ParseNotificationList(string NotificationList)
{
string[] tempNotificationList;
tempNotificationList = NotificationList.Split(';');
return tempNotificationList;
} //CR#1796870 modify by v-yangwu, Change the first parameter model to ServerIPsModel for valid method
private bool isIp1Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev)
{
if (isUserAceAnalyst)
{
if (model.Ip1 <= && model.Ip1 >= )
{
return true;
}
else
{
return false;
}
}
else
{
if (model.Ip1 == )
{
return true;
}
else
{
return false;
}
}
}
private bool isIp2Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev)
{
if (isUserAceAnalyst)
{
if (model.Ip2 <= && model.Ip2 >= )
{
return true;
}
else
{
return false;
}
}
else if (isUserQ6Dev)
{
if (model.Ip2 == || model.Ip2 == || model.Ip2 == || model.Ip2 == || model.Ip2 == )
{
return true;
}
else
{
return false;
}
}
else
{
if (model.Ip2 == || model.Ip2 == || model.Ip2 == || model.Ip2 == )
{
return true;
}
else
{
return false;
}
}
}
private bool isIp3Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev)
{
if (isUserAceAnalyst)
{
if (model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else
{
return false;
}
}
else if (isUserQ6Dev)
{
if (model.Ip2 == && model.Ip3 == )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else
{
return false;
}
}
else
{
if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else if (model.Ip2 == && model.Ip3 <= && model.Ip3 >= )
{
return true;
}
else
{
return false;
}
}
}
private bool isIp4Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev)
{
if (model.Ip4 <= && model.Ip4 >= )
{
return true;
}
else
{
return false;
}
}
private bool isIp5Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev)
{
if (model.Ip5 > model.Ip4 || model.Ip5 == )
{
//CR#1796870 modify by v-yangwu, add a condition which judge if ip5 <= 255
if (model.Ip3 <= && model.Ip3 >= && model.Ip5 <= )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
//CR#1796870 End
}
}

ScanNowController

需要用到的Class如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Q6.Repositories;
using Q6.Models;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;
using Postal;
using Microsoft.Practices.Unity; namespace Q6.Services
{
public class ScanNowService : IScanNowService
{
private readonly IEmailService emailService; private readonly IScanNowRepository scanNowRepository; private readonly string QualysAddress = "http://www.baidu.com"; /// <summary>
/// Initializes a new instance of the <see cref="NotificationService"/> class.
/// </summary>
/// <param name="activeDirectoryService">The active directory service.</param>
[InjectionConstructor]
public ScanNowService(IScanNowRepository scanNowRepository)
: this(scanNowRepository, new EmailService())
{
} public ScanNowService(IScanNowRepository scanNowRepository, IEmailService emailService)
{
this.emailService = emailService;
this.scanNowRepository = scanNowRepository; } public void SendEmail(string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress)
{
string[] alias;
string CC = string.Empty;
if (notification_list != string.Empty)
{
dynamic CompletedEmail = new Email("ScanCompletedWithCC");
CompletedEmail.To = owner + "@microsoft.com";
CompletedEmail.SubjectName = title;
alias = notification_list.Split(';');
foreach (string email in alias)
{
if (email != string.Empty)
{
if (CC == string.Empty)
{
CC = email + "@microsoft.com";
}
else
{
CC = CC + "," + email + "@microsoft.com";
} }
}
CompletedEmail.CC = CC;
CompletedEmail.PCReportAddress = PCReportAddress;
CompletedEmail.VMReportAddress = VMReportAddress;
this.emailService.Send(CompletedEmail);
}
else
{
dynamic CompletedEmail = new Email("ScanCompleted");
CompletedEmail.To = owner + "@microsoft.com";
CompletedEmail.SubjectName = title;
CompletedEmail.PCReportAddress = PCReportAddress;
CompletedEmail.VMReportAddress = VMReportAddress;
this.emailService.Send(CompletedEmail);
}
} //CR#1796870 modify by v-yangwu, update parameters for CreateRequest()
public string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType)
{
QualysSettingsModel QualysSettings = new QualysSettingsModel();
/* Add reports from configuration file */
QualysSettings = this.scanNowRepository.GetAllConfigurations(); string QualysAddress = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysAddress").Value;
string qualysUser = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysUser").Value;
string qualysPass = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysPass").Value;
string vm_Option_Profile = QualysSettings.Settings.FirstOrDefault(x => x.Key == "VMOptionProfile").Value;
string scanner_name = QualysSettings.Settings.FirstOrDefault(x => x.Key == "Scanner_Name").Value;
int pcProfile = Convert.ToInt32(QualysSettings.Settings.FirstOrDefault(x => x.Key == "PCProfileId").Value); //CR#1796870 modify by v-yangwu, update parameters for CreateRequest()
//Create Request in database as Created
string result = this.scanNowRepository.CreateRequest(ipAll, title, requestorAlias, pitId, sraId, sdlTrackId, esdlId, msAppId, NotificationList, OperatorAlias,ScanType); if (!result.Contains("Error"))
{
//CR#1796870 modify by v-yangwu, remove the IPs which are repeated.
string[] arrayIP = ipAll.Split(',');
List<string> listIP = new List<string>();
foreach (string ip in arrayIP)
{
if (!listIP.Contains(ip))
{
listIP.Add(ip);
}
}
string ipAllNew = listIP[];
for (int ipaccount = ; ipaccount < listIP.Count(); ipaccount++)
{
ipAllNew += "," + listIP[ipaccount];
}
ipAll = ipAllNew;
//CR#1796870 End //CR#1796870 modify by v-yangwu, update parameters for Send Request to Qualys.
string vmScanResult = SendVMRequestToQualys(ipAll, title, scanner_name, qualysUser, qualysPass, vm_Option_Profile);
string pcScanResult = SendPCRequestToQualys(ipAll, title, scanner_name, qualysUser, qualysPass, pcProfile); if (!pcScanResult.Contains("Error") || !vmScanResult.Contains("Error"))
{
result = this.scanNowRepository.UpdateRequestToPending(Convert.ToInt32(result));
}
else
{
result = "PC SCan: " + pcScanResult + " VM Scan: " + vmScanResult;
} } if(!result.Contains("Error"))
{
result = string.Empty;
} return result;
} public string CancelScan(string id, string alias)
{
//Get the current Scan information by id //Get the reference for VM
//Cancel VM Request
//CancelVMScan(); //Get the reference for PC
//Cancel PC Request
//CancelPCScan();
return "";
} private string SendVMRequestToQualys(string ip, string title, string scanner_name, string qualysUser, string qualysPass, string vm_Option_Profile)
{
string result = string.Empty; string VMScanAddress = "/msp/scan.php?"; try
{
//Create http request
string requestAddress = (QualysAddress + VMScanAddress); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestAddress);
req.Method = "POST";
//Authentication
byte[] authInfo = new UTF8Encoding().GetBytes(qualysUser + ":" + qualysPass);
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authInfo);
req.Headers["X-Requested-With"] = "XMLHttpRequest";
req.ContentType = "application/x-www-form-urlencoded";
//Information
string postData = ""; postData += "ip=" + ip;
postData += "&";
postData += "scan_title=" + title;
postData += "&";
postData += "iscanner_name=" + scanner_name;
postData += "&";
postData += "option=" + vm_Option_Profile;
postData += "&";
postData += "save_report=" + "yes"; Byte[] postBytes = Encoding.UTF8.GetBytes(postData);
req.ContentLength = postData.Length; using (var dataStream = req.GetRequestStream())
{
dataStream.Write(postBytes, , postBytes.Length);
} //Get Response
ThreadPool.QueueUserWorkItem(o => { req.GetResponse(); }); }
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
result = new StreamReader(data).ReadToEnd(); }
}
} return result;
} private string SendPCRequestToQualys(string ip, string title, string scanner_name, string qualysUser, string qualysPass, int profileid)
{
string result = string.Empty;
string PCScanAddress = "/api/2.0/fo/scan/compliance/";
try
{
//Create http request
string requestAddress = (QualysAddress + PCScanAddress);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestAddress);
req.Method = "POST";
//Authentication
byte[] authInfo = new UTF8Encoding().GetBytes(qualysUser + ":" + qualysPass);
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authInfo);
req.Headers["X-Requested-With"] = "XMLHttpRequest";
req.ContentType = "application/x-www-form-urlencoded";
//Information
string postData = "";
postData += "action=" + "launch";
postData += "&";
postData += "ip=" + ip;
postData += "&";
postData += "scan_title=" + title;
postData += "&";
postData += "iscanner_name=" + scanner_name;
postData += "&";
postData += "option_id=" + profileid;
postData += "&";
postData += "echo_request=" + ; Byte[] postBytes = Encoding.UTF8.GetBytes(postData);
req.ContentLength = postData.Length; using (var dataStream = req.GetRequestStream())
{
dataStream.Write(postBytes, , postBytes.Length);
} //Get Response
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream respStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(respStream);
result = reader.ReadToEnd();
result = validateResponse(result); }
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
result = new StreamReader(data).ReadToEnd();
}
}
} return result;
} private string validateResponse(string response)
{
string result = string.Empty;
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
StringReader stringReader = null; try
{
stringReader = new StringReader(response);
using (XmlReader reader = XmlReader.Create(stringReader, settings))
{
stringReader = null;
XDocument readerDocument = XDocument.Load(reader);
try
{
IEnumerable<XElement> results = new List<XElement>();
results = (IEnumerable<XElement>)readerDocument.Root.Element("RESPONSE").Element("ITEM_LIST").Descendants();
List<XElement> resultss = (List<XElement>)results.ToList();
result = resultss[].Value.ToString(); }
catch (Exception)
{
result = "Error: " + readerDocument.Root.Element("RESPONSE").Element("TEXT").Value.ToString();
}
}
}
finally
{
if (stringReader != null)
{
stringReader.Dispose();
}
} return result;
} public ScanRequestModel GetRequestDataById(int Id, String Alias)
{
return this.scanNowRepository.GetRequestDataById(Id, Alias); } public string UpdateNotificationListonOnRequest(int Id, string[] NotificationList, string requestorAlias, List<string> emailList, string requestStatus)
{
string result = this.scanNowRepository.UpdateNotificationListonOnRequest(Id, NotificationList, requestorAlias); if (requestStatus == "Completed")
{
foreach (string alias in emailList)
{
dynamic createdEmail = new Email("NewToNotificationList"); createdEmail.To = alias + "@microsoft.com"; createdEmail.SubjectName = "Qualys Notification List Updated"; //Send Email Notifications
this.emailService.Send(createdEmail);
}
} return result;
} public bool isDateCreatedValid(string Ip)
{
return this.scanNowRepository.isDateCreatedValid(Ip);
} public string GetConfigurationByName(string configurationName)
{
return this.scanNowRepository.GetConfigurationByName(configurationName);
}
}
}

ScanNowService

 using System;
using System.Collections.Generic;
namespace Q6.Services
{
public interface IScanNowService
{
//CR#1796870 modify by v-yangwu, update parameters for CreateRequest()
string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType);
Q6.Models.ScanRequestModel GetRequestDataById(int Id, String Alias);
string UpdateNotificationListonOnRequest(int Id, string[] NotificationList, string requestorAlias, List<string> emailList, string requestStatus);
bool isDateCreatedValid(string Ip);
string GetConfigurationByName(string configurationName);
string CancelScan(string id, string alias);
void SendEmail(string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress);
}
}

IScanNowService

 using System;
using Q6.Models;
namespace Q6.Repositories
{
public interface IScanNowRepository
{
//CR#1796870 modify by v-yangwu, update parameters for CreateRequest()
string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType);
Q6.Models.ScanRequestModel GetRequestDataById(int Id, string Alias);
string UpdateNotificationListonOnRequest(int requestId, string[] notificationList, string requestorAlias);
string UpdateRequestToPending(int requestId);
bool isDateCreatedValid(string Ip);
string GetConfigurationByName(string configurationName);
QualysSettingsModel GetAllConfigurations();
}
}

IScanNowRepository

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using Q6.Models; namespace Q6.Repositories
{
public class ScanNowRepository : BaseSqlRepository, IScanNowRepository
{
/// <summary>
/// Initializes a new instance of the <see cref="SqlEmployeeRepository"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public ScanNowRepository(string connectionString)
: base(connectionString)
{
} //CR#1796870 modify by v-yangwu, update parameters for CreateRequest()
public string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType)
{
// Send request to Qualys
string[] notificationList; string result = string.Empty; using (DataTable dataTable = new DataTable("Request"))
{
using (DataTable tableNotificationList = new DataTable("NotificationList"))
{
tableNotificationList.Locale = CultureInfo.InvariantCulture;
tableNotificationList.Columns.Add("NotificationListID", typeof(int));
tableNotificationList.Columns.Add("RequestID", typeof(int));
tableNotificationList.Columns.Add("Alias", typeof(string));
if (NotificationList != null)
{
notificationList = NotificationList.Split(';');
foreach (string alias in notificationList)
{
if (alias != requestorAlias)
{
tableNotificationList.Rows.Add(null, null, alias.Trim());
}
}
} dataTable.Locale = CultureInfo.InvariantCulture;
dataTable.Columns.Add("RequestID", typeof(int));
dataTable.Columns.Add("RequestStatusID", typeof(int));
dataTable.Columns.Add("IP", typeof(string));
dataTable.Columns.Add("Title", typeof(string));
dataTable.Columns.Add("Requestor", typeof(string));
dataTable.Columns.Add("PITID", typeof(string));
dataTable.Columns.Add("SRAID", typeof(int));
dataTable.Columns.Add("SDLTrackID", typeof(int));
dataTable.Columns.Add("MSAppID", typeof(int));
dataTable.Columns.Add("ESDID", typeof(int));
dataTable.Columns.Add("PCScanReferenceID", typeof(string));
dataTable.Columns.Add("VMScanReferenceID", typeof(string));
dataTable.Columns.Add("PCReportID", typeof(string));
dataTable.Columns.Add("VMReportID", typeof(string));
dataTable.Columns.Add("PCReportPath", typeof(string));
dataTable.Columns.Add("VMReportPath", typeof(string));
//CR#1796870 modify by v-yangwu, add a columns for ScanType
dataTable.Columns.Add("ScanType",typeof(string)); //CR#1796870 modify by v-yangwu, update parameter for dataTable.Rows.Add()
dataTable.Rows.Add(null, , ipAll, title, requestorAlias, pitId, sraId, sdlTrackId, msAppId, esdlId, null, null, null, null,null,null,ScanType); using (SqlConnection connection = this.CreateDatabaseConnection())
{
using (SqlCommand command = new SqlCommand("dbo.InsertRequest", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("Request", dataTable);
command.Parameters.AddWithValue("NotificationList", tableNotificationList);
command.Parameters.AddWithValue("OperatorAlias", OperatorAlias);
SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar);
param.Direction = ParameterDirection.Output;
param.Size = ;
command.Parameters.Add(param);
SqlParameter param2 = new SqlParameter("@ID", SqlDbType.VarChar);
param2.Direction = ParameterDirection.Output;
param2.Size = ;
command.Parameters.Add(param2); connection.Open();
command.ExecuteNonQuery(); if (param.Value.ToString().Length > )
{
result = "Error - " + param.Value.ToString();
}
else
{
result = param2.Value.ToString();
} return result;
}
}
}
}
} public QualysSettingsModel GetAllConfigurations()
{
QualysSettingsModel QualysSettings = new QualysSettingsModel();
using (SqlConnection connection = this.CreateDatabaseConnection())
{
using (SqlCommand command = new SqlCommand("Q6.GetAllConfigurations", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, ).Direction = ParameterDirection.Output;
connection.Open(); using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default))
{
while (results.Read())
{
var key = (string)(results["Name"]);
var value = (string)results["ConfigValue"];
QualysSettings.Settings.Add(key, value); }
}
}
return QualysSettings;
}
} public ScanRequestModel GetRequestDataById(int Id, string Alias)
{
List<ScanRequestModel> historyList = new List<ScanRequestModel>();
//string[] tempIp;
//string tempRange = string.Empty;
string tempCompleteIp = string.Empty; //CR#1796870 modify by v-yangwu, define scantype
string scantype = string.Empty; string supportAlias = GetConfigurationByName("Support_Alias");
using (SqlConnection connection = this.CreateDatabaseConnection()) if (Alias == supportAlias)
{
using (SqlCommand command = new SqlCommand("Q6.GetRequestDataByIdForSupport", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("RequestID", Id);
command.Parameters.AddWithValue("Alias", Alias);
command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, ).Direction = ParameterDirection.Output;
connection.Open(); using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default))
{
while (results.Read())
{
ScanRequestModel tempModel = new ScanRequestModel();
tempModel.ScanRequestId = Convert.ToInt32(results["RequestID"], CultureInfo.InvariantCulture);
tempCompleteIp = (string)(results["IP"]); //CR#1796870 modify by v-yangwu, add scantype to model
scantype =(string) results["ScanType"];
tempModel.ScanType = scantype; //CR#1796870 Start modify by v-yangwu, parsing the ip string from DB
string[] ips;
ips = tempCompleteIp.Split(',');
int ipsAccount = ips.Count();
//if there are more than 1 ip
if (ipsAccount > )
{
int nextIP4 = ;
int count = ;
//
bool islast = false;
for (int i = ; i < ipsAccount; i++)
{
if (i + != ips.Count())
{
if (ips[i].Split('.')[] == ips[i + ].Split('.')[] && ips[i].Split('.')[] == ips[i + ].Split('.')[] && ips[i].Split('.')[] == ips[i + ].Split('.')[])
{
if (Convert.ToInt32(ips[i].Split('.')[]) + == Convert.ToInt32(ips[i + ].Split('.')[]))
{
count++;
nextIP4 = Convert.ToInt32(ips[i - (count - )].Split('.')[]);
islast = false;
}
else
{
//judge if there is one ip in one row.
if (count > )
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[]);
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]); tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
count = ;
islast = true;
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[]);
sip.Ip5 = ; tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
count = ;
islast = false;
}
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
if (count > )
{
sip.Ip4 = nextIP4;
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]); }
else
{
sip.Ip4 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip5 = ;
} tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
islast = false;
//Copy18
count = ;
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = nextIP4;
if (islast || count <= )
{
sip.Ip5 = ;
}
else
{
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]);
} tempModel.ServerIPs.Add(sip);
}
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip5 = ; tempModel.ServerIPs.Add(sip);
}
//CR#1796870 End tempModel.Title = (string)(results["Title"]); if (results["NotificationList"] == DBNull.Value)
{
tempModel.NotificationList = string.Empty;
}
else
{
tempModel.NotificationList = (string)(results["NotificationList"]);
} tempModel.RequestStatus = (string)results["RequestStatus"];
//CR#1796870 modify by v-yangwu, if scantype is Extranet Scan, Project Information need to be show.
if (scantype == "")
{
tempModel.PitId = (string)(results["PITID"].ToString());
tempModel.SraId = (string)(results["SRAID"].ToString());
tempModel.SdlTrackId = (string)(results["SDLTrackID"].ToString());
tempModel.EsdlId = (string)(results["ESDID"].ToString());
tempModel.MsAppId = (string)(results["MSAppID"].ToString());
}
//CR#1796870 End
tempModel.RequestorAlias = (string)(results["Requestor"]);
tempModel.Agreement = true;
return tempModel;
}
}
}
}
else
{
using (SqlCommand command = new SqlCommand("Q6.GetRequestDataById", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("RequestID", Id);
command.Parameters.AddWithValue("Alias", Alias);
command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, ).Direction = ParameterDirection.Output;
connection.Open(); using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default))
{
while (results.Read())
{
ScanRequestModel tempModel = new ScanRequestModel();
tempModel.ScanRequestId = Convert.ToInt32(results["RequestID"], CultureInfo.InvariantCulture);
tempCompleteIp = (string)(results["IP"]); //CR#1796870 modify by v-yangwu, add scantype to model
scantype = (string)results["ScanType"];
tempModel.ScanType = scantype; //CR#1796870 Start modify by v-yangwu, parsing the ip string from DB
string[] ips;
ips = tempCompleteIp.Split(',');
int ipsAccount = ips.Count();
//if there are more than 1 ip
if (ipsAccount > )
{
int nextIP4 = ;
int count = ;
//
bool islast = false;
for (int i = ; i < ipsAccount; i++)
{
if (i + != ips.Count())
{
if (ips[i].Split('.')[] == ips[i + ].Split('.')[] && ips[i].Split('.')[] == ips[i + ].Split('.')[] && ips[i].Split('.')[] == ips[i + ].Split('.')[])
{
if (Convert.ToInt32(ips[i].Split('.')[]) + ==Convert.ToInt32( ips[i + ].Split('.')[]))
{
count++;
nextIP4 = Convert.ToInt32(ips[i - (count - )].Split('.')[]);
islast = false;
}
else
{
//judge if there is one ip in one row.
if (count > )
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[]);
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]); tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
count = ;
islast = true;
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[]);
sip.Ip5 = ; tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
count = ;
islast = false;
}
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
if (count > )
{
sip.Ip4 = nextIP4;
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]); }
else
{
sip.Ip4 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip5 = ;
} tempModel.ServerIPs.Add(sip); nextIP4 = Convert.ToInt32(ips[i + ].Split('.')[]);
islast = false;
//Copy18
count = ;
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[]);
sip.Ip4 = nextIP4;
if (islast || count <= )
{
sip.Ip5 = ;
}
else
{
sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[]);
} tempModel.ServerIPs.Add(sip);
}
}
}
else
{
ServerIPsModel sip = new ServerIPsModel(); sip.Ip1 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip2 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip3 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip4 = Convert.ToInt32(ips[].Split('.')[]);
sip.Ip5 = ; tempModel.ServerIPs.Add(sip);
}
//CR#1796870 End tempModel.Title = (string)(results["Title"]); if (results["NotificationList"] == DBNull.Value)
{
tempModel.NotificationList = string.Empty;
}
else
{
tempModel.NotificationList = (string)(results["NotificationList"]);
} tempModel.RequestStatus = (string)results["RequestStatus"];
//CR#1796870 modify by v-yangwu, if scantype is Extranet Scan, Project Information need to be show.
if (scantype == "")
{
tempModel.PitId = (string)(results["PITID"].ToString());
tempModel.SraId = (string)(results["SRAID"].ToString());
tempModel.SdlTrackId = (string)(results["SDLTrackID"].ToString());
tempModel.EsdlId = (string)(results["ESDID"].ToString());
tempModel.MsAppId = (string)(results["MSAppID"].ToString());
}
//CR#1796870 End
tempModel.RequestorAlias = (string)(results["Requestor"]);
tempModel.Agreement = true;
return tempModel;
}
}
}
} return new ScanRequestModel();
} public string UpdateRequestToPending(int requestId)
{
using (SqlConnection connection = this.CreateDatabaseConnection())
{
using (SqlCommand command = new SqlCommand("dbo.UpdateRequestToPending", connection))
{
string result = string.Empty;
command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("RequestId", requestId);
SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar);
param.Direction = ParameterDirection.Output;
param.Size = ;
command.Parameters.Add(param); connection.Open();
command.ExecuteNonQuery(); result = param.Value.ToString();
return result;
}
}
} public string UpdateNotificationListonOnRequest(int requestId, string[] NotificationList, string requestorAlias)
{
using (DataTable tableNotificationList = new DataTable("NotificationList"))
{
tableNotificationList.Locale = CultureInfo.InvariantCulture;
tableNotificationList.Columns.Add("NotificationListID", typeof(int));
tableNotificationList.Columns.Add("RequestID", typeof(int));
tableNotificationList.Columns.Add("Alias", typeof(string)); if (NotificationList != null)
{
foreach (string alias in NotificationList)
{
if (alias != requestorAlias)
{
tableNotificationList.Rows.Add(null, null, alias.Trim());
}
}
} using (SqlConnection connection = this.CreateDatabaseConnection())
{
using (SqlCommand command = new SqlCommand("dbo.UpdateNotificationListonOnRequest", connection))
{
string result = string.Empty;
command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("RequestId", requestId);
command.Parameters.AddWithValue("NotificationList", tableNotificationList);
SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar);
param.Direction = ParameterDirection.Output;
param.Size = ;
command.Parameters.Add(param); connection.Open();
command.ExecuteNonQuery(); result = param.Value.ToString();
return result;
}
}
}
}
public bool isDateCreatedValid(string Ip)
{
int InvalidAmount = ;
using (SqlConnection connection = this.CreateDatabaseConnection())
using (SqlCommand command = new SqlCommand("Q6.isDateCreatedValid", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("Ip", Ip);
command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, ).Direction = ParameterDirection.Output;
connection.Open(); using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default))
{
while (results.Read())
{
if (results["InvalidAmount"] != DBNull.Value)
{
InvalidAmount = Convert.ToInt32(results["InvalidAmount"], CultureInfo.InvariantCulture);
}
else
{
InvalidAmount = ;
}
}
}
}
if (InvalidAmount > )
{
return false;
}
else
{
return true;
}
} public string GetConfigurationByName(string configurationName)
{
string configurationValue = string.Empty;
using (SqlConnection connection = this.CreateDatabaseConnection())
using (SqlCommand command = new SqlCommand("Q6.GetConfigurationByName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("ConfigurationName", configurationName);
command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, ).Direction = ParameterDirection.Output;
connection.Open(); using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default))
{
while (results.Read())
{
configurationValue = (string)results["ConfigValue"]; return configurationValue;
}
}
} return configurationValue;
}
}
}

ScanNowRepository

仅供自己为写过的功能保存知识。。。转载请注明出处。。。

上一篇:安装pdo.so和pdo_mysql.so还有pcntl.so扩展到php中


下一篇:Map集合的两种取出方式:keySet()和entrySet()方法使用举例