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

it2022-05-05  124

1 /* 2 CR#1796870 modify by v-yangwu, add a js file to control the page controls. 3 */ 4 $(document).ready(function () { 5 $('#radioExtranet').on('click', function () { showProjectInformation() }); 6 $('#radioCorp').on('click', function () { hideProjectInformation() }); 7 $('.add').on("click", function () { addServerIP(this) }); 8 $('.remove').on("click", function () { removeServerIP(this) }); 9 10 $("form").submit(function () { 11 var trAccount = $("#iptable").find("tr").length - 1; 12 var isvalid = true; 13 var isNuNorNull = true; 14 for (var account = 0; account < trAccount; account++) { 15 var currentIp1 = $("#ServerIPs_" + account + "__Ip1").val(); 16 var currentIp2 = $("#ServerIPs_" + account + "__Ip2").val(); 17 var currentIp3 = $("#ServerIPs_" + account + "__Ip3").val(); 18 var currentIp4 = $("#ServerIPs_" + account + "__Ip4").val(); 19 var currentIp5 = $("#ServerIPs_" + account + "__Ip5").val(); 20 21 var accountNext = account + 1; 22 for (accountNext; accountNext < trAccount; accountNext++) { 23 var ip1Next = $("#ServerIPs_" + accountNext + "__Ip1").val(); 24 var ip2Next = $("#ServerIPs_" + accountNext + "__Ip2").val(); 25 var ip3Next = $("#ServerIPs_" + accountNext + "__Ip3").val(); 26 var ip4Next = $("#ServerIPs_" + accountNext + "__Ip4").val(); 27 var ip5Next = $("#ServerIPs_" + accountNext + "__Ip5").val(); 28 29 if (currentIp1 == ip1Next && currentIp2 == ip2Next && currentIp3 == ip3Next && currentIp4 == ip4Next && currentIp5 == ip5Next) { 30 $("#ServerIP\\[" + accountNext + "\\]").find(".isSameRowValid").html("The IPs are the same with others."); 31 $("#ServerIP\\[" + accountNext + "\\]").find(".isSameRowValid").css("color", "red"); 32 $("#ServerIPs_" + accountNext + "__Ip4").attr("class", "input-validation-error wide"); 33 $("#ServerIPs_" + accountNext + "__Ip5").attr("class", "input-validation-error wide"); 34 isvalid = false; 35 break; 36 } 37 else { 38 $(".isSameRowValid").html(""); 39 $("#ServerIPs_" + accountNext + "__Ip4").attr("class", "wide"); 40 $("#ServerIPs_" + accountNext + "__Ip5").attr("class", "wide"); 41 } 42 } 43 for (currRowIps = 1; currRowIps <= 5; currRowIps++) 44 { 45 var currIp = $("#ServerIPs_" + account + "__Ip" + currRowIps).val(); 46 //Valid if the value is an int type or negative number 47 if (!(/^(\+|-)?\d+$/.test(currIp)) || currIp < 0) { 48 if (currIp == "") { 49 $("#ServerIP\\[" + account + "\\]").find(".field-validation-error").html(""); 50 $("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").html("The IP" + currRowIps + " field is required."); 51 $("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").css("color", "red"); 52 $("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "input-validation-error wide"); 53 isNuNorNull = false; 54 break; 55 } 56 else { 57 $("#ServerIP\\[" + account + "\\]").find(".field-validation-error").html(""); 58 $("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").html("The value '" + currIp + "' is not valid for IP" + currRowIps); 59 $("#ServerIP\\[" + account + "\\]").find(".isNanOrisNull").css("color", "red"); 60 $("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "input-validation-error wide"); 61 isNuNorNull = false; 62 break; 63 } 64 } 65 else { 66 $(".isNanOrisNull").html(""); 67 $("#ServerIPs_" + account + "__Ip" + currRowIps).attr("class", "wide"); 68 } 69 } 70 if (!isvalid) { 71 break; 72 } 73 if (!isNuNorNull) 74 { 75 break; 76 } 77 78 } 79 if (isvalid&&isNuNorNull) 80 { 81 return true; 82 } 83 else { 84 return false; 85 } 86 87 }); 88 } 89 ); 90 91 function hideProjectInformation() { 92 $("#tabProjectInformation").hide(); 93 } 94 function showProjectInformation() { 95 $("#tabProjectInformation").show(); 96 } 97 98 function addServerIP(el) { 99 var serverIPIndex = $('#iptable').find("tr").length-1; 100 var newServerIP = "<tr class='ip' id='ServerIP[" + serverIPIndex + "]'>\ 101 <td></td>\ 102 <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>\ 103 <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>\ 104 <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>\ 105 <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>\ 106 <td><label>-  </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>\ 107 <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>\ 108 <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>\ 109 </tr>" 110 $("#iptable").append(newServerIP); 111 112 var serverIPPrevious = serverIPIndex - 1; 113 $("#ServerIP\\[" + serverIPPrevious + "\\]").find("img").attr("src", "/Content/Images/Remove.png"); 114 $("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("title", "remove"); 115 $("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("alt", "remove"); 116 $("#ServerIP\\[" + serverIPPrevious + "\\]").find(".add").attr("class", "remove"); 117 $('.add').off("click"); 118 $('.add').on("click", function () { addServerIP(this) }); 119 $('.remove').off("click"); 120 $('.remove').on("click", function () { removeServerIP(this) }); 121 122 CreatePoshyTip('#Ip1, #Ip5, #Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name$=\'Ip1\'],input[name$=\'Ip5\']'); 123 124 } 125 126 function removeServerIP(el) { 127 //if remove the first row, we must add the "Server IP" to the second row. 128 if ($(el).closest('#ServerIP\\[0\\]').attr("id")=="ServerIP[0]") 129 { 130 $('#ServerIP\\[1\\]').find("td").first().append("<label class=\"labServerIP\"><strong>Server IP</strong></label>"); 131 } 132 $(el).parent().parent().parent("tr").remove(); 133 134 $('.remove').off("click"); 135 $('.remove').on("click", function () { removeServerIP(this) }); 136 for(var account=1;account<=$('#iptable').find("tr").length; account++) 137 { 138 $('#iptable').find('tr:eq(' + account + ')').attr("id", "ServerIP[" + (account - 1) + "]"); 139 for (var tdAccound = 1; tdAccound <= 5; tdAccound++) 140 { 141 $("#ServerIP\\[" + (account - 1) + "\\]").find("td:eq(" + tdAccound + ")").find("input").attr("name", "ServerIPs[" + (account - 1) + "].Ip" + tdAccound + ""); 142 $("#ServerIP\\[" + (account - 1) + "\\]").find("td:eq(" + tdAccound + ")").find("input").attr("id", "ServerIPs_" + (account - 1) + "__Ip" + tdAccound + ""); 143 } 144 } 145 146 $('.add').off("click"); 147 $('.add').on("click", function () { addServerIP(this) }); 148 149 } jQueryCode

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

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

对应的View如下:

1 @model Q6.Models.ScanRequestModel 2 @{ 3 ViewBag.Title = "Qualys Self-Serve"; 4 } 5 6 @section HeaderContent 7 { 8 @Styles.Render("~/Content/tip-yellow.css") 9 @Scripts.Render("~/Scripts/jquery.poshytip.min.js") 10 11 @*CR#1796870 modify by v-yangwu, Add a java script file named jquery-Q6-scannow.js*@ 12 @Scripts.Render("~/Scripts/jquery-Q6-scannow.js") 13 14 <script type="text/javascript"> 15 //CR#1796870 modify by v-yangwu, Update parameter for CreatePoshyTip() 16 //$(document).ready(function () { CreatePoshyTip('#Ip1, #Ip5, #Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name^=\'ServerIPs\']'); }); 17 $(document).ready(function () { CreatePoshyTip('#Title, #NotificationList, #PitId, #SraId, #SdlTrackId, #EsdlId, #MsAppId, #RequestorAlias, input[name$=\'Ip1\'],input[name$=\'Ip5\']'); }); 18 </script> 19 } 20 <h2>Create a New Scan Request</h2> 21 @*<p>@Html.ValidationMessageFor(m => m.CreatedDate)</p>*@ 22 @if (!string.IsNullOrWhiteSpace(ViewBag.AddSuccess)) 23 { 24 <p class="error" style="color: Red">@ViewBag.AddSuccess</p> 25 } 26 27 @using (Html.BeginForm("Index", "ScanNow", FormMethod.Post)) 28 { 29 <div id="mainform"> 30 @*CR#1796870 modify by v-yangwu, Insert a section named Scan Type to allow user to select the different scan type*@ 31 <h3>Scan Type</h3> 32 <table id="scanTypetable" style="border-collapse: collapse; border: 0px solid black;"> 33 <tr> 34 <td> 35 <strong> 36 <label>Select Scan Type: </label> 37 </strong> 38 </td> 39 </tr> 40 <tr> 41 <td> 42 @Html.RadioButtonFor(model => model.ScanType, 0, new { @id = "radioExtranet", @name = "ScanType", @checked = true }) Extranet Scan 43 @Html.RadioButtonFor(model => model.ScanType, 1, new { @id = "radioCorp", @name = "ScanType" })Corp Scan 44 </td> 45 </tr> 46 </table> 47 <h3>Server information:</h3> 48 <table> 49 <tr> 50 <td><strong>@Html.LabelFor(m => m.Title)</strong></td> 51 <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 = "255" }) 52 @Html.ValidationMessageFor(m => m.Title) 53 </td> 54 </tr> 55 </table> 56 57 <table id="iptable" class="iptable" style="border-collapse: collapse; border: 0px solid black;"> 58 <tr> 59 <td></td> 60 <td></td> 61 <td></td> 62 <td></td> 63 <td colspan="2" align="center" style="font-size: 10px"><strong>(range)</strong></td> 64 <td></td> 65 </tr> 66 @*CR#1796870 modify by v-yangwu, add a for loop to load multiple IP*@ 67 @for (var i = 0; i < Model.ServerIPs.Count; i++) 68 { 69 <tr id="ServerIP[@i]" class="ip"> 70 <td style="white-space:nowrap"> 71 @if (i == 0) 72 { 73 <label class="labServerIP"><strong>Server IP</strong></label> 74 } 75 </td> 76 <td> 77 @Html.TextBoxFor(m => m.ServerIPs[i].Ip1, new { @class = "wide", @maxlength = "3", @style = "width:28px;", @title = "Enter IP xxx.xxx.xxx.xxx" }) 78 </td> 79 <td style="white-space:nowrap"> 80 <label>.</label> 81 @Html.TextBoxFor(m => m.ServerIPs[i].Ip2, new { @class = "wide", @maxlength = "3", @style = "width:28px" }) 82 </td> 83 <td style="white-space:nowrap"> 84 <label>.</label> 85 @Html.TextBoxFor(m => m.ServerIPs[i].Ip3, new { @class = "wide", @maxlength = "3", @style = "width:28px" }) 86 </td> 87 88 <td style="white-space:nowrap"> 89 <label>.</label> 90 @Html.TextBoxFor(m => m.ServerIPs[i].Ip4, new { @class = "wide", @maxlength = "3", @style = "width:28px" }) 91 </td> 92 <td> 93 94 <label>- </label> 95 @Html.TextBoxFor(m => m.ServerIPs[i].Ip5, new { @class = "wide", @maxlength = "3", @style = "width:28px", @title = "Enter ending range" }) 96 </td> 97 <td> 98 @if (i < (Model.ServerIPs.Count - 1)) 99 { 100 <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> 101 } 102 else 103 { 104 <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> 105 } 106 </td> 107 <td> 108 @* CR#1796870 modify by v-yangwu, add two span elements for the validation of IPs *@ 109 <span class="field-validation-error"> 110 @Model.ServerIPs[i].Errormessage 111 </span> 112 <span class="field-validation-error"> 113 @Model.ServerIPs[i].ErrormessageCreateDate 114 </span> 115 <span class="field-validation-error isSameRowValid"> 116 </span> 117 <span class="field-validation-error isNanOrisNull"> 118 </span> 119 </td> 120 </tr> 121 } 122 </table> 123 124 </div> 125 <div id="tabRequestInformation"> 126 <h3>Request information:</h3> 127 <table> 128 129 <tr> 130 <td> 131 <strong>@Html.LabelFor(m => m.RequestorAlias)</strong> 132 </td> 133 <td> 134 @Html.TextBoxFor(m => m.RequestorAlias, new { @class = "wide", @disabled = "disabled" }) 135 @Html.ValidationMessageFor(m => m.RequestorAlias) 136 </td> 137 </tr> 138 139 <tr> 140 <td> 141 <strong>@Html.LabelFor(m => m.NotificationList)</strong> 142 </td> 143 <td> 144 @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." }) 145 @Html.ValidationMessageFor(m => m.NotificationList) 146 </td> 147 </tr> 148 149 </table> 150 </div> 151 152 @*CR#1796870 modify by v-yangwu, add if to show Project Information when select Extranet Scan and hide Project Information when select Corp Scan*@ 153 if (Model.ScanType == "0") 154 { 155 <div id="tabProjectInformation"> 156 <h3>Project Information:</h3> 157 <table> 158 <tr> 159 <td> 160 <a target="_blank" href="http://eapm/">Planning IT ID</a> 161 </td> 162 <td> 163 @Html.TextBoxFor(m => m.PitId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://eapm" }) 164 @Html.ValidationMessageFor(m => m.PitId) 165 </td> 166 </tr> 167 168 <tr> 169 <td> 170 <a target="_blank" href="http://engageisrm/">SRA ID</a> 171 </td> 172 <td> 173 @Html.TextBoxFor(m => m.SraId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://engageisrm. " }) 174 @Html.ValidationMessageFor(m => m.SraId) 175 </td> 176 </tr> 177 178 <tr> 179 <td> 180 <a target="_blank" href="http://getsecure/">SDL Track ID</a> 181 </td> 182 <td> 183 @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." }) 184 @Html.ValidationMessageFor(m => m.SdlTrackId) 185 </td> 186 </tr> 187 188 <tr> 189 <td> 190 <a target="_blank" href="http://getsecure/">eSDL ID</a> 191 </td> 192 <td> 193 @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." }) 194 @Html.ValidationMessageFor(m => m.EsdlId) 195 </td> 196 </tr> 197 198 <tr> 199 <td> 200 <a target="_blank" href="http://eapm/">MS Apps ID</a> 201 </td> 202 <td> 203 @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." }) 204 @Html.ValidationMessageFor(m => m.MsAppId) 205 </td> 206 </tr> 207 </table> 208 </div> 209 } 210 else 211 { 212 <div id="tabProjectInformation" style="display: none;"> 213 <h3>Project Information:</h3> 214 <table> 215 <tr> 216 <td> 217 <a target="_blank" href="http://eapm/">Planning IT ID</a> 218 </td> 219 <td> 220 @Html.TextBoxFor(m => m.PitId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://eapm" }) 221 @Html.ValidationMessageFor(m => m.PitId) 222 </td> 223 </tr> 224 225 <tr> 226 <td> 227 <a target="_blank" href="http://engageisrm/">SRA ID</a> 228 </td> 229 <td> 230 @Html.TextBoxFor(m => m.SraId, new { @class = "wide", @title = "Required for actual Extranet Sign-off Request.Obtain from http://engageisrm. " }) 231 @Html.ValidationMessageFor(m => m.SraId) 232 </td> 233 </tr> 234 235 <tr> 236 <td> 237 <a target="_blank" href="http://getsecure/">SDL Track ID</a> 238 </td> 239 <td> 240 @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." }) 241 @Html.ValidationMessageFor(m => m.SdlTrackId) 242 </td> 243 </tr> 244 245 <tr> 246 <td> 247 <a target="_blank" href="http://getsecure/">eSDL ID</a> 248 </td> 249 <td> 250 @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." }) 251 @Html.ValidationMessageFor(m => m.EsdlId) 252 </td> 253 </tr> 254 255 <tr> 256 <td> 257 <a target="_blank" href="http://eapm/">MS Apps ID</a> 258 </td> 259 <td> 260 @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." }) 261 @Html.ValidationMessageFor(m => m.MsAppId) 262 </td> 263 </tr> 264 </table> 265 </div> 266 } 267 268 <h3>Agreement:</h3> 269 <p> 270 @Html.CheckBoxFor(m => m.Agreement, new { @class = "left" }) 271 <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. 272 <br /> 273 @Html.ValidationMessageFor(m => m.Agreement) 274 </p> 275 276 <div class="formright" style="text-align: left"> 277 278 <input name="submitButton" id="submitButton" type="submit" value="Submit" class="button" /> 279 </div> 280 281 } ViewCode

对应的Model如下:

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 using System.Web; 6 using System.ComponentModel.DataAnnotations; 7 8 9 namespace Q6.Models 10 { 11 12 public class ScanRequestModel 13 { 14 15 /// <summary> 16 /// Gets or sets the identifier for the scan request. 17 /// </summary> 18 public int ScanRequestId 19 { 20 get; 21 set; 22 } 23 24 /// <summary> 25 /// CR#1796870 modify by v-yangwu, create a ServerIPsModel when declare a ScanRequestModel 26 /// </summary> 27 public ScanRequestModel() 28 { 29 ServerIPs = new List<ServerIPsModel>(); 30 } 31 32 /// <summary> 33 /// CR#1796870 modify by v-yangwu, Add a ServerIPsModel list 34 /// </summary> 35 public List<ServerIPsModel> ServerIPs { get; set; } 36 37 38 39 /// <summary> 40 /// CR#1796870 modify by v-yangwu, gets or sets the scan type 41 /// </summary> 42 [DisplayName("ScanType")] 43 public string ScanType { get; set; } 44 45 /// <summary> 46 /// Gets or sets the date created. 47 /// </summary> 48 [DisplayName("Date Created")] 49 public DateTime CreatedDate 50 { 51 get; 52 set; 53 } 54 55 /// <summary> 56 /// Gets or sets the ip name. 57 /// </summary> 58 [DisplayName("Request Status")] 59 public string RequestStatus 60 { 61 get; 62 set; 63 } 64 65 /// <summary> 66 /// CR#1796870 modify by v-yangwu, update "Friendly Name" to "Scan Name" 67 /// Gets or sets the ip name. 68 /// </summary> 69 [Required] 70 [DisplayName("Scan Name")] 71 public string Title 72 { 73 get; 74 set; 75 } 76 77 /// <summary> 78 /// Gets or sets the requestor alias. 79 /// </summary> 80 [DisplayName("Requestor Alias")] 81 public string RequestorAlias 82 { 83 get; 84 set; 85 } 86 87 /// <summary> 88 /// Gets or sets the Pit Id. 89 /// </summary> 90 [Required] 91 [DisplayName("Planning IT ID")] 92 public string PitId 93 { 94 get; 95 set; 96 } 97 98 /// <summary> 99 /// Gets or sets the Sra Id. 100 /// </summary> 101 [Required] 102 [DisplayName("SRA ID")] 103 public string SraId 104 { 105 get; 106 set; 107 } 108 109 /// <summary> 110 /// Gets or sets the Sdl Track Id. 111 /// </summary> 112 [DisplayName("SDL Track ID")] 113 public string SdlTrackId 114 { 115 get; 116 set; 117 } 118 119 /// <summary> 120 /// Gets or sets the Esdl Id. 121 /// </summary> 122 [DisplayName("eSDL ID")] 123 public string EsdlId 124 { 125 get; 126 set; 127 } 128 129 /// <summary> 130 /// Gets or sets the Ms App Id. 131 /// </summary> 132 [DisplayName("MS Apps ID")] 133 public string MsAppId 134 { 135 get; 136 set; 137 } 138 139 /// <summary> 140 /// Gets or sets the Ms App Id. 141 /// </summary> 142 [CustomValidation(typeof(ValidationHasToBeTrue), "ValidateTrue")] 143 [DisplayName("Agreement")] 144 public bool Agreement 145 { 146 get; 147 set; 148 } 149 150 /// <summary> 151 /// Gets or sets the Notification Alias List. 152 /// </summary> 153 [DisplayName("Notification List")] 154 public string NotificationList 155 { 156 get; 157 set; 158 } 159 } 160 161 public class ValidationHasToBeTrue 162 { 163 public static ValidationResult ValidateTrue(bool boolHasToBeTrue) 164 { 165 if(boolHasToBeTrue) 166 { 167 return ValidationResult.Success; 168 } 169 else 170 { 171 return new ValidationResult("Agreement must be accepted."); 172 } 173 } 174 } 175 } ScanRequestModel 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.ComponentModel; 6 using System.ComponentModel.DataAnnotations; 7 8 namespace Q6.Models 9 { 10 /// <summary> 11 /// CR#1796870 modify by v-yangwu, Add ServerIPsModel to store IPs 12 /// </summary> 13 public class ServerIPsModel 14 { 15 16 /// <summary> 17 /// Gets or sets the ip name. 18 /// </summary> 19 [Required] 20 [DisplayName("IP1")] 21 public int Ip1 22 { 23 get; 24 set; 25 } 26 27 /// <summary> 28 /// Gets or sets the ip name. 29 /// </summary> 30 [Required] 31 [DisplayName("IP2")] 32 public int Ip2 33 { 34 get; 35 set; 36 } 37 38 /// <summary> 39 /// Gets or sets the ip name. 40 /// </summary> 41 [Required] 42 [DisplayName("IP3")] 43 public int Ip3 44 { 45 get; 46 set; 47 } 48 49 /// <summary> 50 /// Gets or sets the ip name. 51 /// </summary> 52 [Required] 53 [DisplayName("IP4")] 54 public int Ip4 55 { 56 get; 57 set; 58 } 59 60 /// <summary> 61 /// Gets or sets the ip name. 62 /// </summary> 63 [Required] 64 [DisplayName("IP range")] 65 public int Ip5 66 { 67 get; 68 set; 69 } 70 71 /// <summary> 72 /// gets or sets the errormessage for IP1-IP5 73 /// </summary> 74 public string Errormessage 75 { 76 get; 77 set; 78 } 79 80 /// <summary> 81 /// gets or sets the errormessage for the ceate Date 82 /// </summary> 83 public string ErrormessageCreateDate 84 { 85 get; 86 set; 87 } 88 89 90 } 91 } ServerIPsModel

对应的Controller如下:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using Q6.Services; 7 using Q6.Models; 8 using Postal; 9 using System.Text.RegularExpressions; 10 using Microsoft.Security.Application; 11 12 namespace Q6.Controllers 13 { 14 public class ScanNowController : Controller 15 { 16 17 private readonly IScanNowService scanNowService; 18 19 private readonly IActiveDirectoryService activeDirectoryService; 20 21 public ScanNowController(IScanNowService scanNowService, IActiveDirectoryService activeDirectoryService) 22 { 23 this.activeDirectoryService = activeDirectoryService; 24 this.scanNowService = scanNowService; 25 } 26 27 [HttpGet] 28 [ValidateInput(false)] 29 public ActionResult Index() 30 { 31 ViewBag.Message = "Scan Now."; 32 ScanRequestModel model = new ScanRequestModel(); 33 34 //CR#1796870 modify by v-yangwu, add a list for Server Ip by default 35 ServerIPsModel SIM = new ServerIPsModel(); 36 model.ServerIPs.Add(SIM); 37 //Extranet Scan is default 38 model.ScanType = "0"; 39 //CR#1796870 End 40 41 string[] userAlias = User.Identity.Name.Split('\\'); 42 43 model.RequestorAlias = userAlias[1]; 44 45 return this.View(model); 46 } 47 48 [HttpPost] 49 [ValidateInput(false)] 50 public ActionResult Index(ScanRequestModel model) 51 { 52 model.RequestorAlias = Sanitizer.GetSafeHtmlFragment(model.RequestorAlias); 53 54 string AceTeamAlias = scanNowService.GetConfigurationByName("AceTeamAlias"); 55 string Q6DevTeam = scanNowService.GetConfigurationByName("Q6DevTeam"); 56 57 bool isUserAceAnalyst = activeDirectoryService.DoesUserAccountExistInSpecifiedGroup(User.Identity.Name, AceTeamAlias); 58 bool isUserQ6Dev = activeDirectoryService.DoesUserAccountExistInSpecifiedGroup(User.Identity.Name, Q6DevTeam); 59 60 string[] userAlias = User.Identity.Name.Split('\\'); 61 model.RequestorAlias = userAlias[1]; 62 63 //CR#1796870 modify by v-yangwu, Add for loop to 1.Combine ip string; 2.validate ips 64 string ipAll = string.Empty; 65 for (int ipAccount = 0; ipAccount < model.ServerIPs.Count; ipAccount++) 66 { 67 #region Combine ip string 68 int IpDifference = 0; 69 string tempIp = model.ServerIPs[ipAccount].Ip1 + "." + model.ServerIPs[ipAccount].Ip2 + "." + model.ServerIPs[ipAccount].Ip3 + "." + model.ServerIPs[ipAccount].Ip4; 70 if (model.ServerIPs[ipAccount].Ip5 != 0) 71 { 72 IpDifference = model.ServerIPs[ipAccount].Ip5 - model.ServerIPs[ipAccount].Ip4; 73 74 for (int count = 0; count < IpDifference; count++) 75 { 76 tempIp = tempIp + "," + model.ServerIPs[ipAccount].Ip1 + "." + model.ServerIPs[ipAccount].Ip2 + "." + model.ServerIPs[ipAccount].Ip3 + "." + (model.ServerIPs[ipAccount].Ip4 + (count + 1)); 77 } 78 } 79 if (ipAccount == 0) 80 { 81 ipAll = tempIp; 82 } 83 else 84 { 85 ipAll = ipAll + "," + tempIp; 86 } 87 #endregion 88 89 #region validate ips 90 //CR#1796870 modify by v-yangwu 91 string iperr = string.Empty; 92 bool isvalidated=false; 93 if (!isIp1Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev)) 94 { 95 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip1", "IP1 is out of range."); 96 iperr = "IP1"; 97 isvalidated=true; 98 } 99 if (!isIp2Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev)) 100 { 101 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip2", "IP2 is out of range."); 102 iperr = iperr + ", IP2"; 103 isvalidated=true; 104 } 105 if (!isIp3Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev)) 106 { 107 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip3", "IP3 is out of range."); 108 iperr = iperr + ", IP3"; 109 isvalidated=true; 110 } 111 if (!isIp4Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev)) 112 { 113 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip4", "IP4 is out of range."); 114 iperr = iperr + ", IP4"; 115 isvalidated=true; 116 } 117 if (!isIp5Valid(model.ServerIPs[ipAccount], isUserAceAnalyst, isUserQ6Dev)) 118 { 119 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip5", "IP5 is out of range."); 120 iperr = iperr + ", IP5"; 121 isvalidated=true; 122 } 123 //CR#1796870 modify by v-yangwu 124 if (isvalidated) 125 { 126 iperr = iperr.Trim(',', ' '); 127 model.ServerIPs[ipAccount].Errormessage = iperr + " is out of range."; 128 } 129 130 #endregion 131 132 #region DateCreatedValid 133 if (!isvalidated) 134 { 135 if (!isDateCreatedValid(tempIp)) 136 { 137 //ModelState.AddModelError("CreatedDate", "Can not scan the current IP, it was scanned a few hours ago."); 138 ModelState.AddModelError("ServerIPs[" + ipAccount + "].Ip5", "Can not scan the current IP, it was scanned a few hours ago."); 139 model.ServerIPs[ipAccount].ErrormessageCreateDate = "Can not scan the current IP, it was scanned a few hours ago."; 140 } 141 } 142 #endregion 143 } 144 //CR#1796870 End 145 146 var regexItem = new Regex("^[a-zA-Z0-9 ]*$"); 147 if (model.Title != null) 148 { 149 if (!regexItem.IsMatch(model.Title)) 150 { 151 ModelState.AddModelError("Title", "Invalid Character on the Friendly Name"); 152 } 153 if (model.Title.Contains('\\') || model.Title.Contains('/')) 154 { 155 ModelState.AddModelError("Title", "The Friendly Name can not contain \\ or /"); 156 } 157 } 158 159 if (model.NotificationList != null) 160 { 161 model.NotificationList = model.NotificationList.Trim(); 162 if (model.NotificationList != string.Empty) 163 { 164 if (!isNotificationListValid(model.NotificationList)) 165 { 166 ModelState.AddModelError("NotificationList", "One or more aliases are not valid"); 167 } 168 } 169 } 170 171 //CR#1796870 modify by v-yangwu, if Scan type is Extranet, the Project Information is required. 172 if (model.ScanType == "0") 173 { 174 //Ignore SRAID and PITID if any of the DGs 175 if (isUserAceAnalyst || isUserQ6Dev) 176 { 177 ModelState.Remove("SraId"); 178 ModelState.Remove("PitId"); 179 } 180 181 try 182 { 183 uint tempSraId = Convert.ToUInt32(model.SraId); 184 int tempintSraId = Convert.ToInt32(model.SraId); 185 model.SraId = tempSraId.ToString(); 186 187 } 188 catch (Exception) 189 { 190 ModelState.AddModelError("SraId", "Invalid SRA ID."); 191 } 192 193 try 194 { 195 uint tempSdl = Convert.ToUInt32(model.SdlTrackId); 196 int tempintSdlTrackId = Convert.ToInt32(model.SdlTrackId); 197 model.SdlTrackId = tempSdl.ToString(); 198 199 } 200 catch (Exception) 201 { 202 ModelState.AddModelError("SdlTrackId", "Invalid SDL Track ID."); 203 } 204 try 205 { 206 uint tempEsdl = Convert.ToUInt32(model.EsdlId); 207 int tempintEsdlId = Convert.ToInt32(model.EsdlId); 208 model.EsdlId = tempEsdl.ToString(); 209 210 } 211 catch (Exception) 212 { 213 ModelState.AddModelError("EsdlId", "Invalid eSDL ID."); 214 } 215 try 216 { 217 uint tempMSApp = Convert.ToUInt32(model.MsAppId); 218 int tempintMsAppId = Convert.ToInt32(model.MsAppId); 219 model.MsAppId = tempMSApp.ToString(); 220 221 } 222 catch (Exception) 223 { 224 ModelState.AddModelError("MsAppId", "Invalid MS Apps ID."); 225 } 226 } 227 else 228 { 229 ModelState.Remove("SraId"); 230 ModelState.Remove("PitId"); 231 model.MsAppId = null; 232 model.SdlTrackId = null; 233 model.EsdlId = null; 234 } 235 //CR#1796870 End 236 237 238 if (!ModelState.IsValid) 239 { 240 return this.View(model); 241 } 242 243 //CR#1796870 modify by v-yangwu, Update paramater for CreateRequest 244 //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); 245 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); 246 247 if (result == string.Empty) 248 { 249 return this.RedirectToAction("Index", "History"); 250 } 251 else 252 { 253 ViewBag.AddSuccess = result; 254 return this.View(model); 255 } 256 257 } 258 259 [HttpGet] 260 public ActionResult EditScan(int id) 261 { 262 ViewBag.Message = "Scan Now."; 263 ViewBag.ScanRequestId = id; 264 string[] userAlias = User.Identity.Name.Split('\\'); 265 ScanRequestModel model = scanNowService.GetRequestDataById(id, userAlias[1]); 266 string[] notificationList = model.NotificationList.Split(';'); 267 ViewBag.NotificationListFlag = false; 268 foreach (string user in notificationList) 269 { 270 if (user.Contains(userAlias[1])) 271 { 272 ViewBag.NotificationListFlag = true; 273 } 274 } 275 276 if (model.ScanRequestId != 0) 277 { 278 return this.View(model); 279 } 280 else 281 { 282 return this.RedirectToAction("Index", "History"); 283 } 284 285 } 286 287 [HttpGet] 288 [ValidateInput(false)] 289 public ActionResult CancelScan(string id) 290 { 291 string[] userAlias = User.Identity.Name.Split('\\'); 292 string result = scanNowService.CancelScan(id, userAlias[1]); 293 return this.View(); 294 } 295 296 [HttpPost] 297 public void SendEmail(string key, string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress) 298 { 299 string[] userAlias = User.Identity.Name.Split('\\'); 300 User.Identity.Name.Split('\\'); 301 string q6svc = scanNowService.GetConfigurationByName("Q6ServiceAccount"); 302 if (key == "Qualys") 303 { 304 if (userAlias[1] == q6svc) 305 { 306 scanNowService.SendEmail(request_id, owner, notification_list, title, PCReportAddress, VMReportAddress); 307 } 308 } 309 } 310 311 [HttpPost] 312 [ValidateInput(false)] 313 [ValidateAntiForgeryToken()] 314 public ActionResult EditScan(int id, ScanRequestModel model) 315 { 316 string[] userAlias = User.Identity.Name.Split('\\'); 317 ScanRequestModel RequestModel = scanNowService.GetRequestDataById(id, userAlias[1]); 318 string[] newNotificationList = null; 319 string[] oldNotificationList = RequestModel.NotificationList.Split(';'); 320 List<string> emailList = new List<string>(); 321 322 ViewBag.NotificationListFlag = false; 323 324 //If the new list is not empty 325 if (model.NotificationList != null) 326 { 327 // Turn on flag for notificationlist in the UI 328 newNotificationList = model.NotificationList.Split(';'); 329 string tempNotificationList = string.Empty; 330 //Trim white spaces 331 for (int count = 0; count < newNotificationList.Count(); count++) 332 { 333 newNotificationList[count] = newNotificationList[count].Trim(); 334 } 335 336 foreach (string user in newNotificationList) 337 { 338 if (user.Contains(userAlias[1])) 339 { 340 ViewBag.NotificationListFlag = true; 341 } 342 } 343 344 //Find new emailList 345 string tempString = string.Empty; 346 bool found = false; 347 foreach (string newAlias in newNotificationList) 348 { 349 foreach (string oldAlias in oldNotificationList) 350 { 351 if (oldAlias.Trim() == newAlias.Trim()) 352 { 353 found = true; 354 break; 355 } 356 tempString = newAlias.Trim(); 357 } 358 if (found == false) 359 { 360 emailList.Add(tempString); 361 } 362 tempString = string.Empty; 363 found = false; 364 } 365 } 366 367 ViewBag.Message = "Scan Now."; 368 369 //Update the request with the new notification Alias. 370 if (model.NotificationList != null) 371 { 372 if (model.NotificationList != string.Empty) 373 { 374 if (!isNotificationListValid(model.NotificationList)) 375 { 376 ModelState.AddModelError("NotificationList", "One or more aliases are not valid"); 377 } 378 } 379 } 380 381 ModelState.Remove("Title"); 382 ModelState.Remove("Agreement"); 383 ModelState.Remove("SraId"); 384 ModelState.Remove("PitId"); 385 if (!ModelState.IsValid) 386 { 387 return this.View(RequestModel); 388 } 389 //Send to DB 390 391 string result = scanNowService.UpdateNotificationListonOnRequest(id, newNotificationList, userAlias[1], emailList, RequestModel.RequestStatus); 392 393 if (result == string.Empty) 394 { 395 ViewBag.AddSuccess = "The Notification List was updated successfully"; 396 return this.View(RequestModel); 397 } 398 else 399 { 400 ViewBag.AddSuccess = result; 401 return this.View(RequestModel); 402 } 403 } 404 405 //CR#1796870 modify by v-yangwu, update parameter for isDateCreatedValid() 406 //private bool isDateCreatedValid(ScanRequestModel model) 407 private bool isDateCreatedValid(string ip) 408 { 409 return scanNowService.isDateCreatedValid(ip); 410 } 411 412 private bool isNotificationListValid(string NotificationList) 413 { 414 bool isNotificationListValid = true; 415 IEnumerable<string> tempNotificationList = ParseNotificationList(NotificationList); 416 foreach (string alias in tempNotificationList) 417 { 418 if (!activeDirectoryService.DoesMailEnabledAccountExist(alias)) 419 { 420 isNotificationListValid = false; 421 return isNotificationListValid; 422 } 423 } 424 return isNotificationListValid; 425 } 426 427 private string[] ParseNotificationList(string NotificationList) 428 { 429 string[] tempNotificationList; 430 tempNotificationList = NotificationList.Split(';'); 431 return tempNotificationList; 432 } 433 434 //CR#1796870 modify by v-yangwu, Change the first parameter model to ServerIPsModel for valid method 435 private bool isIp1Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev) 436 { 437 if (isUserAceAnalyst) 438 { 439 if (model.Ip1 <= 255 && model.Ip1 >= 0) 440 { 441 return true; 442 } 443 else 444 { 445 return false; 446 } 447 } 448 else 449 { 450 if (model.Ip1 == 10) 451 { 452 return true; 453 } 454 else 455 { 456 return false; 457 } 458 } 459 } 460 private bool isIp2Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev) 461 { 462 if (isUserAceAnalyst) 463 { 464 if (model.Ip2 <= 255 && model.Ip2 >= 0) 465 { 466 return true; 467 } 468 else 469 { 470 return false; 471 } 472 } 473 else if (isUserQ6Dev) 474 { 475 if (model.Ip2 == 121 || model.Ip2 == 248 || model.Ip2 == 249 || model.Ip2 == 251 || model.Ip2 == 253) 476 { 477 return true; 478 } 479 else 480 { 481 return false; 482 } 483 } 484 else 485 { 486 if (model.Ip2 == 248 || model.Ip2 == 249 || model.Ip2 == 251 || model.Ip2 == 253) 487 { 488 return true; 489 } 490 else 491 { 492 return false; 493 } 494 } 495 } 496 private bool isIp3Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev) 497 { 498 if (isUserAceAnalyst) 499 { 500 if (model.Ip3 <= 255 && model.Ip3 >= 0) 501 { 502 return true; 503 } 504 else 505 { 506 return false; 507 } 508 } 509 else if (isUserQ6Dev) 510 { 511 if (model.Ip2 == 121 && model.Ip3 == 150) 512 { 513 return true; 514 } 515 else if (model.Ip2 == 248 && model.Ip3 <= 31 && model.Ip3 >= 0) 516 { 517 return true; 518 } 519 else if (model.Ip2 == 249 && model.Ip3 <= 255 && model.Ip3 >= 0) 520 { 521 return true; 522 } 523 else if (model.Ip2 == 251 && model.Ip3 <= 255 && model.Ip3 >= 0) 524 { 525 return true; 526 } 527 else if (model.Ip2 == 253 && model.Ip3 <= 255 && model.Ip3 >= 0) 528 { 529 return true; 530 } 531 else 532 { 533 return false; 534 } 535 } 536 else 537 { 538 if (model.Ip2 == 248 && model.Ip3 <= 31 && model.Ip3 >= 0) 539 { 540 return true; 541 } 542 else if (model.Ip2 == 249 && model.Ip3 <= 255 && model.Ip3 >= 0) 543 { 544 return true; 545 } 546 else if (model.Ip2 == 251 && model.Ip3 <= 255 && model.Ip3 >= 0) 547 { 548 return true; 549 } 550 else if (model.Ip2 == 253 && model.Ip3 <= 255 && model.Ip3 >= 0) 551 { 552 return true; 553 } 554 else 555 { 556 return false; 557 } 558 } 559 } 560 private bool isIp4Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev) 561 { 562 if (model.Ip4 <= 255 && model.Ip4 >= 0) 563 { 564 return true; 565 } 566 else 567 { 568 return false; 569 } 570 } 571 private bool isIp5Valid(ServerIPsModel model, bool isUserAceAnalyst, bool isUserQ6Dev) 572 { 573 if (model.Ip5 > model.Ip4 || model.Ip5 == 0) 574 { 575 //CR#1796870 modify by v-yangwu, add a condition which judge if ip5 <= 255 576 if (model.Ip3 <= 255 && model.Ip3 >= 0 && model.Ip5 <= 255) 577 { 578 return true; 579 } 580 else 581 { 582 return false; 583 } 584 } 585 else 586 { 587 return false; 588 } 589 } 590 //CR#1796870 End 591 } 592 } ScanNowController

需要用到的Class如下:

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using Q6.Repositories; 6 using Q6.Models; 7 using System.Xml.Linq; 8 using System.Collections.Specialized; 9 using System.Configuration; 10 using System.Net; 11 using System.Text; 12 using System.IO; 13 using System.Xml; 14 using System.Threading; 15 using Postal; 16 using Microsoft.Practices.Unity; 17 18 namespace Q6.Services 19 { 20 public class ScanNowService : IScanNowService 21 { 22 private readonly IEmailService emailService; 23 24 private readonly IScanNowRepository scanNowRepository; 25 26 private readonly string QualysAddress = "http://www.baidu.com"; 27 28 /// <summary> 29 /// Initializes a new instance of the <see cref="NotificationService"/> class. 30 /// </summary> 31 /// <param name="activeDirectoryService">The active directory service.</param> 32 [InjectionConstructor] 33 public ScanNowService(IScanNowRepository scanNowRepository) 34 : this(scanNowRepository, new EmailService()) 35 { 36 } 37 38 public ScanNowService(IScanNowRepository scanNowRepository, IEmailService emailService) 39 { 40 this.emailService = emailService; 41 this.scanNowRepository = scanNowRepository; 42 43 } 44 45 public void SendEmail(string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress) 46 { 47 string[] alias; 48 string CC = string.Empty; 49 if (notification_list != string.Empty) 50 { 51 dynamic CompletedEmail = new Email("ScanCompletedWithCC"); 52 CompletedEmail.To = owner + "@microsoft.com"; 53 CompletedEmail.SubjectName = title; 54 alias = notification_list.Split(';'); 55 foreach (string email in alias) 56 { 57 if (email != string.Empty) 58 { 59 if (CC == string.Empty) 60 { 61 CC = email + "@microsoft.com"; 62 } 63 else 64 { 65 CC = CC + "," + email + "@microsoft.com"; 66 } 67 68 } 69 } 70 CompletedEmail.CC = CC; 71 CompletedEmail.PCReportAddress = PCReportAddress; 72 CompletedEmail.VMReportAddress = VMReportAddress; 73 this.emailService.Send(CompletedEmail); 74 } 75 else 76 { 77 dynamic CompletedEmail = new Email("ScanCompleted"); 78 CompletedEmail.To = owner + "@microsoft.com"; 79 CompletedEmail.SubjectName = title; 80 CompletedEmail.PCReportAddress = PCReportAddress; 81 CompletedEmail.VMReportAddress = VMReportAddress; 82 this.emailService.Send(CompletedEmail); 83 } 84 } 85 86 //CR#1796870 modify by v-yangwu, update parameters for CreateRequest() 87 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) 88 { 89 QualysSettingsModel QualysSettings = new QualysSettingsModel(); 90 /* Add reports from configuration file */ 91 QualysSettings = this.scanNowRepository.GetAllConfigurations(); 92 93 string QualysAddress = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysAddress").Value; 94 string qualysUser = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysUser").Value; 95 string qualysPass = QualysSettings.Settings.FirstOrDefault(x => x.Key == "QualysPass").Value; 96 string vm_Option_Profile = QualysSettings.Settings.FirstOrDefault(x => x.Key == "VMOptionProfile").Value; 97 string scanner_name = QualysSettings.Settings.FirstOrDefault(x => x.Key == "Scanner_Name").Value; 98 int pcProfile = Convert.ToInt32(QualysSettings.Settings.FirstOrDefault(x => x.Key == "PCProfileId").Value); 99 100 //CR#1796870 modify by v-yangwu, update parameters for CreateRequest() 101 //Create Request in database as Created 102 string result = this.scanNowRepository.CreateRequest(ipAll, title, requestorAlias, pitId, sraId, sdlTrackId, esdlId, msAppId, NotificationList, OperatorAlias,ScanType); 103 104 if (!result.Contains("Error")) 105 { 106 //CR#1796870 modify by v-yangwu, remove the IPs which are repeated. 107 string[] arrayIP = ipAll.Split(','); 108 List<string> listIP = new List<string>(); 109 foreach (string ip in arrayIP) 110 { 111 if (!listIP.Contains(ip)) 112 { 113 listIP.Add(ip); 114 } 115 } 116 string ipAllNew = listIP[0]; 117 for (int ipaccount = 1; ipaccount < listIP.Count(); ipaccount++) 118 { 119 ipAllNew += "," + listIP[ipaccount]; 120 } 121 ipAll = ipAllNew; 122 //CR#1796870 End 123 124 //CR#1796870 modify by v-yangwu, update parameters for Send Request to Qualys. 125 string vmScanResult = SendVMRequestToQualys(ipAll, title, scanner_name, qualysUser, qualysPass, vm_Option_Profile); 126 string pcScanResult = SendPCRequestToQualys(ipAll, title, scanner_name, qualysUser, qualysPass, pcProfile); 127 128 if (!pcScanResult.Contains("Error") || !vmScanResult.Contains("Error")) 129 { 130 result = this.scanNowRepository.UpdateRequestToPending(Convert.ToInt32(result)); 131 } 132 else 133 { 134 result = "PC SCan: " + pcScanResult + " VM Scan: " + vmScanResult; 135 } 136 137 } 138 139 if(!result.Contains("Error")) 140 { 141 result = string.Empty; 142 } 143 144 return result; 145 } 146 147 public string CancelScan(string id, string alias) 148 { 149 //Get the current Scan information by id 150 151 //Get the reference for VM 152 //Cancel VM Request 153 //CancelVMScan(); 154 155 //Get the reference for PC 156 //Cancel PC Request 157 //CancelPCScan(); 158 return ""; 159 } 160 161 private string SendVMRequestToQualys(string ip, string title, string scanner_name, string qualysUser, string qualysPass, string vm_Option_Profile) 162 { 163 string result = string.Empty; 164 165 string VMScanAddress = "/msp/scan.php?"; 166 167 try 168 { 169 //Create http request 170 string requestAddress = (QualysAddress + VMScanAddress); 171 172 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestAddress); 173 req.Method = "POST"; 174 //Authentication 175 byte[] authInfo = new UTF8Encoding().GetBytes(qualysUser + ":" + qualysPass); 176 req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authInfo); 177 req.Headers["X-Requested-With"] = "XMLHttpRequest"; 178 req.ContentType = "application/x-www-form-urlencoded"; 179 //Information 180 string postData = ""; 181 182 postData += "ip=" + ip; 183 postData += "&"; 184 postData += "scan_title=" + title; 185 postData += "&"; 186 postData += "iscanner_name=" + scanner_name; 187 postData += "&"; 188 postData += "option=" + vm_Option_Profile; 189 postData += "&"; 190 postData += "save_report=" + "yes"; 191 192 Byte[] postBytes = Encoding.UTF8.GetBytes(postData); 193 req.ContentLength = postData.Length; 194 195 using (var dataStream = req.GetRequestStream()) 196 { 197 dataStream.Write(postBytes, 0, postBytes.Length); 198 } 199 200 //Get Response 201 ThreadPool.QueueUserWorkItem(o => { req.GetResponse(); }); 202 203 } 204 catch (WebException e) 205 { 206 using (WebResponse response = e.Response) 207 { 208 HttpWebResponse httpResponse = (HttpWebResponse)response; 209 Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 210 using (Stream data = response.GetResponseStream()) 211 { 212 result = new StreamReader(data).ReadToEnd(); 213 214 } 215 } 216 } 217 218 return result; 219 } 220 221 private string SendPCRequestToQualys(string ip, string title, string scanner_name, string qualysUser, string qualysPass, int profileid) 222 { 223 string result = string.Empty; 224 string PCScanAddress = "/api/2.0/fo/scan/compliance/"; 225 try 226 { 227 //Create http request 228 string requestAddress = (QualysAddress + PCScanAddress); 229 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestAddress); 230 req.Method = "POST"; 231 //Authentication 232 byte[] authInfo = new UTF8Encoding().GetBytes(qualysUser + ":" + qualysPass); 233 req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authInfo); 234 req.Headers["X-Requested-With"] = "XMLHttpRequest"; 235 req.ContentType = "application/x-www-form-urlencoded"; 236 //Information 237 string postData = ""; 238 postData += "action=" + "launch"; 239 postData += "&"; 240 postData += "ip=" + ip; 241 postData += "&"; 242 postData += "scan_title=" + title; 243 postData += "&"; 244 postData += "iscanner_name=" + scanner_name; 245 postData += "&"; 246 postData += "option_id=" + profileid; 247 postData += "&"; 248 postData += "echo_request=" + 1; 249 250 Byte[] postBytes = Encoding.UTF8.GetBytes(postData); 251 req.ContentLength = postData.Length; 252 253 using (var dataStream = req.GetRequestStream()) 254 { 255 dataStream.Write(postBytes, 0, postBytes.Length); 256 } 257 258 //Get Response 259 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 260 Stream respStream = resp.GetResponseStream(); 261 StreamReader reader = new StreamReader(respStream); 262 result = reader.ReadToEnd(); 263 result = validateResponse(result); 264 265 } 266 catch (WebException e) 267 { 268 using (WebResponse response = e.Response) 269 { 270 HttpWebResponse httpResponse = (HttpWebResponse)response; 271 Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 272 using (Stream data = response.GetResponseStream()) 273 { 274 result = new StreamReader(data).ReadToEnd(); 275 } 276 } 277 } 278 279 return result; 280 } 281 282 private string validateResponse(string response) 283 { 284 string result = string.Empty; 285 XmlReaderSettings settings = new XmlReaderSettings(); 286 settings.DtdProcessing = DtdProcessing.Parse; 287 StringReader stringReader = null; 288 289 try 290 { 291 stringReader = new StringReader(response); 292 using (XmlReader reader = XmlReader.Create(stringReader, settings)) 293 { 294 stringReader = null; 295 XDocument readerDocument = XDocument.Load(reader); 296 try 297 { 298 IEnumerable<XElement> results = new List<XElement>(); 299 results = (IEnumerable<XElement>)readerDocument.Root.Element("RESPONSE").Element("ITEM_LIST").Descendants(); 300 List<XElement> resultss = (List<XElement>)results.ToList(); 301 result = resultss[5].Value.ToString(); 302 303 304 } 305 catch (Exception) 306 { 307 result = "Error: " + readerDocument.Root.Element("RESPONSE").Element("TEXT").Value.ToString(); 308 } 309 } 310 } 311 finally 312 { 313 if (stringReader != null) 314 { 315 stringReader.Dispose(); 316 } 317 } 318 319 return result; 320 } 321 322 public ScanRequestModel GetRequestDataById(int Id, String Alias) 323 { 324 return this.scanNowRepository.GetRequestDataById(Id, Alias); 325 326 } 327 328 public string UpdateNotificationListonOnRequest(int Id, string[] NotificationList, string requestorAlias, List<string> emailList, string requestStatus) 329 { 330 string result = this.scanNowRepository.UpdateNotificationListonOnRequest(Id, NotificationList, requestorAlias); 331 332 if (requestStatus == "Completed") 333 { 334 foreach (string alias in emailList) 335 { 336 dynamic createdEmail = new Email("NewToNotificationList"); 337 338 createdEmail.To = alias + "@microsoft.com"; 339 340 createdEmail.SubjectName = "Qualys Notification List Updated"; 341 342 //Send Email Notifications 343 this.emailService.Send(createdEmail); 344 } 345 } 346 347 return result; 348 } 349 350 public bool isDateCreatedValid(string Ip) 351 { 352 return this.scanNowRepository.isDateCreatedValid(Ip); 353 } 354 355 public string GetConfigurationByName(string configurationName) 356 { 357 return this.scanNowRepository.GetConfigurationByName(configurationName); 358 } 359 } 360 } ScanNowService

 

1 using System; 2 using System.Collections.Generic; 3 namespace Q6.Services 4 { 5 public interface IScanNowService 6 { 7 //CR#1796870 modify by v-yangwu, update parameters for CreateRequest() 8 string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType); 9 Q6.Models.ScanRequestModel GetRequestDataById(int Id, String Alias); 10 string UpdateNotificationListonOnRequest(int Id, string[] NotificationList, string requestorAlias, List<string> emailList, string requestStatus); 11 bool isDateCreatedValid(string Ip); 12 string GetConfigurationByName(string configurationName); 13 string CancelScan(string id, string alias); 14 void SendEmail(string request_id, string owner, string notification_list, string title, string PCReportAddress, string VMReportAddress); 15 } 16 } IScanNowService 1 using System; 2 using Q6.Models; 3 namespace Q6.Repositories 4 { 5 public interface IScanNowRepository 6 { 7 //CR#1796870 modify by v-yangwu, update parameters for CreateRequest() 8 string CreateRequest(string ipAll, string title, string requestorAlias, string pitId, string sraId, string sdlTrackId, string esdlId, string msAppId, string NotificationList, string OperatorAlias,string ScanType); 9 Q6.Models.ScanRequestModel GetRequestDataById(int Id, string Alias); 10 string UpdateNotificationListonOnRequest(int requestId, string[] notificationList, string requestorAlias); 11 string UpdateRequestToPending(int requestId); 12 bool isDateCreatedValid(string Ip); 13 string GetConfigurationByName(string configurationName); 14 QualysSettingsModel GetAllConfigurations(); 15 } 16 } IScanNowRepository 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Globalization; 6 using System.Data; 7 using System.Data.SqlClient; 8 using Q6.Models; 9 10 namespace Q6.Repositories 11 { 12 public class ScanNowRepository : BaseSqlRepository, IScanNowRepository 13 { 14 /// <summary> 15 /// Initializes a new instance of the <see cref="SqlEmployeeRepository"/> class. 16 /// </summary> 17 /// <param name="connectionString">The connection string.</param> 18 public ScanNowRepository(string connectionString) 19 : base(connectionString) 20 { 21 } 22 23 //CR#1796870 modify by v-yangwu, update parameters for CreateRequest() 24 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) 25 { 26 // Send request to Qualys 27 string[] notificationList; 28 29 string result = string.Empty; 30 31 using (DataTable dataTable = new DataTable("Request")) 32 { 33 using (DataTable tableNotificationList = new DataTable("NotificationList")) 34 { 35 tableNotificationList.Locale = CultureInfo.InvariantCulture; 36 tableNotificationList.Columns.Add("NotificationListID", typeof(int)); 37 tableNotificationList.Columns.Add("RequestID", typeof(int)); 38 tableNotificationList.Columns.Add("Alias", typeof(string)); 39 if (NotificationList != null) 40 { 41 notificationList = NotificationList.Split(';'); 42 foreach (string alias in notificationList) 43 { 44 if (alias != requestorAlias) 45 { 46 tableNotificationList.Rows.Add(null, null, alias.Trim()); 47 } 48 } 49 } 50 51 dataTable.Locale = CultureInfo.InvariantCulture; 52 dataTable.Columns.Add("RequestID", typeof(int)); 53 dataTable.Columns.Add("RequestStatusID", typeof(int)); 54 dataTable.Columns.Add("IP", typeof(string)); 55 dataTable.Columns.Add("Title", typeof(string)); 56 dataTable.Columns.Add("Requestor", typeof(string)); 57 dataTable.Columns.Add("PITID", typeof(string)); 58 dataTable.Columns.Add("SRAID", typeof(int)); 59 dataTable.Columns.Add("SDLTrackID", typeof(int)); 60 dataTable.Columns.Add("MSAppID", typeof(int)); 61 dataTable.Columns.Add("ESDID", typeof(int)); 62 dataTable.Columns.Add("PCScanReferenceID", typeof(string)); 63 dataTable.Columns.Add("VMScanReferenceID", typeof(string)); 64 dataTable.Columns.Add("PCReportID", typeof(string)); 65 dataTable.Columns.Add("VMReportID", typeof(string)); 66 dataTable.Columns.Add("PCReportPath", typeof(string)); 67 dataTable.Columns.Add("VMReportPath", typeof(string)); 68 //CR#1796870 modify by v-yangwu, add a columns for ScanType 69 dataTable.Columns.Add("ScanType",typeof(string)); 70 71 //CR#1796870 modify by v-yangwu, update parameter for dataTable.Rows.Add() 72 dataTable.Rows.Add(null, 1, ipAll, title, requestorAlias, pitId, sraId, sdlTrackId, msAppId, esdlId, null, null, null, null,null,null,ScanType); 73 74 using (SqlConnection connection = this.CreateDatabaseConnection()) 75 { 76 using (SqlCommand command = new SqlCommand("dbo.InsertRequest", connection)) 77 { 78 command.CommandType = CommandType.StoredProcedure; 79 command.Parameters.AddWithValue("Request", dataTable); 80 command.Parameters.AddWithValue("NotificationList", tableNotificationList); 81 command.Parameters.AddWithValue("OperatorAlias", OperatorAlias); 82 SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar); 83 param.Direction = ParameterDirection.Output; 84 param.Size = 100; 85 command.Parameters.Add(param); 86 SqlParameter param2 = new SqlParameter("@ID", SqlDbType.VarChar); 87 param2.Direction = ParameterDirection.Output; 88 param2.Size = 100; 89 command.Parameters.Add(param2); 90 91 connection.Open(); 92 command.ExecuteNonQuery(); 93 94 if (param.Value.ToString().Length > 0) 95 { 96 result = "Error - " + param.Value.ToString(); 97 } 98 else 99 { 100 result = param2.Value.ToString(); 101 } 102 103 return result; 104 } 105 } 106 } 107 } 108 } 109 110 public QualysSettingsModel GetAllConfigurations() 111 { 112 QualysSettingsModel QualysSettings = new QualysSettingsModel(); 113 using (SqlConnection connection = this.CreateDatabaseConnection()) 114 { 115 using (SqlCommand command = new SqlCommand("Q6.GetAllConfigurations", connection)) 116 { 117 command.CommandType = CommandType.StoredProcedure; 118 command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output; 119 connection.Open(); 120 121 using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default)) 122 { 123 while (results.Read()) 124 { 125 var key = (string)(results["Name"]); 126 var value = (string)results["ConfigValue"]; 127 QualysSettings.Settings.Add(key, value); 128 129 } 130 } 131 } 132 return QualysSettings; 133 } 134 } 135 136 137 public ScanRequestModel GetRequestDataById(int Id, string Alias) 138 { 139 List<ScanRequestModel> historyList = new List<ScanRequestModel>(); 140 //string[] tempIp; 141 //string tempRange = string.Empty; 142 string tempCompleteIp = string.Empty; 143 144 //CR#1796870 modify by v-yangwu, define scantype 145 string scantype = string.Empty; 146 147 string supportAlias = GetConfigurationByName("Support_Alias"); 148 using (SqlConnection connection = this.CreateDatabaseConnection()) 149 150 if (Alias == supportAlias) 151 { 152 using (SqlCommand command = new SqlCommand("Q6.GetRequestDataByIdForSupport", connection)) 153 { 154 command.CommandType = CommandType.StoredProcedure; 155 command.Parameters.AddWithValue("RequestID", Id); 156 command.Parameters.AddWithValue("Alias", Alias); 157 command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output; 158 connection.Open(); 159 160 using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default)) 161 { 162 while (results.Read()) 163 { 164 ScanRequestModel tempModel = new ScanRequestModel(); 165 tempModel.ScanRequestId = Convert.ToInt32(results["RequestID"], CultureInfo.InvariantCulture); 166 tempCompleteIp = (string)(results["IP"]); 167 168 //CR#1796870 modify by v-yangwu, add scantype to model 169 scantype =(string) results["ScanType"]; 170 tempModel.ScanType = scantype; 171 172 //CR#1796870 Start modify by v-yangwu, parsing the ip string from DB 173 string[] ips; 174 ips = tempCompleteIp.Split(','); 175 int ipsAccount = ips.Count(); 176 //if there are more than 1 ip 177 if (ipsAccount > 1) 178 { 179 int nextIP4 = 0; 180 int count = 0; 181 // 182 bool islast = false; 183 for (int i = 0; i < ipsAccount; i++) 184 { 185 if (i + 1 != ips.Count()) 186 { 187 if (ips[i].Split('.')[0] == ips[i + 1].Split('.')[0] && ips[i].Split('.')[1] == ips[i + 1].Split('.')[1] && ips[i].Split('.')[2] == ips[i + 1].Split('.')[2]) 188 { 189 if (Convert.ToInt32(ips[i].Split('.')[3]) + 1 == Convert.ToInt32(ips[i + 1].Split('.')[3])) 190 { 191 count++; 192 nextIP4 = Convert.ToInt32(ips[i - (count - 1)].Split('.')[3]); 193 islast = false; 194 } 195 else 196 { 197 //judge if there is one ip in one row. 198 if (count > 0) 199 { 200 ServerIPsModel sip = new ServerIPsModel(); 201 202 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 203 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 204 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 205 sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[3]); 206 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 207 208 tempModel.ServerIPs.Add(sip); 209 210 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 211 count = 0; 212 islast = true; 213 } 214 else 215 { 216 ServerIPsModel sip = new ServerIPsModel(); 217 218 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 219 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 220 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 221 sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[3]); 222 sip.Ip5 = 0; 223 224 tempModel.ServerIPs.Add(sip); 225 226 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 227 count = 0; 228 islast = false; 229 } 230 } 231 } 232 else 233 { 234 ServerIPsModel sip = new ServerIPsModel(); 235 236 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 237 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 238 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 239 if (count > 0) 240 { 241 sip.Ip4 = nextIP4; 242 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 243 244 } 245 else 246 { 247 sip.Ip4 = Convert.ToInt32(ips[i].Split('.')[3]); 248 sip.Ip5 = 0; 249 } 250 251 tempModel.ServerIPs.Add(sip); 252 253 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 254 islast = false; 255 //Copy18 256 count = 0; 257 } 258 } 259 else 260 { 261 ServerIPsModel sip = new ServerIPsModel(); 262 263 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 264 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 265 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 266 sip.Ip4 = nextIP4; 267 if (islast || count <= 0) 268 { 269 sip.Ip5 = 0; 270 } 271 else 272 { 273 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 274 } 275 276 tempModel.ServerIPs.Add(sip); 277 } 278 } 279 } 280 else 281 { 282 ServerIPsModel sip = new ServerIPsModel(); 283 284 sip.Ip1 = Convert.ToInt32(ips[0].Split('.')[0]); 285 sip.Ip2 = Convert.ToInt32(ips[0].Split('.')[1]); 286 sip.Ip3 = Convert.ToInt32(ips[0].Split('.')[2]); 287 sip.Ip4 = Convert.ToInt32(ips[0].Split('.')[3]); 288 sip.Ip5 = 0; 289 290 tempModel.ServerIPs.Add(sip); 291 } 292 //CR#1796870 End 293 294 tempModel.Title = (string)(results["Title"]); 295 296 if (results["NotificationList"] == DBNull.Value) 297 { 298 tempModel.NotificationList = string.Empty; 299 } 300 else 301 { 302 tempModel.NotificationList = (string)(results["NotificationList"]); 303 } 304 305 tempModel.RequestStatus = (string)results["RequestStatus"]; 306 //CR#1796870 modify by v-yangwu, if scantype is Extranet Scan, Project Information need to be show. 307 if (scantype == "0") 308 { 309 tempModel.PitId = (string)(results["PITID"].ToString()); 310 tempModel.SraId = (string)(results["SRAID"].ToString()); 311 tempModel.SdlTrackId = (string)(results["SDLTrackID"].ToString()); 312 tempModel.EsdlId = (string)(results["ESDID"].ToString()); 313 tempModel.MsAppId = (string)(results["MSAppID"].ToString()); 314 } 315 //CR#1796870 End 316 tempModel.RequestorAlias = (string)(results["Requestor"]); 317 tempModel.Agreement = true; 318 return tempModel; 319 } 320 } 321 } 322 } 323 else 324 { 325 using (SqlCommand command = new SqlCommand("Q6.GetRequestDataById", connection)) 326 { 327 command.CommandType = CommandType.StoredProcedure; 328 command.Parameters.AddWithValue("RequestID", Id); 329 command.Parameters.AddWithValue("Alias", Alias); 330 command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output; 331 connection.Open(); 332 333 using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default)) 334 { 335 while (results.Read()) 336 { 337 ScanRequestModel tempModel = new ScanRequestModel(); 338 tempModel.ScanRequestId = Convert.ToInt32(results["RequestID"], CultureInfo.InvariantCulture); 339 tempCompleteIp = (string)(results["IP"]); 340 341 //CR#1796870 modify by v-yangwu, add scantype to model 342 scantype = (string)results["ScanType"]; 343 tempModel.ScanType = scantype; 344 345 //CR#1796870 Start modify by v-yangwu, parsing the ip string from DB 346 string[] ips; 347 ips = tempCompleteIp.Split(','); 348 int ipsAccount = ips.Count(); 349 //if there are more than 1 ip 350 if (ipsAccount > 1) 351 { 352 int nextIP4 = 0; 353 int count = 0; 354 // 355 bool islast = false; 356 for (int i = 0; i < ipsAccount; i++) 357 { 358 if (i + 1 != ips.Count()) 359 { 360 if (ips[i].Split('.')[0] == ips[i + 1].Split('.')[0] && ips[i].Split('.')[1] == ips[i + 1].Split('.')[1] && ips[i].Split('.')[2] == ips[i + 1].Split('.')[2]) 361 { 362 if (Convert.ToInt32(ips[i].Split('.')[3]) + 1 ==Convert.ToInt32( ips[i + 1].Split('.')[3])) 363 { 364 count++; 365 nextIP4 = Convert.ToInt32(ips[i - (count - 1)].Split('.')[3]); 366 islast = false; 367 } 368 else 369 { 370 //judge if there is one ip in one row. 371 if (count > 0) 372 { 373 ServerIPsModel sip = new ServerIPsModel(); 374 375 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 376 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 377 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 378 sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[3]); 379 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 380 381 tempModel.ServerIPs.Add(sip); 382 383 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 384 count = 0; 385 islast = true; 386 } 387 else 388 { 389 ServerIPsModel sip = new ServerIPsModel(); 390 391 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 392 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 393 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 394 sip.Ip4 = Convert.ToInt32(ips[i - (count)].Split('.')[3]); 395 sip.Ip5 = 0; 396 397 tempModel.ServerIPs.Add(sip); 398 399 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 400 count = 0; 401 islast = false; 402 } 403 } 404 } 405 else 406 { 407 ServerIPsModel sip = new ServerIPsModel(); 408 409 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 410 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 411 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 412 if (count > 0) 413 { 414 sip.Ip4 = nextIP4; 415 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 416 417 } 418 else 419 { 420 sip.Ip4 = Convert.ToInt32(ips[i].Split('.')[3]); 421 sip.Ip5 = 0; 422 } 423 424 tempModel.ServerIPs.Add(sip); 425 426 nextIP4 = Convert.ToInt32(ips[i + 1].Split('.')[3]); 427 islast = false; 428 //Copy18 429 count = 0; 430 } 431 } 432 else 433 { 434 ServerIPsModel sip = new ServerIPsModel(); 435 436 sip.Ip1 = Convert.ToInt32(ips[i].Split('.')[0]); 437 sip.Ip2 = Convert.ToInt32(ips[i].Split('.')[1]); 438 sip.Ip3 = Convert.ToInt32(ips[i].Split('.')[2]); 439 sip.Ip4 = nextIP4; 440 if (islast || count <= 0) 441 { 442 sip.Ip5 = 0; 443 } 444 else 445 { 446 sip.Ip5 = Convert.ToInt32(ips[i].Split('.')[3]); 447 } 448 449 tempModel.ServerIPs.Add(sip); 450 } 451 } 452 } 453 else 454 { 455 ServerIPsModel sip = new ServerIPsModel(); 456 457 sip.Ip1 = Convert.ToInt32(ips[0].Split('.')[0]); 458 sip.Ip2 = Convert.ToInt32(ips[0].Split('.')[1]); 459 sip.Ip3 = Convert.ToInt32(ips[0].Split('.')[2]); 460 sip.Ip4 = Convert.ToInt32(ips[0].Split('.')[3]); 461 sip.Ip5 = 0; 462 463 tempModel.ServerIPs.Add(sip); 464 } 465 //CR#1796870 End 466 467 tempModel.Title = (string)(results["Title"]); 468 469 if (results["NotificationList"] == DBNull.Value) 470 { 471 tempModel.NotificationList = string.Empty; 472 } 473 else 474 { 475 tempModel.NotificationList = (string)(results["NotificationList"]); 476 } 477 478 tempModel.RequestStatus = (string)results["RequestStatus"]; 479 //CR#1796870 modify by v-yangwu, if scantype is Extranet Scan, Project Information need to be show. 480 if (scantype == "0") 481 { 482 tempModel.PitId = (string)(results["PITID"].ToString()); 483 tempModel.SraId = (string)(results["SRAID"].ToString()); 484 tempModel.SdlTrackId = (string)(results["SDLTrackID"].ToString()); 485 tempModel.EsdlId = (string)(results["ESDID"].ToString()); 486 tempModel.MsAppId = (string)(results["MSAppID"].ToString()); 487 } 488 //CR#1796870 End 489 tempModel.RequestorAlias = (string)(results["Requestor"]); 490 tempModel.Agreement = true; 491 return tempModel; 492 } 493 } 494 } 495 } 496 497 498 499 return new ScanRequestModel(); 500 } 501 502 public string UpdateRequestToPending(int requestId) 503 { 504 using (SqlConnection connection = this.CreateDatabaseConnection()) 505 { 506 using (SqlCommand command = new SqlCommand("dbo.UpdateRequestToPending", connection)) 507 { 508 string result = string.Empty; 509 command.CommandType = CommandType.StoredProcedure; 510 511 command.Parameters.AddWithValue("RequestId", requestId); 512 SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar); 513 param.Direction = ParameterDirection.Output; 514 param.Size = 100; 515 command.Parameters.Add(param); 516 517 connection.Open(); 518 command.ExecuteNonQuery(); 519 520 result = param.Value.ToString(); 521 return result; 522 } 523 } 524 } 525 526 public string UpdateNotificationListonOnRequest(int requestId, string[] NotificationList, string requestorAlias) 527 { 528 using (DataTable tableNotificationList = new DataTable("NotificationList")) 529 { 530 tableNotificationList.Locale = CultureInfo.InvariantCulture; 531 tableNotificationList.Columns.Add("NotificationListID", typeof(int)); 532 tableNotificationList.Columns.Add("RequestID", typeof(int)); 533 tableNotificationList.Columns.Add("Alias", typeof(string)); 534 535 if (NotificationList != null) 536 { 537 foreach (string alias in NotificationList) 538 { 539 if (alias != requestorAlias) 540 { 541 tableNotificationList.Rows.Add(null, null, alias.Trim()); 542 } 543 } 544 } 545 546 using (SqlConnection connection = this.CreateDatabaseConnection()) 547 { 548 using (SqlCommand command = new SqlCommand("dbo.UpdateNotificationListonOnRequest", connection)) 549 { 550 string result = string.Empty; 551 command.CommandType = CommandType.StoredProcedure; 552 553 command.Parameters.AddWithValue("RequestId", requestId); 554 command.Parameters.AddWithValue("NotificationList", tableNotificationList); 555 SqlParameter param = new SqlParameter("@ErrorMessage", SqlDbType.VarChar); 556 param.Direction = ParameterDirection.Output; 557 param.Size = 100; 558 command.Parameters.Add(param); 559 560 connection.Open(); 561 command.ExecuteNonQuery(); 562 563 result = param.Value.ToString(); 564 return result; 565 } 566 } 567 } 568 } 569 public bool isDateCreatedValid(string Ip) 570 { 571 int InvalidAmount = 0; 572 using (SqlConnection connection = this.CreateDatabaseConnection()) 573 using (SqlCommand command = new SqlCommand("Q6.isDateCreatedValid", connection)) 574 { 575 command.CommandType = CommandType.StoredProcedure; 576 command.Parameters.AddWithValue("Ip", Ip); 577 command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output; 578 connection.Open(); 579 580 using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default)) 581 { 582 while (results.Read()) 583 { 584 if (results["InvalidAmount"] != DBNull.Value) 585 { 586 InvalidAmount = Convert.ToInt32(results["InvalidAmount"], CultureInfo.InvariantCulture); 587 } 588 else 589 { 590 InvalidAmount = 0; 591 } 592 } 593 } 594 } 595 if (InvalidAmount > 0) 596 { 597 return false; 598 } 599 else 600 { 601 return true; 602 } 603 } 604 605 606 public string GetConfigurationByName(string configurationName) 607 { 608 string configurationValue = string.Empty; 609 using (SqlConnection connection = this.CreateDatabaseConnection()) 610 using (SqlCommand command = new SqlCommand("Q6.GetConfigurationByName", connection)) 611 { 612 command.CommandType = CommandType.StoredProcedure; 613 command.Parameters.AddWithValue("ConfigurationName", configurationName); 614 command.Parameters.Add("@ErrorMessage", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output; 615 connection.Open(); 616 617 using (SqlDataReader results = command.ExecuteReader(CommandBehavior.Default)) 618 { 619 while (results.Read()) 620 { 621 configurationValue = (string)results["ConfigValue"]; 622 623 return configurationValue; 624 } 625 } 626 } 627 628 return configurationValue; 629 } 630 } 631 } ScanNowRepository

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

 

 

转载于:https://www.cnblogs.com/zzuIvy/p/jQueryInMvc4Project.html


最新回复(0)