text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
@model SmartAdmin.WebUI.Data.Models.ApplicationUser @{ /**/ ViewData["Title"] = "登录账号"; ViewData["PageName"] = "accountmanage_index"; ViewData["Heading"] = "<i class='fal fa-users text-primary'></i> 登录账号"; ViewData["Category1"] = "系统管理"; ViewData["PageDescription"] = ""; } @section HeadBlock { <link href="~/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css" rel="stylesheet" asp-append-version="true" /> <link href="~/js/easyui/themes/insdep/easyui.css" rel="stylesheet" asp-append-version="true" /> <link href="~/css/formplugins/cropperjs/cropper.css" rel="stylesheet" asp-append-version="true" /> <style> .overlay { position: absolute; bottom: 10px; left: 0; right: 0; background-color: rgba(255, 255, 255, 0.5); overflow: hidden; height: 0; transition: .5s ease; width: 100%; } .avatars:hover .overlay { height: 50%; cursor: pointer; } .avatars { position: relative; border-radius: 50%; } .text { color: #333; position: absolute; top: 30%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } img { display: block !important; /* This rule is very important, please don't ignore this */ max-width: 100%; } /*.img-container { min-height: 400px; margin-bottom:0px; }*/ </style> } <div class="row"> <div class="col-lg-12 col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> 登录账号 </h2> <div class="panel-toolbar"> <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button> <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button> @*<button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"><i class="fal fa-times"></i></button>*@ </div> </div> <div class="panel-container enable-loader show"> <div class="loader"><i class="fal fa-spinner-third fa-spin-4x fs-xxl"></i></div> <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0 text-muted bg-faded bg-subtlelight-fade"> <div class="row no-gutters align-items-center"> <div class="col"> <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") --> <div class="btn-group btn-group-sm "> <button name="searchbutton" onclick="reloadData()" class="btn btn-default"> <span class="fal fa-search mr-1"></span> 刷新 </button> </div> <div class="btn-group "> <button name="resetpasswordbutton" onclick="resetpassword()" class="btn btn-sm btn-primary"> <i class="fal fa-key mr-1"></i> 重置密码 </button> </div> <div class="btn-group "> <button name="lockoutbutton" onclick="setlockout()" class="btn btn-sm btn-danger"> <i class="fal fa-user-lock mr-1"></i> 禁用账号 </button> </div> <div class="btn-group "> <button name="unlockbutton" onclick="setunlockout()" class="btn btn-sm btn-success"> <i class="fal fa-unlock-alt mr-1"></i> 恢复账号 </button> </div> <div class="btn-group btn-group-sm "> <button name="registbutton" onclick="registuser()" class="btn btn-default"> <span class="fal fa-plus mr-1"></span> 注册新账号 </button> </div> <div class="btn-group btn-group-sm "> <button name="deletebutton" disabled onclick="removeusers()" class="btn btn-default"> <span class="fal fa-times mr-1"></span> 删除账号 </button> </div> <div class="btn-group btn-group-sm hidden-xs "> <button name="importbutton" type="button" onclick="importexcel('ApplicationUser')" class="btn btn-default"><span class="fal fa-cloud-upload mr-1"></span> 导入 </button> <button type="button" class="btn btn-default dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu"> <button name="downloadbutton" class="dropdown-item js-waves-on" href="javascript:downloadtemplate()"><span class="fal fa-download"></span> 下载模板 </button> </div> </div> <div class="btn-group btn-group-sm "> <button name="exportbutton" onclick="exportexcel()" class="btn btn-default"> <span class="fal fa-file-excel mr-1"></span> 导出 </button> </div> </div> </div> </div> <div class="panel-content"> <div class="table-responsive"> <table id="users_datagrid"></table> </div> </div> </div> </div> </div> </div> <partial name="_ResetPasswordPartial" /> <partial name="_RegisterFormPartial" /> <!-- END MAIN CONTENT --> @section ScriptsBlock { <script src="~/js/dependency/moment/moment.js" asp-append-version="true"></script> <script src="~/js/dependency/numeral/numeral.min.js" asp-append-version="true"></script> <script src="~/js/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js" asp-append-version="true"></script> <script src="~/js/easyui/jquery.easyui.min.js" asp-append-version="true"></script> <script src="~/js/easyui/plugins/datagrid-filter.js" asp-append-version="true"></script> <script src="~/js/easyui/plugins/columns-ext.js" asp-append-version="true"></script> <script src="~/js/easyui/plugins/columns-reset.js" asp-append-version="true"></script> <script src="~/js/easyui/locale/easyui-lang-zh_CN.js" asp-append-version="true"></script> <script src="~/js/easyui/jquery.easyui.component.js" asp-append-version="true"></script> <script src="~/js/jquery.extend.formatter.js" asp-append-version="true"></script> <script src="~/js/jquery.custom.extend.js" asp-append-version="true"></script> <script src="~/js/plugin/jquery.serializejson/jquery.serializejson.js" asp-append-version="true"></script> <script src="~/js/formplugins/cropperjs/cropper.js" asp-append-version="true"></script> <script type="text/javascript"> //全屏事件 document.addEventListener('panel.onfullscreen', () => { $dg.treegrid('resize'); }); //禁用账号 function setlockout() { const userid = $dg.datagrid('getChecked').map(x => x.Id); if (userid.length > 0) { $.post('/AccountManage/SetLockout', { userid: userid }).done(res => { reloadData(); }); } } function setunlockout() { const userid = $dg.datagrid('getChecked').map(x => x.Id); if (userid.length > 0) { $.post('/AccountManage/SetUnLockout', { userid: userid }).done(res => { reloadData(); }); } } //执行Excel到处下载 function exportexcel() { } function downloadtemplate() { //默认模板路径存放位置 const url = '/FileUpload/Download?file=/ExcelTemplate/Accounts.xlsx'; $.fileDownload(url) .done(() => { //console.log('file download a success!'); toastr.success('模板下载完成!'); }) .fail(() => { $.messager.alert('下载模板失败', '没有下载到导入模板[Accounts.xlsx]文件!', 'error'); }); } //显示帮助信息 function resetpassword() { var row = $dg.datagrid('getChecked'); if (row.length === 0) { $.messager.alert("提示", "请选中需要重置密码的记录!"); } else { //console.log(row); showresetform(row[0].Id, row[0].UserName); } } function reloadData() { $dg.datagrid('unselectAll'); $dg.datagrid('uncheckAll'); $dg.datagrid('reload'); } var $dg = $('#users_datagrid'); function edituser(user) { showedituserform(user) } function registuser() { showregisterform(); } function removeusers() { const rows = $dg.datagrid('getChecked'); if (rows.length > 0) { var id = rows.filter(item => item.Id != null).map(item => { return item.Id; }); $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${id.length}</span> 个账号?`, result => { if (result) { $.post('/AccountManage/DeleteCheckedUser', { id: id }) .done(response => { if (response.success) { toastr.success('删除成功', '确认', { timeOut: 2000 }); $dg.datagrid('uncheckAll'); $dg.datagrid('reload'); } else { $.messager.alert('错误', response.err, 'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); $.messager.alert('失败', errorThrown, 'error'); }); } }); } else { $.messager.alert('提示', '请选择要删除的账号'); } } $(function () { $dg.datagrid({ rownumbers: true, checkOnSelect: false, selectOnCheck: false, idField: 'Id', sortName: 'Id', sortOrder: 'desc', remoteFilter: true, singleSelect: false, method: 'get', pagination: true, clientPaging: false, striped: true, height: 670, pageSize: 15, pageList: [15, 20, 50, 100, 500, 2000], onDblClickRow: function (index, row) { edituser(row); }, onBeforeLoad: function () { $('.enable-loader').removeClass('enable-loader') }, onLoadSuccess: function (data) { editIndex = undefined; $("button[name*='deletebutton']").prop('disabled', true); }, onSelect: function (index, row) { menuitem = row; }, onCheck: function (index,row) { $("button[name*='deletebutton']").prop('disabled', false); menuitem = row; }, onUncheck: function () { const checked = $(this).datagrid('getChecked').length > 0; $("button[name*='deletebutton']").prop('disabled', !checked); }, onCheck: function () { $("button[name*='deletebutton']").prop('disabled', false); }, onBeforeEdit: function (index, row) { row.editing = true; $(this).datagrid('refreshRow', index); }, onCancelEdit: function (index, row) { row.editing = false; editIndex = undefined; $(this).datagrid('refreshRow', index); }, columns: [[ { field: 'ck', checkbox: true }, { field: 'status', title: '状态', width: 80, align: 'center', formatter: function (v, r, i) { if (r.LockoutEnd == null) { return '<span class="badge badge-info">正常</span>' } else { if (moment(r.LockoutEnd) > moment()) { return '<span class="badge badge-danger">锁定</span>' } else { return '<span class="badge badge-info">正常</span>' } } } }, { field: 'UserName', title: '账号', width: 140, editor: { type: 'textbox', options: { prompt: '账号', required: true, validType: 'length[0,128]' } }, sortable: true, resizable: true }, { field: 'GivenName', title: '昵称', width: 140, editor: { type: 'textbox', options: { prompt: '昵称', required: true, validType: 'length[0,128]' } }, sortable: true, resizable: true }, { field: 'Email', title: '电子邮件', width: 240, editor: { type: 'textbox', options: { prompt: '电子邮件', required: true, validType: 'email' } }, sortable: true, resizable: true }, { field: 'PhoneNumber', title: '电话号码', width: 140, editor: { type: 'textbox', options: { prompt: '电话号码', required: false, validType: 'length[0,128]' } }, sortable: true, resizable: true }, { field: 'TenantId', title: '@Html.DisplayNameFor(model => model.TenantId)', width: 160, formatter: function (value, row, index) { return row.TenantName } }, { field: 'IsOnline', title: '是否在线', width: 90, sortable: true, resizable: true, formatter: booleanformatter } ]] }) .datagrid('enableFilter', [ { field: 'TenantId', type: 'combobox', options: { valueField: 'Id', panelHeight: 'auto', textField: 'Name', method: 'post', url: '/AccountManage/GetTenantData', onChange: value => { if (value === '' || value === null) { $dg.datagrid('removeFilterRule', 'TenantId'); } else { $dg.datagrid('addFilterRule', { field: 'TenantId', op: 'equal', value: value }); } $dg.datagrid('doFilter'); } } }]) .datagrid('load', '/AccountManage/GetData'); }); </script> }
the_stack
@model Sheng.WeixinConstruction.Infrastructure.CouponEntity @{ ViewBag.Title = "CouponDistribute"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } <script type="text/javascript" src="/Scripts/laydate/laydate.js"></script> <script> var _couponId = getQueryString("couponId"); var _member; var _validator_memberSearch; var _validator_distribute; $(document).ready(function () { _validator_memberSearch = $("#form").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtSearch_CardNumber": "required" }, messages: { "txtSearch_CardNumber": "请输入会员的完整会员卡号查询会员;" } }); _validator_distribute = $("#formDistribute").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtDistributeCount": { required: true, number: true, digits: true, range: [1, 100] } }, messages: { "txtDistributeCount": { required: "请输入派发张数", number: "请输入有效整数字;", digits: "请输入有效整数字;", range: "派发张数请介于 1 到 100 之间;" } } }); $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { search(); //如果不加 return false ,表单会自动 提交且会丢失URL后的参数 return false; } }); $("#txtDistributeCount").keypress(function (e) { if (e.keyCode == 13) { distribute(); return false; } }); }); function search() { if (_validator_memberSearch.form() == false) { return; } var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); var cardNumber = $("#txtSearch_CardNumber").val(); $.ajax({ url: "/Api/Member/GetMemberByCardNumber?cardNumber=" + cardNumber, type: "POST", dataType: "json", success: function (data, status, jqXHR) { // alert(data); layer.close(loadLayerIndex); if (data.Success) { _member = data.Data; $("#imageHead").attr("src", _member.Headimgurl_132); $("#spanNickName").html(_member.NickName); $("#spanName").html(_member.Name); $("#spanSex").html(_member.SexString); $("#spanPoint").html(_member.Point); $("#spanCashAccount").html(_member.CashAccount / 100.0); $("#spanCity").html(_member.Country + " " + _member.Province + " " + _member.City); $("#spanMobilePhone").html(_member.MobilePhone); $("#spanEmail").html(_member.Email); $("#spanSubscribeTime").html(_member.SubscribeTime); $("#divMemberInfo").show(); $("#divMessage").hide(); } else { _member = null; $("#divMemberInfo").hide(); $("#divMessage").show(); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); // alert("Error: " + xmlHttpRequest.status); } }); } function distribute() { if (_member == null) { layerAlert("请先查询会员后再执行派发。"); return; } if (_validator_distribute.form() == false) { return; } var count = $("#txtDistributeCount").val(); var msg = "是否确认向会员 " + _member.NickName + " 派发 [@Model.Name] " + count + " 张?" var confirmLayerIndex = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 shade: [0.4, '#393D49'], title: false, closeBtn: false, shift: _layerShift }, function () { layer.close(confirmLayerIndex); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); var args = new Object(); args.CouponId = _couponId; args.MemberId = _member.Id; args.LimitedTime = $("#txtLimitedTime").val(); args.Count = count; $.ajax({ url: "/Api/Coupon/Distribute", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { switch (data.Data.Reason) { case 0: layerAlert("派发成功!", loadDataAndCloseLayer); break; case 1: layerAlert("无权限。"); break; case 2: layerAlert("库存不足。"); break; case 3: layerAlert("卡券已删除。"); break; case 4: layerAlert("卡券不存在。"); break; case 5: layerAlert("派发张数无效。"); break; default: layerAlert("未知错误:" + data.Data.Reason); break; } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); }); } function loadDataAndCloseLayer() { var index = parent.layer.getFrameIndex(window.name); parent.loadDataAndCloseLayer(index); } function cancel() { var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 parent.layer.close(index); //再执行关闭 } </script> <div style="margin-left:20px; margin-right:20px; margin-top:20px;"> <span id="spanTitle" class="font_black_24">派发</span> </div> <div style=" background-color:#ccc; margin-left:20px; margin-right:20px; margin-top:10px; height:1px;"> </div> <div style=" position:absolute; overflow:auto ;margin-top:25px;left:30px; right:30px; bottom:60px; top:50px; "> <form id="form"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">会员卡号:</td> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><input id="txtSearch_CardNumber" name="txtSearch_CardNumber" type="text" class="input_16" style="width:100%; " keyenter /></td> <td align="right" width="90"><input name="btnSearch" type="button" class="btn_white" id="btnSearch" value="查询" onclick="search()" /></td> </tr> </table> </td> </tr> </table> </form> <div id="divMessage" style="margin-top:20px;"> 请输入会员的完整会员卡号查询会员。 </div> <div id="divMemberInfo" style="margin-top:10px;display:none"> <div> <form id="formDistribute"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">派发张数:</td> <td width="130"><input id="txtDistributeCount" name="txtDistributeCount" type="text" class="input_16" style="width:100px; " /></td> <td width="90">有效期:</td> <td width="110"><input id="txtLimitedTime" class="input_16" onclick="laydate({format: 'YYYY-MM-DD'})" /></td> <td><input name="btnDistribute" type="button" class="btn_green" id="btnDistribute" value="派 发" style="margin-left:10px;" onclick="distribute()" /></td> </tr> <tr> <td width="110" height="36"></td> <td colspan="4" class="font_gray_13">有效期留空表示永久有效,有效期当天仍然有效,次日过期;<br/>请注意核对会员信息,派发后不可撤销。</td> </tr> </table> </form> </div> <div class="divDotLine" style="margin-top:10px;margin-bottom:10px;"></div> <div style="background-color:lightgray;width:132px;height:132px;float:right"> <img id="imageHead" /> </div> <div style="float:left"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">微信昵称:</td> <td> <span id="spanNickName"></span> </td> </tr> <tr> <td height="36">姓名:</td> <td> <span id="spanName"></span> </td> </tr> <tr> <td height="36">性别:</td> <td> <span id="spanSex"></span> </td> </tr> <tr> <td height="36">积分:</td> <td> <span id="spanPoint"></span> </td> </tr> <tr> <td height="36">现金余额:</td> <td> <span id="spanCashAccount"></span> </td> </tr> <tr> <td height="36">城市:</td> <td> <span id="spanCity"></span> </td> </tr> <tr> <td height="36">手机号码:</td> <td> <span id="spanMobilePhone"></span> </td> </tr> <tr> <td height="36">电子邮箱:</td> <td> <span id="spanEmail"></span> </td> </tr> <tr> <td height="36">关注时间:</td> <td> <span id="spanSubscribeTime"></span> </td> </tr> </table> </div> <div style="clear:both"></div> </div> </div> <div style=" background-color:#ccc; position:absolute; bottom:55px; left:20px;right:20px; height:1px;"> </div> <div style="position:absolute; bottom:15px; left:20px;right:20px;"> @*<div style="float:left;"> <form id="formDistribute"> 派发张数: <input id="txtDistributeCount" name="txtDistributeCount" type="text" class="input_16" style="width:100px; " /> <input name="btnDistribute" type="button" class="btn_green" id="btnDistribute" value="派 发" onclick="distribute()" /> </form> </div>*@ <div style="float:right"> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" /> </div> <div style="clear:both"> </div> </div>
the_stack
////////////////////////////////////////////////////////////////////////////// public static void AssertFiles(this FilePathCollection collection, params FilePath[] files) { Assert.NotNull(collection); Assert.Equal(files.Length, collection.Count); foreach(var file in files) { Assert.True(collection.Contains(file, PathComparer.Default), $"Expected '{file}' to be found by globber."); } } public static void AssertDirectories(this DirectoryPathCollection collection, params DirectoryPath[] directories) { Assert.NotNull(collection); Assert.Equal(directories.Length, collection.Count); foreach(var directory in directories) { Assert.True(collection.Contains(directory, PathComparer.Default), $"Expected '{directory}' to be found by globber."); } } public static void AssertPaths(this PathCollection collection, params Cake.Core.IO.Path[] paths) { Assert.NotNull(collection); Assert.Equal(paths.Length, collection.Count); foreach(var path in paths) { Assert.True(collection.Contains(path, PathComparer.Default), $"Expected '{path}' to be found by globber."); } } ////////////////////////////////////////////////////////////////////////////// Task("Cake.Common.IO.GlobbingAliases.GetFiles.Wildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/wildcard"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa.txt")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao.txt")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau.txt")); // When var files = GetFiles($"{root}/*"); // Then files.AssertFiles(foobaa, foobao, foobau); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.Wildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/wildcard"); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var directories = GetDirectories($"{root}/*"); // Then directories.AssertDirectories(foobar, foobaz, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.Wildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/wildcard"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa.txt")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao.txt")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau.txt")); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var paths = GetPaths($"{root}/*"); // Then paths.AssertPaths(foobaa, foobao, foobau, foobar, foobaz, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetFiles.RecursiveWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/recursivewildcard"); var first = EnsureFileExist(root.CombineWithFilePath("foo/bar/qux.txt")); var second = EnsureFileExist(root.CombineWithFilePath("bar/qux.txt")); var third = EnsureFileExist(root.CombineWithFilePath("bar/foo/baz.txt")); // When var files = GetFiles($"{root}/**/qux.txt"); // Then files.AssertFiles(first, second); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.RecursiveWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/recursivewildcard"); var first = EnsureDirectoryExist(root.Combine("foo/bar/qux")); var second = EnsureDirectoryExist(root.Combine("bar/qux")); var third = EnsureDirectoryExist(root.Combine("bar/foo/baz")); // When var files = GetDirectories($"{root}/**/qux"); // Then files.AssertDirectories(first, second); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.RecursiveWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/recursivewildcard"); var firstf = EnsureFileExist(root.CombineWithFilePath("foo/boo/qux")); var secondf = EnsureFileExist(root.CombineWithFilePath("boo/qux")); var thirdf = EnsureFileExist(root.CombineWithFilePath("boo/foo/baz")); var firstd = EnsureDirectoryExist(root.Combine("foo/bar/qux")); var secondd = EnsureDirectoryExist(root.Combine("bar/qux")); var thirdd = EnsureDirectoryExist(root.Combine("bar/foo/baz")); // When var paths = GetPaths($"{root}/**/qux"); // Then paths.AssertPaths(firstf, secondf, firstd, secondd); }); Task("Cake.Common.IO.GlobbingAliases.GetFiles.CharacterWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/characterwildcard"); var foobar = EnsureFileExist(root.CombineWithFilePath("foobar.txt")); var foobaz = EnsureFileExist(root.CombineWithFilePath("foobaz.txt")); var foobax = EnsureFileExist(root.CombineWithFilePath("foobax.txt")); // When var files = GetFiles($"{root}/fooba?.txt"); // Then files.AssertFiles(foobar, foobaz, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.CharacterWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/characterwildcard"); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var files = GetDirectories($"{root}/fooba?"); // Then files.AssertDirectories(foobar, foobaz, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.CharacterWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/characterwildcard"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau")); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var paths = GetPaths($"{root}/fooba?"); // Then paths.AssertPaths(foobaa, foobao, foobau, foobar, foobaz, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetFiles.BracketWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/bracketwildcard"); var foobar = EnsureFileExist(root.CombineWithFilePath("foobar.txt")); var foobaz = EnsureFileExist(root.CombineWithFilePath("foobaz.txt")); var foobax = EnsureFileExist(root.CombineWithFilePath("foobax.txt")); // When var files = GetFiles($"{root}/fooba[rz].txt"); // Then files.AssertFiles(foobar, foobaz); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.BracketWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/bracketwildcard"); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var files = GetDirectories($"{root}/fooba[rz]"); // Then files.AssertDirectories(foobar, foobaz); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.BracketWildcard") .Does(context => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/bracketwildcard"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau")); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var paths = GetPaths($"{root}/fooba[aorz]"); // Then paths.AssertPaths(foobaa, foobao, foobar, foobaz); }); Task("Cake.Common.IO.GlobbingAliases.GetFiles.BraceExpansion") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansion"); var foobar = EnsureFileExist(root.CombineWithFilePath("foobar.txt")); var foobaz = EnsureFileExist(root.CombineWithFilePath("foobaz.txt")); var foobax = EnsureFileExist(root.CombineWithFilePath("foobax.txt")); // When var files = GetFiles($"{root}/foo{{bar,bax}}.txt"); // Then files.AssertFiles(foobar, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.BraceExpansion") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansion"); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var files = GetDirectories($"{root}/foo{{bar,bax}}"); // Then files.AssertDirectories(foobar, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.BraceExpansion") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansion"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau")); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var paths = GetPaths($"{root}/foo{{baa,bau,bar,bax}}"); // Then paths.AssertPaths(foobaa, foobau, foobar, foobax); }); Task("Cake.Common.IO.GlobbingAliases.GetFiles.BraceExpansionNegation") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansionnegation"); var foobar = EnsureFileExist(root.CombineWithFilePath("foobar.txt")); var foobaz = EnsureFileExist(root.CombineWithFilePath("foobaz.txt")); var foobax = EnsureFileExist(root.CombineWithFilePath("foobax.txt")); // When var files = GetFiles($"{root}/fooba[!x].txt"); // Then files.AssertFiles(foobar, foobaz); }); Task("Cake.Common.IO.GlobbingAliases.GetDirectories.BraceExpansionNegation") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansionnegation"); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var files = GetDirectories($"{root}/fooba[!x]"); // Then files.AssertDirectories(foobar, foobaz); }); Task("Cake.Common.IO.GlobbingAliases.GetPaths.BraceExpansionNegation") .Does(() => { // Given var root = EnsureDirectoryExist($"{Paths.Temp}/Cake.Common.IO.GlobbingAliases/braceexpansionnegation"); var foobaa = EnsureFileExist(root.CombineWithFilePath("foobaa")); var foobao = EnsureFileExist(root.CombineWithFilePath("foobao")); var foobau = EnsureFileExist(root.CombineWithFilePath("foobau")); var foobar = EnsureDirectoryExist(root.Combine("foobar")); var foobaz = EnsureDirectoryExist(root.Combine("foobaz")); var foobax = EnsureDirectoryExist(root.Combine("foobax")); // When var paths = GetPaths($"{root}/fooba[!ux]"); // Then paths.AssertPaths(foobaa, foobao, foobar, foobaz); }); ////////////////////////////////////////////////////////////////////////////// Task("Cake.Common.IO.GlobbingAliases") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.Wildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.Wildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.Wildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.RecursiveWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.RecursiveWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.RecursiveWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.CharacterWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.CharacterWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.CharacterWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.BracketWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.BracketWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.BracketWildcard") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.BraceExpansion") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.BraceExpansion") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.BraceExpansion") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetFiles.BraceExpansionNegation") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetDirectories.BraceExpansionNegation") .IsDependentOn("Cake.Common.IO.GlobbingAliases.GetPaths.BraceExpansionNegation");
the_stack
@model WebApp.Models.OrderDetail <script type="text/javascript"> //是否开启行内编辑 const SUBEDITINLINE = false; //初始化 OrderDetail datagrid var $orderdetailsdg = $('#orderdetails_datagrid'); //当前行记录 var orderdetail = {}; //datagrid CRUD method var orderdetails_editIndex = undefined; //取消 function orderdetails_reject() { $orderdetailsdg.datagrid('rejectChanges'); orderdetails_editIndex = undefined; } //重新加载数据 function orderdetails_reload() { if (orderdetails_endEditing()) { $orderdetailsdg.datagrid('reload'); } } //关闭编辑状态 function orderdetails_endEditing() { if (orderdetails_editIndex === undefined) { return true; } if ($orderdetailsdg.datagrid('validateRow', orderdetails_editIndex)) { $orderdetailsdg.datagrid('endEdit', orderdetails_editIndex); orderdetails_editIndex = undefined; return true; } else { const invalidinput = $('input.validatebox-invalid'); const fieldnames = invalidinput.map((index, item) => { return $(item).attr('placeholder') || $(item).attr('id'); }); $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error'); return false; } } //单击列开启编辑功能 function orderdetails_onClickCell(index, field) { var _operates = ['_operate1', 'ck']; if (!SUBEDITINLINE || $.inArray(field, _operates) >= 0) { return false; } if (orderdetails_editIndex !== index) { if (orderdetails_endEditing()) { $orderdetailsdg.datagrid('selectRow', index) .datagrid('beginEdit', index); orderdetails_editIndex = index; var ed = $orderdetailsdg.datagrid('getEditor', { index: index, field: field }); if (ed) { ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus(); } } else { $orderdetailsdg.datagrid('selectRow', orderdetails_editIndex); } } } //双击弹出编辑当前行对话框 function orderdetails_onDblClickRow(index, row) { if (!SUBEDITINLINE) { open_orderdetaildlg(index, row, 'Modified'); } } //订阅对话框新增返回事件 $(document).on('orderdetail_form.add', (e, index,item) => { $orderdetailsdg.datagrid("insertRow", { index: 0, row: item }); }); //订阅对话框修改返回事件 $(document).on('orderdetail_form.edit', (e,index, item) => { $orderdetailsdg.datagrid('updateRow', { index: index, row: item }); }); //新增记录 function orderdetails_append() { if (!SUBEDITINLINE) { var item = { Qty: 1, OrderId:orderid }; open_orderdetaildlg(0, item, 'Added'); } else { if (orderdetails_endEditing()) { //对必填字段进行默认值初始化 $orderdetailsdg.datagrid('insertRow', { index: 0, row: { Qty: 1, OrderId:orderid } }); orderdetails_editIndex = 0; $orderdetailsdg.datagrid('selectRow', orderdetails_editIndex) .datagrid('beginEdit', orderdetails_editIndex); } } } //删除编辑的行 function orderdetails_removeit() { if (orderdetails_editIndex !== undefined) { $orderdetailsdg.datagrid('cancelEdit', orderdetails_editIndex) .datagrid('deleteRow', orderdetails_editIndex); orderdetails_editIndex = undefined; } else { var row = $orderdetailsdg.datagrid('getSelected'); if(row){ var rowindex = $orderdetailsdg.datagrid('getRowIndex', row); $orderdetailsdg.datagrid('deleteRow', rowindex); }else{ $.messager.alert('提示', '没有选中删除的记录.', 'info'); } } } //删除选中的行 function orderdetails_deletechecked() { var rows = $orderdetailsdg.datagrid('getChecked'); if (rows.length > 0) { var id = rows.map(item => { return item.Id; }); $.messager.confirm('确认', `你确定要删除这 <span class='badge bg-color-red'>${id.length}</span> 行记录?`,result => { if (result) { $.post('/OrderDetails/DeleteCheckedAsync', { id: id }) .done(response => { if (response.success) { $orderdetailsdg.datagrid('reload'); } else { $.messager.alert('错误', response.err,'error'); } }); } }); } else { $.messager.alert('提示', '请先选择要删除的记录!','question'); } } //提交保存后台数据库 function orderdetails_accept() { return new Promise((resolve, reject) => { if (orderdetails_endEditing()) { if (MODELSTATE === 'Modified' && $orderdetailsdg.datagrid('getChanges').length) { var inserted = $orderdetailsdg.datagrid('getChanges', 'inserted'); var deleted = $orderdetailsdg.datagrid('getChanges', 'deleted'); var updated = $orderdetailsdg.datagrid('getChanges', 'updated'); //过滤已删除的重复项 updated = updated.filter(item => { return !deleted.includes(item); }); var item = {}; if (inserted.length) { item.inserted = inserted; } if (deleted.length) { item.deleted = deleted; } if (updated.length) { item.updated = updated; } //console.log(JSON.stringify(item)); $.post('/OrderDetails/SaveDataAsync', item) .done(response => { resolve(response); //console.log(response); if (response.success) { toastr.success('保存成功', '确认', { timeOut:2000 }); $orderdetailsdg.datagrid('acceptChanges'); $orderdetailsdg.datagrid('reload'); } else { $.messager.alert('错误', response.err ,'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); resolve({ success: false, err: errorThrown }); $.messager.alert('异常', errorThrown,'error'); }); } else { resolve({ success: true }); } } else { resolve({ success: false }); } }); } $(() => { $orderdetailsdg.datagrid({ rownumbers: true, iconCls: 'fa fa-list', idField: 'Id', sortName: 'Id', sortOrder: 'asc', remoteFilter: true, singleSelect: true, checkOnSelect: false, selectOnCheck: false, method: 'get', onDblClickRow: orderdetails_onDblClickRow, onClickCell: orderdetails_onClickCell, onSelect: function(index,row) { orderdetail = row; }, onEndEdit: function (index, row) { var orderid = $(this).datagrid('getEditor', { index: index, field: 'OrderId' }); var orderorderno = $(orderid.target).combobox('getText'); row['OrderOrderNo'] = orderorderno; var productid = $(this).datagrid('getEditor', { index: index, field: 'ProductId' }); var productname = $(productid.target).combobox('getText'); row['ProductName'] = productname; }, onBeforeEdit: function (index, row) { row.editing = true; $(this).datagrid('refreshRow', index); }, onAfterEdit: function (index, row) { row.editing = false; $(this).datagrid('refreshRow', index); }, onCancelEdit: function (index, row) { row.editing = false; $(this).datagrid('refreshRow', index); }, pagination: true, striped: true, columns: [[ {field:'Id',title:'<span class="required">@Html.DisplayNameFor(model => model.Id)</span>', width:100 ,sortable:true,resizable:true, hidden:true}, { field:'ProductId', title:'<span class="required">@Html.DisplayNameFor(model => model.ProductId)</span>', width:160, sortable:true, resizable:true, formatter:function(value,row) { return row.ProductName; }, editor:{ type:'combobox', options:{ prompt:'@Html.DisplayNameFor(model => model.ProductId)' , mode: 'remote', valueField:'Id', textField:'Name', method:'get', url:'/Orders/GetProductsAsync', required:true } } }, { field:'Qty', title:'<span class="required">@Html.DisplayNameFor(model => model.Qty)</span>', width:100, align:'right', editor:{ type:'numberbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Qty)', required:true, validType:'integer' } }, sortable:true, resizable:true, formatter:intformatter }, { field:'Price', title:'<span class="required">@Html.DisplayNameFor(model => model.Price)</span>', width:100, align:'right', editor:{ type:'numberbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Price)', required:true, precision:2, validType:'decimal' } }, sortable:true, resizable:true, formatter:numberformatter }, { field:'Amount', title:'<span class="required">@Html.DisplayNameFor(model => model.Amount)</span>', width:100, align:'right', editor:{ type:'numberbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Amount)', required:true, precision:2, validType:'decimal' } }, sortable:true, resizable:true, formatter:numberformatter }, { field:'Remark', title:'@Html.DisplayNameFor(model => model.Remark)', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Remark)',required:false ,validType:'length[0,30]' } }, sortable:true, resizable:true }, { field:'OrderId', title:'<span class="required">@Html.DisplayNameFor(model => model.OrderId)</span>', width:160, sortable:true, resizable:true, formatter:function(value,row) { return row.OrderOrderNo; }, editor:{ type:'combobox', options:{ prompt:'@Html.DisplayNameFor(model => model.OrderId)' , mode: 'remote', valueField:'Id', textField:'OrderNo', method:'get', url:'/Orders/GetOrdersAsync', required:true } } }, ]] }); //初始化 datagrid filter $orderdetailsdg.datagrid('enableFilter',[ { field: 'Id', type: 'numberbox', op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: 'Qty', type: 'numberbox', op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: 'Price', type: 'numberbox', op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: 'Amount', type: 'numberbox', op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: 'ProductId', type:'combobox', options:{ valueField:'Id', textField:'Name', method:'get', url:'/Orders/GetProductsAsync', onChange: function (value) { if (value == '') { $orderdetailsdg.datagrid('removeFilterRule', 'ProductId'); } else { $orderdetailsdg.datagrid('addFilterRule', { field: 'ProductId', op: 'equal', value: value }); } $orderdetailsdg.datagrid('doFilter'); } } }, { field: 'OrderId', type:'combobox', options:{ valueField:'Id', textField:'OrderNo', method:'get', url:'/Orders/GetOrdersAsync', onChange: function (value) { if (value == '') { $orderdetailsdg.datagrid('removeFilterRule', 'OrderId'); } else { $orderdetailsdg.datagrid('addFilterRule', { field: 'OrderId', op: 'equal', value: value }); } $orderdetailsdg.datagrid('doFilter'); } } }, ]); }); </script>
the_stack
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <style> body,ul,ol,li,p,h1,h2,h3,h4,h5,h6,form,fieldset,table,td,img,div{margin:0;padding:0;border:0;} ul,ol{list-style-type:none;} select,input,img,select{vertical-align:middle;} input{ font-size:12px;} .clear{clear:both;} /* 大转盘样式 */ .banner{display:block;width:79%;margin-left:auto;margin-right:auto;margin-bottom: 20px;} .banner .turnplate{display:block;width:100%;position:relative;} .banner .turnplate canvas.item{width:100%;} .banner .turnplate img.pointer{position:absolute;width:31.5%;height:42.5%;left:34.1%;top:23%;} #sbtn{ position: absolute;top: 85%;text-align: center;width: 100%; } #sbtn img{ width: 24%;margin: 0 20px; } .container {margin: 0 auto;} .content {position: absolute;width: 100%;height: auto;margin: 0px auto;margin-top: 58%;} </style> </head> <body> <img src="/src/wx/images/game-bg.jpg" alt="" style="position: absolute;width: 100%;height: 100%;"> <div class="content" style="margin-top: 58%;"> <img src="/src/wx/images/8.png" id="fen-img" style="display:none;" /> <img src="/src/wx/images/6.png" id="zuliao-img" style="display:none;" /> <img src="/src/wx/images/3.png" id="baowen-img" style="display:none;" /> <img src="/src/wx/images/5.png" id="yundou-img" style="display:none;" /> <img src="/src/wx/images/7.png" id="ganlan-img" style="display:none;" /> <img src="/src/wx/images/4.png" id="yusan-img" style="display:none;" /> <div class="banner"> <div class="turnplate" style="background-image:url(/src/wx/images/turnplate-bg.png);background-size:100% 100%;"> <canvas class="item" id="wheelcanvas" width="422px" height="422px"></canvas> <img class="pointer" src="/src/wx/images/turnplate-pointer.png"> </div> </div> </div> <div id="sbtn"> <a href="#"><img src="/src/wx/images/btn-rule.png" alt=""></a> <a href="#"><img src="/src/wx/images/btn-zjcx.png" alt=""></a> </div> <script src="/ui/js/jquery.min.js"></script> <script src="~/src/wx/awardRotate.js"></script> <script> var turnplate = { restaraunts: [], //大转盘奖品名称 colors: [], //大转盘奖品区块对应背景颜色 outsideRadius: 192, //大转盘外圆的半径 textRadius: 155, //大转盘奖品位置距离圆心的距离 insideRadius: 68, //大转盘内圆的半径 startAngle: 0, //开始角度 bRotate: false //false:停止;ture:旋转 }; $(document).ready(function () { //动态添加大转盘的奖品与奖品区域背景颜色 turnplate.restaraunts = ["20积分", "足疗机", "20积分", "保温杯", "20积分", "手持式电熨斗", "20积分 ", "橄榄油", "20积分", "晴雨伞"]; turnplate.colors = ["#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF"]; var rotateTimeOut = function () { $('#wheelcanvas').rotate({ angle: 0, animateTo: 2160, duration: 8000, callback: function () { alert('网络超时,请检查您的网络设置!'); } }); }; //旋转转盘 item:奖品位置; txt:提示语; var rotateFn = function (item, txt) { var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length * 2)); if (angles < 270) { angles = 270 - angles; } else { angles = 360 - angles + 270; } $('#wheelcanvas').stopRotate(); $('#wheelcanvas').rotate({ angle: 0, animateTo: angles + 1800, duration: 8000, callback: function () { //中奖提示 alert(txt); turnplate.bRotate = !turnplate.bRotate; } }); }; $('.pointer').click(function () { if (turnplate.bRotate) return; turnplate.bRotate = !turnplate.bRotate; //获取随机数(奖品个数范围内) var item = rnd(1, turnplate.restaraunts.length); //奖品数量等于10,指针落在对应奖品区域的中心角度[252, 216, 180, 144, 108, 72, 36, 360, 324, 288] rotateFn(item, turnplate.restaraunts[item - 1]); // switch (item) { // case 1: // rotateFn(252, turnplate.restaraunts[0]); // break; // case 2: // rotateFn(216, turnplate.restaraunts[1]); // break; // case 3: // rotateFn(180, turnplate.restaraunts[2]); // break; // case 4: // rotateFn(144, turnplate.restaraunts[3]); // break; // case 5: // rotateFn(108, turnplate.restaraunts[4]); // break; // case 6: // rotateFn(72, turnplate.restaraunts[5]); // break; // case 7: // rotateFn(36, turnplate.restaraunts[6]); // break; // case 8: // rotateFn(360, turnplate.restaraunts[7]); // break; // case 9: // rotateFn(324, turnplate.restaraunts[8]); // break; // case 10: // rotateFn(288, turnplate.restaraunts[9]); // break; // } console.log(item); }); }); function rnd(n, m) { n = 1;//最小随机数 m = 100;//最大随机数(概率范围最大值) //最大数数不超过最大随机数 var ransluck = [50, 60, 65, 70, 75, 80, 85, 90, 95, 100];//概率为比自己小的第一个数之间的差 var randoms = Math.floor(Math.random() * (m - n + 1) + n); if (randoms <= ransluck[0]) { var random = 1; } else if (randoms <= ransluck[1]) { var random = 2; } else if (randoms <= ransluck[2]) { var random = 3; } else if (randoms <= ransluck[3]) { var random = 4; } else if (randoms <= ransluck[4]) { var random = 5; } else if (randoms <= ransluck[5]) { var random = 6; } else if (randoms <= ransluck[6]) { var random = 7; } else if (randoms <= ransluck[7]) { var random = 8; } else if (randoms <= ransluck[8]) { var random = 9; } else if (randoms <= ransluck[9]) { var random = 10; } //alert(randoms); //alert(random); return random; } //页面所有元素加载完毕后执行drawRouletteWheel()方法对转盘进行渲染 window.onload = function () { drawRouletteWheel(); }; function drawRouletteWheel() { var canvas = document.getElementById("wheelcanvas"); if (canvas.getContext) { //根据奖品个数计算圆周角度 var arc = Math.PI / (turnplate.restaraunts.length / 2); var ctx = canvas.getContext("2d"); //在给定矩形内清空一个矩形 ctx.clearRect(0, 0, 422, 422); //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式 ctx.strokeStyle = "#FFBE04"; //font 属性设置或返回画布上文本内容的当前字体属性 ctx.font = '16px Microsoft YaHei'; for (var i = 0; i < turnplate.restaraunts.length; i++) { var angle = turnplate.startAngle + i * arc; ctx.fillStyle = turnplate.colors[i]; ctx.beginPath(); //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线(用于创建圆或部分圆) ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false); ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true); ctx.stroke(); ctx.fill(); //锁画布(为了保存之前的画布状态) ctx.save(); //----绘制奖品开始---- ctx.fillStyle = "#E5302F"; var text = turnplate.restaraunts[i]; var line_height = 17; //translate方法重新映射画布上的 (0,0) 位置 ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius); //rotate方法旋转当前的绘图 ctx.rotate(angle + arc / 2 + Math.PI / 2); /** 下面代码根据奖品类型、奖品名称长度渲染不同效果,如字体、颜色、图片效果。(具体根据实际情况改变) **/ if (text.indexOf("M") > 0) {//流量包 var texts = text.split("M"); for (var j = 0; j < texts.length; j++) { ctx.font = j == 0 ? 'bold 20px Microsoft YaHei' : '16px Microsoft YaHei'; if (j == 0) { ctx.fillText(texts[j] + "M", -ctx.measureText(texts[j] + "M").width / 2, j * line_height); } else { ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height); } } } else if (text.indexOf("M") == -1 && text.length > 6) {//奖品名称长度超过一定范围 text = text.substring(0, 6) + "||" + text.substring(6); var texts = text.split("||"); for (var j = 0; j < texts.length; j++) { ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height); } } else { //在画布上绘制填色的文本。文本的默认颜色是黑色 //measureText()方法返回包含一个对象,该对象包含以像素计的指定字体宽度 ctx.fillText(text, -ctx.measureText(text).width / 2, 0); } //添加对应图标 if (text.indexOf("分") > 0) { var img = document.getElementById("fen-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } else if (text.indexOf("足疗") >= 0) { var img = document.getElementById("zuliao-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } else if (text.indexOf("保温") >= 0) { var img = document.getElementById("baowen-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } else if (text.indexOf("电熨斗") >= 0) { var img = document.getElementById("yundou-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } else if (text.indexOf("橄榄") >= 0) { var img = document.getElementById("ganlan-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } else if (text.indexOf("雨伞") >= 0) { var img = document.getElementById("yusan-img"); img.onload = function () { ctx.drawImage(img, -15, 10); }; ctx.drawImage(img, -15, 10); } //把当前画布返回(调整)到上一个save()状态之前 ctx.restore(); //----绘制奖品结束---- } } } </script> </body> </html>
the_stack
@model Xms.Web.Models.FilterModel @{ Layout = null; } @{ DialogModel dialogModel = ViewData["DialogModel"] as DialogModel; } <!--(Modal) --> <div class="modal fade" id="filtersModal" tabindex="-1" role="dialog" aria-labelledby="filtersModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="filtersModalLabel"> <span class="glyphicon glyphicon-filter"></span> @app.T["filter_condition"] - @Model.AttributeMeta.LocalizedName </h4> </div> <div class="modal-body"> <div class="table-responsive" id="filterContainer"> <div class="form-group"> <div class="col-sm-3"> <select class="input-sm" name="conditionoperator"></select> </div> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="value" disabled="disabled" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label> <input type="radio" name="logicaloperator" value="0" data-value="and" checked /> @app.T["filter_and"] </label> <label> <input type="radio" name="logicaloperator" value="1" data-value="or" /> @app.T["filter_or"] </label> </div> </div> <div class="form-group"> <div class="col-sm-3"> <select class="input-sm" name="conditionoperator"></select> </div> <div class="col-sm-9"> <input type="text" class="form-control input-sm" name="value" disabled="disabled" /> </div> </div> <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script> <script> function digitsValue(e){ var val=$(e).val(); var check=true; var reg = new RegExp(/^\+?[1-9][0-9]*$/); if(!reg.test(val)||val==''){ if($(e).next('label[name="digitsTip"]').length<=0){ $('<label name="digitsTip">'+LOC_VALIDATION_DIGIT+'</label>').insertAfter($(e)); } check=false; } else{ $(e).next('label[name="digitsTip"]').remove(); check=true; } return check; } var LOC_FILTER_CONDITION_OPERATOR_SELECT = '@app.T["filter_condition_operator_select"]'; var LOC_VALIDATION_DIGIT = '@app.T["validation_digit"]'; var FilterDialogModel = { pageUrl: '@app.Url', callback : @dialogModel.CallBack.IfEmpty("null"), attributeName : '@Model.Field', filter : @Html.Raw(Model.Filter != null ? Model.Filter.SerializeToJson(true) : "null"), dialog : $('#filtersModal'), operators : Xms.Fetch.ConditionOperators["@Model.DataType"], datatype : "@Model.DataType", attributeMetaDatas : @Html.Raw(Model.AttributeMeta.SerializeToJson()), dialog_return: function () { var digitscheck=true; $('#filterContainer').find('input[name=value]').each(function(i,n){ if($(n).attr('data-num')==true||$(n).attr('data-num')=='true'){ digitscheck= digitsValue($(n)); if(digitscheck==false){ Xms.Web.Alert(false, LOC_VALUE_NOTVALID); return false; } } }); if(digitscheck==false){ return false; } var filter = new Xms.Fetch.FilterExpression(); $('#filterContainer').find('.form-group').each(function (i, n) { var row = $(n); var conditionoperator = Xms.Web.SelectedValue(row.find('select[name=conditionoperator]')); var logicaloperator = row.find('input[name=logicaloperator]:checked').val(); //console.log(row,conditionoperator,logicaloperator); if (conditionoperator && conditionoperator != '') { var condition = new Xms.Fetch.ConditionExpression(); condition.AttributeName = FilterDialogModel.attributeName; condition.Operator = parseInt(conditionoperator); var v = row.find('input[name=value]').attr('data-value') || row.find('input[name=value]').val(); if(v && v != '') condition.Values.push(v); filter.Conditions.push(condition); //console.log(condition); } else if (logicaloperator) { filter.FilterOperator = parseInt(logicaloperator); } }); console.log(filter); if(typeof(FilterDialogModel.callback) == 'function'){ FilterDialogModel.callback(FilterDialogModel.attributeName,filter); } Xms.Web.CloseDialog('#filtersModal'); }, bindSelected: function (result, inputid){ console.log(result,inputid); $('#' + inputid).val(result[0].name); $('#' + inputid).attr('data-value',result[0].id); }, bindMoreSelected: function (result, inputid){ var rName=''; var rId=''; for(var i=0;i<result.length;i++){ console.log(result,inputid); rName+=result[i].name; rId+=result[i].id; if(i!=result.length-1){ rName+=','; rId+=','; } } $('#' + inputid).val(rName); $('#' + inputid).attr('data-value',rId); } }; console.log(FilterDialogModel.attributeMetaDatas); $(function () { //console.log(1); FilterDialogModel.dialog.modal({ keyboard: true }); FilterDialogModel.dialog.on('hidden.bs.modal', function () { Xms.Web.CloseDialog('#filtersModal'); }); //操作符 var op = new Array(); op.push('<option data-value="" value="">--'+LOC_FILTER_CONDITION_OPERATOR_SELECT+'--</option>'); $(FilterDialogModel.operators).each(function(i, n){ op.push('<option data-value="'+n[0]+'" value="'+n[1]+'">'+n[2]+'</option>'); }); //禁用输入框 var disabledArr=['Last7Days','LastWeek','LastMonth','LastYear','LastYear','NextWeek','NextMonth','NextYear','ThisWeek','ThisMonth','ThisYear','Today','Tomorrow','Yesterday']; //显示时间控件 var showDatepicker=['Equal','NotEqual','GreaterThan','LessThan','GreaterEqual','LessEqual','OnOrAfter','OnOrBefore']; //无需查找按钮 var noFindButton=['BeginsWith','DoesNotBeginWith','EndsWith','DoesNotEndWith','Like','NotLike']; //需要下拉 多选 var moreSelect=[]; //包含和不包含 var includeNull=['NotNull','Null']; //操作符改变事件 $('#filterContainer').find('select[name=conditionoperator]').each(function(i, n){ $(n).html(op.join('\n')); $(n).bind('change', function(){ var v = Xms.Web.SelectedValue($(this)); var dataval=$(this).find('option:selected').attr('data-value'); var id = FilterDialogModel.datatype + Math.round(new Date().getTime() / 1000); var input = $(this).parents('.form-group').find('input[name=value]'); input.prop('id', id); if(v == Xms.Fetch.ConditionOperator.NotNull || v == Xms.Fetch.ConditionOperator.Null || v == null || v == ''||$.inArray(dataval,disabledArr)!=-1){ if(input.parents('.typeahead__container').length>0){ input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" disabled="disabled" >'); }else{ input.val('').prop('disabled','disabled'); } } else if(v != null && v != ''){ input.removeProp('disabled'); //根据字段类型生成输入框 switch(FilterDialogModel.datatype){ case "lookup": if($.inArray(dataval,noFindButton)!=-1){ if(input.parents('.typeahead__container').length>0){ input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" >'); }else{ input.removeProp('disabled'); } } else if($.inArray(dataval,moreSelect)!=-1){ input.lookup({ dialog: function(){ Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindMoreSelected') } ,clear: function(){ $('#' + id).val(''); $('#' + id).siblings(':input').val(''); }, disabled:true }); } else{ input.lookup({ dialog: function(){ Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected') } ,clear: function(){ $('#' + id).val(''); $('#' + id).siblings(':input').val(''); }, disabled:true }); } break; case "owner": if($.inArray(dataval,noFindButton)!=-1){ if(input.parents('.typeahead__container').length>0){ input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" >'); }else{ input.removeProp('disabled'); } } else if($.inArray(dataval,moreSelect)!=-1){ input.lookup({ dialog: function(){ Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindMoreSelected',null,function(){ input.removeProp('disabled'); }) } ,clear: function(){ $('#' + id).val(''); $('#' + id).siblings(':input').val(''); }, disabled:true }); } else{ input.lookup({ dialog: function(){ Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected',null,function(){ input.removeProp('disabled'); }) } ,clear: function(){ $('#' + id).val(''); $('#' + id).siblings(':input').val(''); }, disabled:true }); } break; case "customer": input.lookup({ dialog: function(){ Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected') } ,clear: function(){ $('#' + id).val(''); $('#' + id).siblings(':input').val(''); }, disabled:true }); break; case "picklist": input.picklist({ displaytype: 'select' , required: true ,items: FilterDialogModel.attributeMetaDatas.optionset.items//[{value:0, text:'已提交'},{value:1, text:'审核中'}] }); if($.inArray(dataval,moreSelect)!=-1){ input.siblings('select').prop('multiple','multiple'); input.siblings('select').prop('size',4); } else{ input.siblings('select').removeProp('multiple'); input.siblings('select').removeProp('size'); } break; case "bit": input.picklist({ displaytype: 'select' , required: true ,items: FilterDialogModel.attributeMetaDatas.picklists//[{value:0, text:'否'},{value:1, text:'是'}] }); break; case "datetime": input.unbind('keyup'); input.removeAttr('data-num'); if($.inArray(dataval,showDatepicker)!=-1){ input.addClass('datepicker'); $('.datepicker').datepicker({ autoclose: true , clearBtn: true , format: "yyyy-mm-dd" , language: "zh-CN" }); }else{ input.removeClass('datepicker'); input.attr('data-num',true); input.replaceWith(input.clone().bind('keyup',function(){digitsValue(this)})); } break; default: input.removeProp('disabled'); break; } } }); }); //绑定条件 if (FilterDialogModel.filter && FilterDialogModel.filter.Conditions&& FilterDialogModel.filter.Conditions.length > 0){ $('#filterContainer').find('input[name=logicaloperator][value='+FilterDialogModel.filter.FilterOperator+']').prop('checked',true); var idx = 0; $('#filterContainer').find('.form-group').each(function (i, n) { var row = $(n); if(row.find('select[name=conditionoperator]').length > 0){ if(idx>=FilterDialogModel.filter.Conditions.length) return; var cd = FilterDialogModel.filter.Conditions[idx]; if(FilterDialogModel.datatype == 'lookup' || FilterDialogModel.datatype == 'owner' || FilterDialogModel.datatype == 'customer'){ Xms.Web.GetJson('/api/data/Retrieve/ReferencedRecord/' + FilterDialogModel.attributeMetaDatas.referencedentityid + '/' + cd.Values.join(',') ,null,function(response){ row.find('input[name=value]').val(response.content.name); }); } else{ row.find('input[name=value]').val(cd.Values.join(',')); } row.find('input[name=value]').attr('data-value',cd.Values.join(',')); row.find('select[name=conditionoperator] option[value='+cd.Operator+']').prop('selected',true).trigger('change'); idx++; } }); } }); </script> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> <span class="glyphicon glyphicon-remove"></span> @app.T["dialog_close"] </button> <button type="button" class="btn btn-primary" onclick="FilterDialogModel.dialog_return()"> <span class="glyphicon glyphicon-ok"></span> @app.T["dialog_ok"] </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
the_stack
@{ ViewBag.MainMenu = "Portal"; ViewBag.LeftMenu = "CustomForm"; ViewBag.Title = "自定义表单"; Layout = "~/Views/Shared/_Layout.cshtml"; } <link rel="stylesheet" type="text/css" href="/Scripts/wangEditor/css/wangEditor.min.css"> <script type="text/javascript" src='/Scripts/wangEditor/js/wangEditor.min.js'></script> <style> .wangEditor-container .wangEditor-txt p, .wangEditor-container .wangEditor-txt h1, .wangEditor-container .wangEditor-txt h2, .wangEditor-container .wangEditor-txt h3, .wangEditor-container .wangEditor-txt h4, .wangEditor-container .wangEditor-txt h5 { margin: 0px 0; line-height: 1.8; } </style> <script language="javascript"> var _formId = getQueryString("id"); var _editorIntroduction; var _editorSuccessfulDescription; var _mode = "create";//modify var _validator; var _data; $(document).ready(function () { //_editorIntroduction = $('#txtIntroduction').wangEditor({ // 'menuConfig': [ // ['viewSourceCode'], // ['bold', 'underline', 'italic', 'foreColor', 'backgroundColor', 'strikethrough'], // ['blockquote', 'fontFamily', 'fontSize', 'setHead', 'list', 'justify'], // ['createLink', 'unLink', 'insertTable'], // ['insertLocation'], // ['undo', 'redo', 'fullScreen'] // ] //}); _editorIntroduction = new wangEditor('divIntroductionEditor'); _editorIntroduction.config.menus = [ 'source', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor', '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', '|', 'link', 'unlink', 'table', '|', 'undo', 'redo', 'fullscreen' ]; _editorIntroduction.create(); //_editorSuccessfulDescription = $('#txtSuccessfulDescription').wangEditor({ // 'menuConfig': [ // ['viewSourceCode'], // ['bold', 'underline', 'italic', 'foreColor', 'backgroundColor', 'strikethrough'], // ['blockquote', 'fontFamily', 'fontSize', 'setHead', 'list', 'justify'], // ['createLink', 'unLink', 'insertTable'], // ['insertLocation'], // ['undo', 'redo', 'fullScreen'] // ] //}); _editorSuccessfulDescription = new wangEditor('divSuccessfulDescriptionEditor'); _editorSuccessfulDescription.config.menus = [ 'source', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor', '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright', '|', 'link', 'unlink', 'table', '|', 'undo', 'redo', 'fullscreen' ]; _editorSuccessfulDescription.create(); _validator = $("#form").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtName": "required" }, messages: { "txtName": "请输入名称;" } }); loadData(); }); function loadData() { var id = getQueryString("id"); if (id == undefined || id == "") { return; } _mode = "modify"; $("#btnRemove").show(); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/CustomForm/GetCustomForm?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { _data = data.Data; $("#txtId").val(_data.Id); $("#txtName").val(_data.Name); _editorIntroduction.$txt.html(_data.Introduction) _editorSuccessfulDescription.$txt.html(_data.SuccessfulDescription); $("#txtShareImageUrl").val(_data.ShareImageUrl); $("#txtShareTimelineTitle").val(_data.ShareTimelineTitle); $("#txtShareAppMessageTitle").val(_data.ShareAppMessageTitle); $("#txtShareAppMessageDescription").val(_data.ShareAppMessageDescription); $("#txtImageUrl").val(_data.ImageUrl); $("#selectOnlyMember").find("option[value='" + _data.OnlyMember + "']").attr("selected", true); $("#txtGuideSubscribeUrl").val(_data.GuideSubscribeUrl); $("#txtRemark").val(_data.Remark); if (_data.FieldName) { $("#checkboxFieldName").attr("checked", "checked"); } if (_data.FieldNameRequired) { $("#checkboxFieldNameRequired").attr("checked", "checked"); } if (_data.FieldBirthday) { $("#checkboxFieldBirthday").attr("checked", "checked"); } if (_data.FieldBirthdayRequired) { $("#checkboxFieldBirthdayRequired").attr("checked", "checked"); } if (_data.FieldMobilePhone) { $("#checkboxFieldMobilePhone").attr("checked", "checked"); } if (_data.FieldMobilePhoneRequired) { $("#checkboxFieldMobilePhoneRequired").attr("checked", "checked"); } if (_data.FieldEmail) { $("#checkboxFieldEmail").attr("checked", "checked"); } if (_data.FieldEmailRequired) { $("#checkboxFieldEmailRequired").attr("checked", "checked"); } loadShareImage(); loadImage(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function uploadShareImage() { __showFileUpload(getUploadShareImageResult); } function getUploadShareImageResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; $("#txtShareImageUrl").val(url); loadShareImage(); } function loadShareImage() { $("#shareImage").attr("src", $("#txtShareImageUrl").val()); } function removeShareImage() { $("#txtShareImageUrl").val(""); loadShareImage(); } function uploadImage() { __showFileUpload(getUploadImageResult); } function getUploadImageResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; $("#txtImageUrl").val(url); loadImage(); } function loadImage() { $("#image").attr("src", $("#txtImageUrl").val()); } function removeImage() { $("#txtImageUrl").val(""); loadImage(); } function save() { if (_validator.form() == false) { return; } if (_data == undefined || _data == null) { _data = new Object(); } _data.Name = $("#txtName").val(); _data.Introduction = _editorIntroduction.$txt.html(); _data.SuccessfulDescription = _editorSuccessfulDescription.$txt.html(); _data.ShareImageUrl = $("#txtShareImageUrl").val(); _data.ShareTimelineTitle = $("#txtShareTimelineTitle").val(); _data.ShareAppMessageTitle = $("#txtShareAppMessageTitle").val(); _data.ShareAppMessageDescription = $("#txtShareAppMessageDescription").val(); _data.ImageUrl = $("#txtImageUrl").val(); _data.OnlyMember = $("#selectOnlyMember").val(); _data.GuideSubscribeUrl = $("#txtGuideSubscribeUrl").val(); _data.Remark = $("#txtRemark").val(); _data.FieldName = $("#checkboxFieldName").is(":checked"); _data.FieldNameRequired = $("#checkboxFieldNameRequired").is(":checked"); _data.FieldBirthday = $("#checkboxFieldBirthday").is(":checked"); _data.FieldBirthdayRequired = $("#checkboxFieldBirthdayRequired").is(":checked"); _data.FieldMobilePhone = $("#checkboxFieldMobilePhone").is(":checked"); _data.FieldMobilePhoneRequired = $("#checkboxFieldMobilePhoneRequired").is(":checked"); _data.FieldEmail = $("#checkboxFieldEmail").is(":checked"); _data.FieldEmailRequired = $("#checkboxFieldEmailRequired").is(":checked"); var url = "/Api/CustomForm/CreateCustomForm"; if (_mode == "modify") { _data.Id = $("#txtId").val(); url = "/Api/CustomForm/UpdateCustomForm"; } var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: url, type: "POST", dataType: "json", data: JSON.stringify(_data), success: function (data, status, jqXHR) { if (data.Success) { window.location.href = "/Portal/CustomFormContent?formId=" + _formId; } else { layer.close(loadLayerIndex); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function cancel() { if (_mode == "create") { window.location.href = "/Portal/CustomForm"; } else { window.location.href = "/Portal/CustomFormContent?formId=" + _formId; } } </script> <div style=" margin-top:25px; margin-left:10px;" class="font_black_24"> 添加表单 </div> <div class="divDotLine" style="margin-top:15px;"></div> <div style="margin-top:25px;"> <form id="form"> <input type="hidden" id="txtId" /> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="140" height="36">名称:</td> <td><input id="txtName" name="txtName" type="text" class="input_16" style="width:96%; " /></td> </tr> <tr> <td height="36">说明:</td> <td> <div style="width:96%"> <div id="divIntroductionEditor" style='height:200px; '></div> </div> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 说明内容将显示在页面上。 </div> </td> </tr> <tr> <td height="36">提交成功后提示:</td> <td> <div style="width:96%"> <div id="divSuccessfulDescriptionEditor" style='height:200px; '></div> </div> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 提交成功后,显示此内容。 </div> </td> </tr> <tr> <td height="110" valign="top"> <div style="margin-top: 5px;"> 分享小图片: </div> </td> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110"> <img id="shareImage" src="" alt="" width="100" height="100" /> </td> <td> <a href="javascript:void(0)" onclick="uploadShareImage()">上传新图片</a><br /> <a href="javascript:void(0)" onclick="removeShareImage()">删除图片</a> </td> </tr> </table> </td> </tr> <tr> <td height="36">&nbsp;</td> <td> <input id="txtShareImageUrl" name="txtShareImageUrl" type="text" class="input_16" style="width: 96%;" maxlength="500" /> </td> </tr> <tr> <td></td> <td valign="top"> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 在微信中分享活动时,使用的正方形小图片。 </div> </td> </tr> <tr> <td width="140" height="36">分享到朋友圈标题:</td> <td> <input id="txtShareTimelineTitle" name="txtShareTimelineTitle" type="text" class="input_16" style="width: 96%;" maxlength="50" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享到朋友圈时显示的标题文字。 </div> </td> </tr> <tr> <td width="140" height="36">分享给好友标题:</td> <td> <input id="txtShareAppMessageTitle" name="txtShareAppMessageTitle" type="text" class="input_16" style="width: 96%;" maxlength="50" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享给好友时显示的标题文字。 </div> </td> </tr> <tr> <td width="140" height="36">分享给好友描述:</td> <td> <input id="txtShareAppMessageDescription" name="txtShareAppMessageDescription" type="text" class="input_16" style="width: 96%;" maxlength="100" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享给好友时显示的标题下方的一段描述文字。 </div> </td> </tr> <tr> <td height="110" valign="top"> <div style="margin-top:5px;"> 图片: </div> </td> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="250"><img id="image" src="" alt="" width="240" height="100" /></td> <td> <a href="javascript:void(0)" onclick="uploadImage()">上传新图片</a><br /> <a href="javascript:void(0)" onclick="removeImage()">删除图片</a> </td> </tr> </table> </td> </tr> <tr> <td height="36">&nbsp;</td> <td><input id="txtImageUrl" name="txtImageUrl" type="text" class="input_16" style="width:96%; " /></td> </tr> <tr> <td></td> <td valign="top"> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 主题图片。 </div> </td> </tr> <tr> <td height="36">仅关注者可填写:</td> <td> <select id="selectOnlyMember" name="selectOnlyMember" class="input_16" style="width:130px;"> <option value="true">是</option> <option value="false">否</option> </select> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 当仅关注者才可参与时,未关注公众号者将被引导到“引导关注页面”。 </div> </td> </tr> <tr> <td width="140" height="36">引导关注页面:</td> <td><input id="txtGuideSubscribeUrl" name="txtGuideSubscribeUrl" type="text" class="input_16" style="width:96%; " /></td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 如果留空,将以全局设置为准,也可以在此指定一个针对本活动的特殊引导关注页面。 </div> </td> </tr> <tr> <td width="140" height="36">备注:</td> <td><input id="txtRemark" name="txtRemark" type="text" class="input_16" style="width:96%; " /></td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 内部备注,关注者不可见。 </div> </td> </tr> <tr> <td height="36" valign="top">填写字段:</td> <td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="100" height="30"> <input type="checkbox" id="checkboxFieldName" /> <label for="checkboxFieldName">姓名</label> </td> <td width="150"> <input type="checkbox" id="checkboxFieldNameRequired" /> <label for="checkboxFieldNameRequired">必填</label> </td> <td>&nbsp;</td> </tr> <tr> <td height="30"> <input type="checkbox" id="checkboxFieldBirthday" /> <label for="checkboxFieldBirthday">生日</label> </td> <td> <input type="checkbox" id="checkboxFieldBirthdayRequired" /> <label for="checkboxFieldBirthdayRequired">必填</label> </td> <td>&nbsp;</td> </tr> <tr> <td height="30"> <input type="checkbox" id="checkboxFieldMobilePhone" /> <label for="checkboxFieldMobilePhone">手机</label> </td> <td> <input type="checkbox" id="checkboxFieldMobilePhoneRequired" /> <label for="checkboxFieldMobilePhoneRequired">必填</label> </td> <td>&nbsp;</td> </tr> <tr> <td height="30"> <input type="checkbox" id="checkboxFieldEmail" /> <label for="checkboxFieldEmail">邮箱</label> </td> <td> <input type="checkbox" id="checkboxFieldEmailRequired" /> <label for="checkboxFieldEmailRequired">必填</label> </td> <td>&nbsp;</td> </tr> </table> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width:96%;margin-bottom:10px;"> 表单中粉丝需要填写的内容。 </div> </td> </tr> </table> </form> </div> <div style="margin-top:25px;"> <div style="float:right;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" style="display:none" onclick="removeData()" /> </div> <div style="float:left"> <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保 存" onclick="save()" /> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" /> </div> <div style="clear:both"></div> </div> @Helpers.FileUpload()
the_stack
@page <div class="container-fluid mt-3 mb-3"> <h2 class="mt-4">Custom select</h2> <div class="row mt-4"> <div class="col-3"> <select class="custom-select"> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> <div class="col-3"> <select class="custom-select disabled" disabled> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> </div> <h2 class="mt-4">Input group</h2> <div class="row mt-4"> <div class="col-3"> <div class="input-group"> <select class="custom-select"> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> <input class="form-control valid" type="text"> </div> </div> <div class="col-3"> <div class="input-group"> <input class="form-control valid" type="text"> <select class="custom-select"> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> </div> <div class="col-3"> <div class="input-group"> <div class="input-group-prepend"> <select class="custom-select"> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> <input class="form-control valid" type="text"> </div> </div> <div class="col-3"> <div class="input-group"> <input class="form-control valid" type="text"> <div class="input-group-append"> <select class="custom-select"> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-3"> <div class="input-group"> <select class="custom-select disabled" disabled> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> <input class="form-control valid" type="text"> </div> </div> <div class="col-3"> <div class="input-group"> <input class="form-control valid" type="text"> <select class="custom-select disabled" disabled> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> </div> <div class="col-3"> <div class="input-group"> <div class="input-group-prepend"> <select class="custom-select disabled" disabled> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> <input class="form-control valid" type="text"> </div> </div> <div class="col-3"> <div class="input-group"> <input class="form-control valid" type="text"> <div class="input-group-append"> <select class="custom-select disabled" disabled> <option value="">Choose an item</option> @for (var i = 0; i < 10; i++){ <option value="1">Item @i</option> } </select> </div> </div> </div> </div> <h2 class="mt-4"> Form Validation <small>Issue <a href="https://github.com/ForEvolve/bootstrap-dark/issues/40" target="_blank">#40</a></small> </h2> <div class="row mt-4"> <div class="col-4"> <form method="POST" class="needs-validation" novalidate> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationCustom01">First name</label> <input type="text" class="form-control" id="validationCustom01" value="Mark" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> This field is required. </div> </div> <div class="col-md-6 mb-3"> <label for="validationCustom02">Last name</label> <input type="text" class="form-control" id="validationCustom02" value="Otto" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> This field is required. </div> </div> </div> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationCustom03">City</label> <input type="text" class="form-control" id="validationCustom03" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label for="validationCustom04">State</label> <select class="custom-select" id="validationCustom04" required> <option selected disabled value="">Choose...</option> <option>...</option> </select> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please select a valid state. </div> </div> <div class="col-md-3 mb-3"> <label for="validationCustom05">Zip</label> <input type="text" class="form-control" id="validationCustom05" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please provide a valid zip. </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="invalidCheck1" required> <label class="form-check-label" for="invalidCheck1"> Agree to terms and conditions </label> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> You must agree before submitting. </div> </div> </div> <button class="btn btn-primary" type="submit">Submit form</button> </form> </div> <div class="col-4"> <form method="POST" class="needs-validation" novalidate> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationCustom11">First name</label> <input type="text" class="form-control" id="validationCustom11" value="Mark" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-6 mb-3"> <label for="validationCustom12">Last name</label> <input type="text" class="form-control" id="validationCustom12" value="Otto" required> <div class="valid-feedback"> Looks good! </div> </div> </div> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationCustom13">City</label> <input type="text" class="form-control" id="validationCustom13" required> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label for="validationCustom14">State</label> <select class="custom-select" id="validationCustom14" required> <option selected disabled value="">Choose...</option> <option>...</option> </select> <div class="invalid-feedback"> Please select a valid state. </div> </div> <div class="col-md-3 mb-3"> <label for="validationCustom15">Zip</label> <input type="text" class="form-control" id="validationCustom15" required> <div class="invalid-feedback"> Please provide a valid zip. </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required> <label class="form-check-label" for="invalidCheck2"> Agree to terms and conditions </label> <div class="invalid-feedback"> You must agree before submitting. </div> </div> </div> <button class="btn btn-primary" type="submit">Submit form</button> </form> </div> <div class="col-4"> <form> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationServer06">First name</label> <input type="text" class="form-control is-valid" id="validationServer06" value="Mark" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-6 mb-3"> <label for="validationServer07">Last name</label> <input type="text" class="form-control is-valid" id="validationServer07" value="Otto" required> <div class="valid-feedback"> Looks good! </div> </div> </div> <div class="form-row"> <div class="col-md-6 mb-3"> <label for="validationServer08">City</label> <input type="text" class="form-control is-invalid" id="validationServer08" required> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label for="validationServer09">State</label> <select class="custom-select is-invalid" id="validationServer09" required> <option selected disabled value="">Choose...</option> <option>...</option> </select> <div class="invalid-feedback"> Please select a valid state. </div> </div> <div class="col-md-3 mb-3"> <label for="validationServer10">Zip</label> <input type="text" class="form-control is-invalid" id="validationServer10" required> <div class="invalid-feedback"> Please provide a valid zip. </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Agree to terms and conditions </label> <div class="invalid-feedback"> You must agree before submitting. </div> </div> </div> <button class="btn btn-primary" type="submit">Submit form</button> </form> </div> </div> </div> @section scripts{ <script> // Example starter JavaScript for disabling form submissions if there are invalid fields (function () { 'use strict'; window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function (form) { console.log("Attach form action", form); form.addEventListener('submit', function (event) { var isValid = form.checkValidity(); console.log("Validate form", form, isValid); if (isValid === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })(); </script> }
the_stack
@model PackageListViewModel @{ ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm; ViewBag.SortText = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "recent installs" : "relevance"; ViewBag.Tab = "Packages"; ViewBag.BlockSearchEngineIndexing = !String.IsNullOrWhiteSpace(Model.SearchTerm) || Model.PageIndex != 0; } @helper AddPackageFilterOption(string optionName, string optionValue, bool isDefault = false) { @AddRadioGroupOption("Package Type", "packagetype", optionName, optionValue, Model.PackageType, isDefault); } @helper AddSortByOption(string optionName, string optionValue, bool isDefault = false) { @AddRadioGroupOption("Sort By", "sortby", optionName, optionValue, Model.SortBy, isDefault); } @helper AddRadioGroupOption(string ariaSectionLabel, string radioGroupName, string optionName, string optionValue, string optionCompareValue, bool isDefault = false) { <div style="display: flex;"> <label aria-label="@(ariaSectionLabel): @optionName"> <input type="radio" name="@radioGroupName" @(string.Equals(optionValue, optionCompareValue, StringComparison.OrdinalIgnoreCase) || (isDefault && optionCompareValue == null) ? "checked" : "") value="@optionValue"> @optionName </label> </div> } @functions { private const string DefaultPackageType = ""; private static readonly IReadOnlyDictionary<string, string> UiSupportedPackageTypes = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase) { { DefaultPackageType, "All types" }, { "dependency", "Dependency" }, { "dotnettool", ".NET tool" }, { "template" , "Template" }, }; } <section role="main" class="container main-container page-list-packages"> <div class="row clearfix no-margin"> <div class="col-md-10 no-padding"> <h1 role="alert"> @if (String.IsNullOrEmpty(Model.SearchTerm)) { if (Model.TotalCount == 1) { <text>There is 1 package</text> } else { <text>There are @Model.TotalCount.ToNuGetNumberString() packages</text> } } else { if (Model.TotalCount == 1) { <text>1 package </text> } else { <text>@Model.TotalCount.ToNuGetNumberString() packages </text> } <text>returned for @Html.BreakWord(Model.SearchTerm)</text> } </h1> </div> <div class="col-md-2 col-xs-3 col-sm-1 text-align-right no-padding"> @if (Model.IsAdvancedSearchFlightEnabled) { <button class="btn-command" data-toggle="collapse" data-target="#advancedSearchPanel" aria-expanded="false" aria-controls="advancedSearchPanel"> <i class="ms-Icon @(Model.ShouldDisplayAdvancedSearchPanel ? "ms-Icon--FilterSolid" : "ms-Icon--Filter") ms-fontColor-blue" aria-hidden="true"></i> Filter </button> } else { <a class="prerel-filter" href="?q=@Uri.EscapeDataString(Model.SearchTerm)@(Model.IncludePrerelease ? "&prerel=false" : "")">@(Model.IncludePrerelease ? "Hide" : "Show") prerelease</a> } </div> </div> @if (Model.IsAdvancedSearchFlightEnabled) { <form method="get" class="row clearfix collapse advanced-search-panel@(Model.ShouldDisplayAdvancedSearchPanel ? " in" : "")" id="advancedSearchPanel"> @if (Model.PackageType != null && !UiSupportedPackageTypes.ContainsKey(Model.PackageType)) { <div class="row warning-panel"> <div class="col-md-12 icon-text alert alert-warning"> <i class="ms-Icon ms-Icon--Info" aria-hidden="true"></i> Filtering on unrecognized package type: @Model.PackageType </div> </div> } <div class="row"> <div class="col-md-2"> <fieldset id="packagetype"> <legend>Package type</legend> @foreach (var packageType in UiSupportedPackageTypes) { @AddPackageFilterOption(packageType.Value, packageType.Key, isDefault: packageType.Key == DefaultPackageType) } </fieldset> </div> <div class="col-md-2"> <fieldset id="sortby"> <legend>Sort by</legend> @AddSortByOption("Relevance", GalleryConstants.SearchSortNames.Relevance, isDefault: true) @AddSortByOption("Downloads", GalleryConstants.SearchSortNames.TotalDownloadsDesc) @AddSortByOption("Recently updated", GalleryConstants.SearchSortNames.CreatedDesc) </fieldset> </div> <div class="col-md-2"> <fieldset> <legend>Options</legend> <div style="display: flex;"> <label aria-label="Options: Include prerelease"> <input id="prerel-checkbox" type="checkbox" checked="@Model.IncludePrerelease"> Include prerelease </label> </div> </fieldset> </div> </div> <div class="row"> <div class="col-xs-4 col-sm-3 col-md-2 col-lg-1"> <input class="btn btn-primary form-control" type="submit" value="Apply"> </div> <div class="col-xs-4 col-sm-3 col-md-2 col-lg-1"> <input id="reset-advanced-search" class="btn btn-link form-control" type="button" value="Reset"> </div> </div> <input type="hidden" name="q" value="@Model.SearchTerm"> <input type="hidden" id="prerel" name="prerel" value="@Model.IncludePrerelease.ToString()"> </form> } @if (!Model.Items.Any()) { <div class="row"> <div class="col-xs-12 clearfix"> <div class="panel panel-default" aria-expanded="true" > <div class="panel-body"> NuGet package search works the same on nuget.org, from the NuGet CLI, and within the NuGet Package Manager extension in Visual Studio. <br /> Check out our <strong><a href="https://docs.microsoft.com/nuget/consume-packages/finding-and-choosing-packages#search-syntax">Search Syntax</a></strong>. </div> </div> </div> </div> } <div class="list-packages" role="list"> @{ var itemIndex = Model.PageIndex * Model.PageSize; var eventName = Model.IsPreviewSearch ? "preview-search-selection" : "search-selection"; } @foreach (var package in Model.Items) { @Html.Partial("_ListPackage", package, new ViewDataDictionary { { "itemIndex", itemIndex }, { "eventName", eventName } }) itemIndex++; } </div> <div class="row"> <div class="col-xs-12 clearfix"> @ViewHelpers.PreviousNextPager(Model.Pager) </div> </div> </section> @section bottomScripts { <script type="text/javascript"> // Used to track how long the user waited before clicking a search selection. var pageLoadTime = Date.now(); // Used to track how many selections were made on this page. Multiple selections can happen if the user opens // a search selection in a new tab, instead of navigating away from this page. var sincePageLoadCount = 0; @{ var searchId = Guid.NewGuid().ToString(); var category = Model.IsPreviewSearch ? "preview-search-page" : "search-page"; var action = Model.IncludePrerelease ? "search-prerel" : "search-stable"; // Emit an event representing the search page and the page index. This make it easier for the search selection // event to be correlated in Google Analytics. <text> window.nuget.sendAnalyticsEvent('@category', '@action', @Html.Raw(Json.Encode(Model.SearchTerm)), @Model.PageIndex); window.nuget.sendMetric('BrowserSearchPage', @Model.PageIndex, { SearchId: '@searchId', SearchTerm: @Html.Raw(Json.Encode(Model.SearchTerm)), IncludePrerelease: '@Model.IncludePrerelease', PageIndex: @Model.PageIndex, TotalCount: @Model.TotalCount, IsPreviewSearch: '@Model.IsPreviewSearch', PackageType: @Html.ToJson(Model.PackageType ?? string.Empty), SortBy: @Html.ToJson(Model.SortBy) }); </text> } $(function () { var emitClickEvent = function () { var $this = $(this); var data = $this.data(); if ($this.attr('href') && data.track) { window.nuget.sendMetric('BrowserSearchSelection', data.trackValue, { SearchId: '@searchId', SearchTerm: @Html.Raw(Json.Encode(Model.SearchTerm)), IncludePrerelease: '@Model.IncludePrerelease', PageIndex: @Model.PageIndex, TotalCount: @Model.TotalCount, ClickIndex: data.trackValue, PackageId: data.packageId, PackageVersion: data.packageVersion, UseVersion: data.useVersion, SincePageLoadMs: Date.now() - pageLoadTime, SincePageLoadCount: sincePageLoadCount, IsPreviewSearch: '@Model.IsPreviewSearch', PackageType: @Html.ToJson(Model.PackageType ?? string.Empty), SortBy: @Html.ToJson(Model.SortBy) }); sincePageLoadCount++; } }; $.each($('a[data-track]'), function () { $(this).on('mouseup', function (e) { if (e.which === 2) { // Middle-mouse click emitClickEvent.call(this, e); } }); $(this).on('click', function (e) { emitClickEvent.call(this, e); }); }); }); $('#prerel-checkbox').on('change', function (event) { $('#prerel').val($(event.target).is(':checked')); }); $('#reset-advanced-search').on('click', function () { location.href = '?q=@Uri.EscapeDataString(Model.SearchTerm)'; }); </script> @Scripts.Render("~/Scripts/gallery/page-list-packages.min.js") }
the_stack
@page @model IonrangesliderModel @{ ViewData["Title"] = "Ion.RangeSlider"; ViewData["PageName"] = "form_plugins_ionrangeslider"; ViewData["Category1"] = "Form Plugins"; ViewData["Heading"] = "<i class='subheader-icon fal fa-credit-card-front'></i> Ion.RangeSlider<sup class='badge badge-primary fw-500'>ADDON</sup>"; ViewData["PageDescription"] = "Easy to use, flexible and responsive range slider with skin support"; } @section HeadBlock { <link rel="stylesheet" media="screen, print" href="~/css/formplugins/ion-rangeslider/ion-rangeslider.css"> } <div class="alert alert-primary"> <div class="d-flex flex-start w-100"> <div class="mr-2 hidden-md-down"> <span class="icon-stack icon-stack-lg"> <i class="base base-6 icon-stack-3x opacity-100 color-primary-500"></i> <i class="base base-10 icon-stack-2x opacity-100 color-primary-300 fa-flip-vertical"></i> <i class="ni ni-blog-read icon-stack-1x opacity-100 color-white"></i> </span> </div> <div class="d-flex flex-fill"> <div class="flex-fill"> <span class="h5">About</span> <p>Easy to use, flexible and responsive range slider comes with skin support (6 skins included). Features include two types of sliders (1 or double), support for negative and fractional values. Ability to setup custom step and snap to grid option. Customizable grid values and the ability to add port & prefixes. Slider writes its value right into input value field, making it easy to use in any HTML form. You can have many sliders in one page without any conflict.</p> <p class="m-0"> Find in-depth, guidelines, tutorials and more on Ion.RangeSlider's <a href="http://ionden.com/a/plugins/ion.rangeSlider/index.html" target="_blank">Official Documentation</a> </p> </div> </div> </div> </div> <div class="mb-g text-center"> <h5>Skin Options</h5> <div class="js-toggle-skin btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-default active"> <input type="radio" name="skinchange" id="skin-1" checked="" value="irs--flat"> <span class="hidden-sm-down">Flat</span><span class="hidden-sm-up">Opt 1</span> </label> <label class="btn btn-default"> <input type="radio" name="skinchange" id="skin-2" value="irs--big"> <span class="hidden-sm-down">Big</span><span class="hidden-sm-up">Opt 2</span> </label> <label class="btn btn-default"> <input type="radio" name="skinchange" id="skin-3" value="irs--modern"> <span class="hidden-sm-down">Modern</span><span class="hidden-sm-up">Opt 3</span> </label> <label class="btn btn-default"> <input type="radio" name="skinchange" id="skin-4" value="irs--sharp"> <span class="hidden-sm-down">Sharp</span><span class="hidden-sm-up">Opt 4</span> </label> <label class="btn btn-default"> <input type="radio" name="skinchange" id="skin-5" value="irs--round"> <span class="hidden-sm-down">Round</span><span class="hidden-sm-up">Opt 5</span> </label> <label class="btn btn-default"> <input type="radio" name="skinchange" id="skin-6" value="irs--square"> <span class="hidden-sm-down">Square</span><span class="hidden-sm-up">Opt 6</span> </label> </div> </div> <div class="row"> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> Simple start <span class="fw-300"><i>basic params</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Set type to double, specify range, show grid and add a prefix <code>"$"</code> </div> <input id="demo_1" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-2" class="panel"> <div class="panel-hdr"> <h2> Set up <span class="fw-300"><i>range and step</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Force fractional values, using fractional step 0.1 </div> <input id="demo_2" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6"> <div id="panel-3" class="panel"> <div class="panel-hdr"> <h2> Using <span class="fw-300"><i>array of custom values</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Values array could be anything, even strings </div> <input id="demo_3" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-4" class="panel"> <div class="panel-hdr"> <h2> Change <span class="fw-300"><i>visual look of numbers (prettify)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Use your own prettify function to transform numbers whatever you like </div> <input id="demo_4" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6"> <div id="panel-5" class="panel"> <div class="panel-hdr"> <h2> Decorating <span class="fw-300"><i>with prefixes, postfixes</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Using prefix and postfix at the same time, taking care of labels collision </div> <input id="demo_5" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-6" class="panel"> <div class="panel-hdr"> <h2> Manipulating <span class="fw-300"><i>UI</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Disable enable any UI elements </div> <input id="demo_6" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6"> <div id="panel-7" class="panel"> <div class="panel-hdr"> <h2> Customising <span class="fw-300"><i>Grid</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Manipulate the grid using build in parameters </div> <input id="demo_7" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-8" class="panel"> <div class="panel-hdr"> <h2> Lock <span class="fw-300"><i>and restrict handles</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Limit movement of a handle </div> <input id="demo_8" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6"> <div id="panel-9" class="panel"> <div class="panel-hdr"> <h2> Manipulating <span class="fw-300"><i>interval</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Restrict interval size and/or drag it </div> <input id="demo_9" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-10" class="panel"> <div class="panel-hdr"> <h2> Working <span class="fw-300"><i>with dates</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Restrict interval size and/or drag it </div> <input id="demo_10" type="text" value="" class="d-none" tabindex="-1" readonly=""> </div> </div> </div> </div> </div> </div> </div> @section ScriptsBlock { <script src="~/js/formplugins/ion-rangeslider/ion-rangeslider.js"></script> <script> $(document).ready(function () { $('input[type=radio][name=skinchange]').change(function() { $('.irs').removeClassPrefix('irs--').addClass(this.value); }); var ionskin = "flat"; $("#demo_1").ionRangeSlider({ skin: ionskin, type: "double", grid: true, min: 0, max: 1000, from: 200, to: 800, prefix: "$" }); $("#demo_2").ionRangeSlider({ skin: ionskin, type: "double", grid: true, min: -12.8, max: 12.8, from: -3.2, to: 3.2, step: 0.1 }); $("#demo_3").ionRangeSlider({ skin: ionskin, grid: true, from: new Date().getMonth(), values: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); function my_prettify (n) { var num = Math.log2(n); return n + " → " + (+num.toFixed(3)); } $("#demo_4").ionRangeSlider({ skin: ionskin, grid: true, min: 1, max: 1000, from: 100, prettify: my_prettify }); $("#demo_5").ionRangeSlider({ skin: ionskin, type: "double", grid: true, min: 0, max: 100, from: 47, to: 53, prefix: "Weight: ", postfix: " lbs", decorate_both: true // false, // values_separator: " to " }); $("#demo_6").ionRangeSlider({ skin: ionskin, type: "double", min: -100000, max: 100000, from: -100000, to: 100000, step: 10000, grid: true, // show/hide grid force_edges: false, // force UI in the box hide_min_max: false, // show/hide MIN and MAX labels hide_from_to: false, // show/hide FROM and TO labels block: false // block instance from changing }) //Customising Grid $("#demo_7").ionRangeSlider({ skin: ionskin, min: 0, max: 10000, from: 777, step: 1, // default 1 (set step) grid: true, // default false (enable grid) grid_num: 4, // default 4 (set number of grid cells) grid_snap: false // default false (snap grid to step) }); //Lock and restrict handles $("#demo_8").ionRangeSlider({ skin: ionskin, type: "single", min: 0, max: 1000, from: 500, grid: true, from_min: 250, // set min position for FROM handle (replace FROM to TO to change handle) from_max: 750, // set max position for FROM handle from_shadow: true // highlight restriction for FROM handle }); //Manipulating interval $("#demo_9").ionRangeSlider({ skin: ionskin, type: "double", min: 0, max: 1000, from: 400, to: 600, drag_interval: true, min_interval: 100, max_interval: 700 }); //Working with dates var lang = "en-US"; var year = 2018; function dateToTS (date) { return date.valueOf(); } function tsToDate (ts) { var d = new Date(ts); return d.toLocaleDateString(lang, { year: 'numeric', month: 'numeric', day: 'numeric' }); } //Working with dates $("#demo_10").ionRangeSlider({ skin: ionskin, type: "double", grid: true, min: dateToTS(new Date(year, 10, 1)), max: dateToTS(new Date(year, 11, 1)), from: dateToTS(new Date(year, 10, 8)), to: dateToTS(new Date(year, 10, 23)), prettify: tsToDate }); }); </script> }
the_stack
 @{ ViewData["Title"] = "Index"; Layout = "~/Views/Shared/_Index.cshtml"; } <link href="~/ui/plugins/jquery-layout/jquery.layout-latest.css" rel="stylesheet" /> <link href="~/ui/plugins/jquery-ztree/3.5/css/metro/zTreeStyle.css" rel="stylesheet" /> <div class="ui-layout-west"> <div class="box box-main"> <div class="box-header"> <div class="box-title"> <i class="fa icon-grid"></i>栏目列表 </div> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新栏目" onclick="loadChannelTree();"><i class="fa fa-refresh"></i></button> </div> </div> <div class="ui-layout-content"> <div id="channelTree" class="ztree"></div> </div> </div> </div> <div class="ui-layout-center"> <div class="container-div"> <div class="row"> <div class="col-sm-12 search-collapse"> <form id="searchForm"> <div class="select-list"> <ul> <li> 标题:<input type="text" name="contentTitle" id="contentTitle"/> </li> <li> 审核状态: <select name="contentStatus" id="contentStatus"> <option value="-1">所有</option> <option value="0">待审</option> <option value="1">通过</option> <option value="100">审核不通过</option> </select> </li> <li> 属性: <select name="contentProperty" id="contentProperty"> <option value="0">所有</option> <option value="1">置顶</option> <option value="2">推荐</option> </select> </li> <li> <a class="btn btn-primary btn-rounded btn-sm" id="searchButton"><i class="fa fa-search"></i>&nbsp;搜索</a> <a class="btn btn-warning btn-rounded btn-sm" id="resetButton"><i class="fa fa-refresh"></i>&nbsp;重置</a> </li> </ul> </div> </form> </div> <div class="btn-group-sm" id="toolbar" role="group"> <a class="btn btn-success" onclick="add();" data-id="0" data-role="cms:content:add"> <i class="fa fa-plus"></i> 新增 </a> <a class="btn btn-primary single disabled" onclick="edit(this);" data-id="0" data-role="cms:content:edit"> <i class="fa fa-edit"></i> 修改 </a> <a class="btn btn-danger multiple disabled" onclick="removeAll(this);" data-id="0" data-role="cms:content:delete"> <i class="fa fa-remove"></i> 删除 </a> <a class="btn btn-info multiple disabled" onclick="setTop(this)" data-id="0" data-role="cms:content:top"> <i class="fa fa-arrow-up"></i> 置顶 </a> <a class="btn btn-warning multiple disabled" onclick="setRecomend()" data-id="0" data-role="cms:content:recomend"> <i class="fa fa-thumbs-up"></i> 推荐 </a> </div> <div class="col-sm-12 select-table table-striped"> <table id="dataTable"></table> </div> </div> </div> </div> @section scripts{ <script src="~/ui/plugins/jquery-layout/jquery.layout-latest.js"></script> <script src="~/ui/plugins/jquery-ztree/3.5/js/jquery.ztree.all-3.5.js"></script> <script> let $table, channelTree, channelId = 0, lastChannelNode; $(function () { let panehHidden = false; if ($(this).width() < 769) { panehHidden = true; } $('body').layout({ initClosed: panehHidden, west__size: 200 }); // 回到顶部绑定 if ($.fn.toTop !== undefined) { var opt = { win: $('.ui-layout-center'), doc: $('.ui-layout-center') }; $('#scroll-up').toTop(opt); } jutils.handleMessage(function (res) { //console.log(res); if (res.title === 'cms_content_form') { $table.easyTable('search'); } }); loadChannelTree(); loadGrid(); }); function loadChannelTree() { channelId = 0; var opts = { data: { simpleData: { enable: true, pIdKey: "pId", } }, callback: { onClick: DicZtreeClick }, check: { enable: true, chkStyle: "radio" } }; jutils.ajaxGet('/Cms/Channel/GetChannelTree', null, function (res) { channelTree = $.fn.zTree.init($("#channelTree"), opts, res.data.channels); channelTree.expandAll(true); }); } //单击事件 function DicZtreeClick(event, treeId, treeNode) { if (lastChannelNode) { channelTree.checkNode(lastChannelNode, false, true); } channelTree.checkNode(treeNode, true, true); lastChannelNode = treeNode; //console.log(treeNode); channelId = treeNode.id; $table.easyTable('search'); } function loadGrid() { let options = { url: '/cms/content/GetData', pageNumber: 1, // 初始化加载第一页,默认第一页,并记录 pageSize: 10, // 每页的记录行数(*) pageList: "10, 25, 50, 100", // 可供选择的每页的行数(*) uniqueId: 'id', queryParams: function (params) { let p = { pageNumber: params.pageNumber, pageSize: params.pageSize, channelId: channelId, contentProperty: $('#contentProperty').val(), title: $('#contentTitle').val(), status: $('#contentStatus').val() } return p; }, columns: [ { field: 'selectItem', checkbox: true }, { field: 'id', title: '文章ID', align: 'left' }, { field: 'title', title: '文章标题', align: 'left', formatter: renderTitle }, { field: 'publish_time', title: '发布时间', align: 'center' }, { field: 'author', title: '作者', align: 'center' }, { field: 'content_status', title: '状态', align: 'center', formatter: function (v) { if (v === 1) { return '<span class="label label-primary">已审核</span>'; } return '<span class="label">待审核</span>'; } } //{ // field: 'id', title: '操作', align: 'center', // formatter: render //} ] }; $table = $('#dataTable').easyTable(options); } function render(v, r, i) { var html = jutils.initToolBarRow(v); return html; } function renderTitle(v, d) { var thtml = '<a href="/news/' + d.channel_id + '/' + d.id + '" target="_blank">' + v + '&nbsp;&nbsp;'; if (d.is_top == 1) { thtml += '<img src="/static/images/top.gif"/>&nbsp;&nbsp;'; } //if (d.hit_count > 100) { // thtml += '<img src="/static/images/hot.gif"/>&nbsp;&nbsp;'; //} if (d.is_recommend) { thtml += '<img src="/static/images/tuijian.png"/>&nbsp;&nbsp;'; } thtml += '</a>'; return thtml; //return '<a href="/static/content/' + d.channel_id + '/' + d.id + '.html" target="_blank">' + v + '</a>'; } function add() { if (channelId == '0') { jutils.warn("请先选择栏目"); return; } var url = '/cms/Content/Form'; jutils.openTab('cms_content_form', '发布文章', url, { id: 0, channelId: channelId }); //jutils.dialogTop("发布文章", url, { id: 0, channelId: channelId }, null, function () { // $table.easyTable('search'); //}); } function edit() { var rows = $table.easyTable("selected"); if (rows.length == 0) { jutils.warn('请选择数据行'); return; } var id = rows[0].id; //var row = $table.bootstrapTable('getRowByUniqueId', id); var channel = rows[0].channel_id; var url = '/cms/Content/Form'; jutils.openTab('cms_content_form', '修改文章', url, { id: id, channelId: channel }); //jutils.dialogTop("修改文章", url, { id: 0, channelId: channelId }, null, function () { // $table.easyTable('search'); //}); } function removeAll(obj) { var rows = $table.easyTable("selected"); if (rows.length == 0) { jutils.warn('请选择数据行'); return; } var ids = []; for (let i = 0; i < rows.length; i++) { ids.push(rows[i].id); } jutils.confirm("确认删除选中的文章吗", function () { jutils.ajaxGet('/cms/Content/DeleteById', { ids: ids.join() }, function (res) { $table.easyTable('search'); }) }) } function setTop() { var rows = $table.bootstrapTable('getSelections'); if (rows.length == 0) { jutils.error("请选择需要置顶的文章数据行"); return; } var ids = []; for (let i = 0; i < rows.length; i++) { ids.push(rows[i].id); } jutils.confirm("确认置顶选择的文章吗?", function () { jutils.ajaxGet('/cms/content/SetTop', { ids: ids }, function (res) { $table.easyTable('search'); }); }); } function setRecomend() { var rows = $table.bootstrapTable('getSelections'); if (rows.length == 0) { jutils.error("请选择需要推荐的文章数据行"); return; } var ids = []; for (let i = 0; i < rows.length; i++) { ids.push(rows[i].id); } jutils.confirm("确认置顶选择的文章吗?", function () { jutils.ajaxGet('/cms/content/SetRecomend', { ids: ids }, function (res) { $table.easyTable('search'); }); }); } </script> }
the_stack
@{ ViewBag.Title = "MenuEdit"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } <script> var _domainId = '@ViewBag.Domain.Id'; var _appId = '@ViewBag.DomainContext.AppId'; //在同一个form中创建多个jValidate验证器不灵 var _validator_wxc_function; var _validator_view; var _validator_wxc_campaign; var _validator_wxc_information; var _validator_wxc_customForm; var _validator_mediaId; var _validator_click; var _mode //createButton //modifyButton //createSubButton //modifySubButton var _buttonIndex; var _button; var _parentButtonIndex; $(document).ready(function () { //alert(window.location.href); _mode = getQueryString("mode"); createValidator(); switchTypeTable(); $("#selectType").change(function () { switchTypeTable(); }); $("#select_wxc_function").change(function () { setFunctionUrl(); }); $("#select_wxc_campaign_type").change(function () { // alert("select_wxc_campaign_type change"); loadCampaignList(); }); $("#select_wxc_campaign").change(function () { setCampaignUrl(); }); $("#select_wxc_information").change(function () { setInformationUrl(); }); $("#select_wxc_customForm").change(function () { setCustomFormUrl(); }); $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { save(); } }); switch (_mode) { case "createButton": break; case "modifyButton": loadButton(); break; case "createSubButton": _parentButtonIndex = getQueryString("parentButton"); break; case "modifySubButton": _parentButtonIndex = getQueryString("parentButton"); loadButton(); break; default: alert("_mode:" + _mode); break; } //if (_button != undefined && _button != null && _button.type == "wxc_campaign") { // //在loadButton中读取CampaignList //} else { // loadCampaignList(); //} //if (_button != undefined && _button != null && _button.type == "wxc_information") { // //在loadButton中读取 //} else { // loadInformationList(); //} //if (_button != undefined && _button != null && _button.type == "wxc_customForm") { // //在loadButton中读取 //} else { // loadCustomFormList(); //} }); function setFunctionUrl() { var selectedFunction = $("#select_wxc_function").find("option:selected").attr("urlpath"); $("#divUrl").html("http://" + _appId + ".wxc.shengxunwei.com/" + selectedFunction + "/" + _domainId); } function setCampaignUrl() { var selectedCampaignType = $("#select_wxc_campaign_type").find("option:selected").attr("urlpath"); var selectedCampaignId = $("#select_wxc_campaign").val(); $("#divUrl").html("http://" + _appId + ".wxc.shengxunwei.com/Campaign/" + selectedCampaignType + "/" + _domainId + "?campaignId=" + selectedCampaignId); } function setInformationUrl() { var selectedInformationId = $("#select_wxc_information").val(); $("#divUrl").html("http://" + _appId + ".wxc.shengxunwei.com/Home/Information/" + _domainId + "?informationId=" + selectedInformationId); } function setCustomFormUrl() { var selectedFormId = $("#select_wxc_customForm").val(); $("#divUrl").html("http://" + _appId + ".wxc.shengxunwei.com/Home/CustomForm/" + _domainId + "?formId=" + selectedFormId); } function switchTypeTable() { //alert($("#selectType").val()); var type = $("#selectType").val(); $("#divTableCollection div[buttonTypeDiv='buttonTypeDiv']").hide(); $("#divTableCollection div[buttonTypeDiv='buttonTypeDiv']").each(function (n, value) { if ($(value).attr("id") == "div_" + type) { $(value).show(); if ($(value).attr("directurl") == "true") { $("#divDirectUrlArea").show(); } else { $("#divDirectUrlArea").hide(); } } }); switch (type) { case "wxc_function": setFunctionUrl(); break; case "click": loadClickList(); break; case "wxc_campaign": loadCampaignList(); break; case "wxc_information": loadInformationList(); break; case "wxc_customForm": loadCustomFormList(); break; } } function createValidator() { _validator_wxc_function = $("#form_wxc_function").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_wxc_function_name": "required" }, messages: { "txt_wxc_function_name": "请输入名称;" } }); _validator_view = $("#form_view").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_view_name": "required", "txt_view_url": { required: true, url: true } }, messages: { "txt_view_name": "请输入名称;", "txt_view_url": { required: "请输入要访问的网址;", url: "请输入格式正确的网址" } } }); _validator_click = $("#form_click").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_click_name": "required", "select_click_type": "required", "select_click": "required" }, messages: { "txt_view_name": "请输入名称;", "select_click_type": "请选择要触发的事件;", "select_click": "请选择要触发的事件;" } }); _validator_wxc_campaign = $("#form_wxc_campaign").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_wxc_campaign_name": "required", "select_wxc_campaign_type": "required", "select_wxc_campaign": "required" }, messages: { "txt_wxc_campaign_name": "请输入名称;", "select_wxc_campaign_type": "请选择活动;", "select_wxc_campaign": "请选择活动;" } }); _validator_wxc_information = $("#form_wxc_information").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_wxc_information_name": "required", "select_wxc_information": "required" }, messages: { "txt_wxc_information_name": "请输入名称;", "select_wxc_information": "请选择分类信息;" } }); _validator_wxc_customForm = $("#form_wxc_customForm").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_wxc_customForm_name": "required", "select_wxc_customForm": "required" }, messages: { "txt_wxc_customForm_name": "请输入名称;", "select_wxc_customForm": "请选择表单;" } }); _validator_mediaId = $("#form_mediaId").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_mediaId_name": "required", }, messages: { "txt_mediaId_name": "请输入名称;", } }); } function loadButton() { _buttonIndex = getQueryString("button"); if (_buttonIndex == undefined || _buttonIndex == "") { return; } $("#spanTitle").html("修改菜单"); $("#btnRemove").show(); if (_mode == "modifyButton") { _button = parent.getButton(_buttonIndex); } else if (_mode == "modifySubButton") { _button = parent.getSubButton(_parentButtonIndex, _buttonIndex); } $("#selectType").val(_button.type); switchTypeTable(); switch (_button.type) { case "wxc_function": load_wxc_function(); break; case "view": load_view(); break; case "click": load_click(); break; case "wxc_campaign": load_wxc_campaign(); break; case "wxc_information": load_wxc_information(); break; case "wxc_customForm": load_wxc_customForm(); break; case "mediaId": load_mediaId(); break; default: alert("type:" + type); break; } } function load_wxc_function() { $("#txt_wxc_function_name").val(_button.name); $("#select_wxc_function").val(_button.function); setFunctionUrl(); } function load_view() { $("#txt_view_name").val(_button.name); $("#txt_view_url").val(_button.url); } function load_click() { $("#txt_click_name").val(_button.name); $("#select_click_type").val(_button.clickType); loadClickList(); } function load_wxc_campaign() { $("#txt_wxc_campaign_name").val(_button.name); $("#select_wxc_campaign_type").val(_button.campaignType); loadCampaignList(); } function load_wxc_information() { $("#txt_wxc_information_name").val(_button.name); loadInformationList(); } function load_wxc_customForm() { $("#txt_wxc_customForm_name").val(_button.name); loadCustomFormList(); } function load_mediaId() { $("#txt_mediaId_name").val(_button.name); __setMaterial(_button.materialType, null, _button.materialId); } function save() { var validateResult = false; var type = $("#selectType").val(); // alert("type:" + type); switch (type) { case "wxc_function": validateResult = save_wxc_function(); break; case "view": validateResult = save_view(); break; case "click": validateResult = save_click(); break; case "wxc_campaign": validateResult = save_wxc_campaign(); break; case "wxc_information": validateResult = save_wxc_information(); break; case "wxc_customForm": validateResult = save_wxc_customForm(); break; case "mediaId": validateResult = save_mediaId(); break; default: alert("type:" + type); break; } if (validateResult == false) return; var layerIndex = parent.layer.getFrameIndex(window.name); switch (_mode) { case "createButton": parent.addButtonAndCloseLayer(layerIndex, _button); break; case "modifyButton": parent.closeLayer(layerIndex); break; case "createSubButton": parent.addSubButtonAndCloseLayer(layerIndex, _parentButtonIndex, _button); break; case "modifySubButton": parent.closeLayer(layerIndex); break; default: alert("_mode:" + _mode); break; } } function save_wxc_function() { if (_validator_wxc_function.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "wxc_function"; _button.name = $("#txt_wxc_function_name").val(); _button.function = $("#select_wxc_function").val(); return true; } function save_view() { if (_validator_view.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "view"; _button.name = $("#txt_view_name").val(); _button.url = $("#txt_view_url").val(); return true; } function save_click() { if (_validator_click.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "click"; _button.name = $("#txt_click_name").val(); _button.clickType = $("#select_click_type").val(); _button.key = $("#select_click").val(); return true; } function save_wxc_campaign() { if (_validator_wxc_campaign.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "wxc_campaign"; _button.name = $("#txt_wxc_campaign_name").val(); _button.campaignType = $("#select_wxc_campaign_type").val(); _button.campaign = $("#select_wxc_campaign").val(); return true; } function save_wxc_information() { if (_validator_wxc_information.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "wxc_information"; _button.name = $("#txt_wxc_information_name").val(); _button.information = $("#select_wxc_information").val(); return true; } function save_wxc_customForm() { if (_validator_wxc_customForm.form() == false) { return false; } if (_button == undefined) { _button = new Object(); } _button.type = "wxc_customForm"; _button.name = $("#txt_wxc_customForm_name").val(); _button.customForm = $("#select_wxc_customForm").val(); return true; } function save_mediaId() { if (_validator_mediaId.form() == false) { return false; } if (__validateMaterialSelect() == false) return false; if (_button == undefined) { _button = new Object(); } _button.type = "mediaId"; _button.name = $("#txt_mediaId_name").val(); _button.materialType = __materialType; _button.materialId = __materialSelect_materialId; _button.mediaId = __materialSelect_mediaId; return true; } function loadCampaignList() { $("#select_wxc_campaign").empty(); $("#select_wxc_campaign").attr("disabled", "disabled"); //var loadLayerIndex = layer.open({ // type: 2, // shadeClose: false, // content: '请稍候...' //}); var args = new Object(); args.Page = 1; args.PageSize = 1000; args.Type = $("#select_wxc_campaign_type").val(); $.ajax({ url: "/Api/Campaign/GetCampaignList", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); // layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; $.each(resultObj.ItemList, function (idx, obj) { $("#select_wxc_campaign").append("<option value='" + obj.Id + "'>" + obj.Name + "</option>"); }); $("#select_wxc_campaign").removeAttr("disabled"); if (_button != undefined && _button != null && _button.campaign != undefined && _button.campaign != null && _button.campaignType == args.Type) { // alert(_button.campaign); $("#select_wxc_campaign").val(_button.campaign); } else { $('#select_wxc_campaign option:eq(0)').attr('selected', 'selected'); } setCampaignUrl(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); // alert("Error: " + xmlHttpRequest.status); } }); } function loadClickList() { $("#select_click").empty(); $("#select_click").attr("disabled", "disabled"); switch ($("#select_click_type").val()) { case "MemberQRCode": loadClickList_MemberQRCode(); break; default: break; } } function loadClickList_MemberQRCode() { //var loadLayerIndex = layer.open({ // type: 2, // shadeClose: false, // content: '请稍候...' //}); var args = new Object(); args.Page = 1; args.PageSize = 1000; args.Type = "MemberQRCode"; $.ajax({ url: "/Api/Campaign/GetCampaignList", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); // layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; $.each(resultObj.ItemList, function (idx, obj) { $("#select_click").append("<option value='" + obj.Id + "'>" + obj.Name + "</option>"); }); $("#select_click").removeAttr("disabled"); if (_button != undefined && _button != null && _button.key != undefined && _button.key != null && _button.type == "MemberQRCode") { // alert(_button.campaign); $("#select_click").val(_button.key); } else { $('#select_click option:eq(0)').attr('selected', 'selected'); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); // alert("Error: " + xmlHttpRequest.status); } }); } function loadInformationList() { $("#select_wxc_information").empty(); $("#select_wxc_information").attr("disabled", "disabled"); //var loadLayerIndex = layer.open({ // type: 2, // shadeClose: false, // content: '请稍候...' //}); var args = new Object(); args.Page = 1; args.PageSize = 1000; $.ajax({ url: "/Api/Information/GetInformationList", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); // layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; $.each(resultObj.ItemList, function (idx, obj) { $("#select_wxc_information").append("<option value='" + obj.Id + "'>" + obj.Name + "</option>"); }); $("#select_wxc_information").removeAttr("disabled"); if (_button != undefined && _button != null && _button.information != undefined && _button.information != null) { $("#select_wxc_information").val(_button.information); } setInformationUrl(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); // alert("Error: " + xmlHttpRequest.status); } }); } function loadCustomFormList() { $("#select_wxc_customForm").empty(); $("#select_wxc_customForm").attr("disabled", "disabled"); //var loadLayerIndex = layer.open({ // type: 2, // shadeClose: false, // content: '请稍候...' //}); var args = new Object(); args.Page = 1; args.PageSize = 1000; $.ajax({ url: "/Api/CustomForm/GetCustomFormList", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); // layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; $.each(resultObj.ItemList, function (idx, obj) { $("#select_wxc_customForm").append("<option value='" + obj.Id + "'>" + obj.Name + "</option>"); }); $("#select_wxc_customForm").removeAttr("disabled"); if (_button != undefined && _button != null && _button.customForm != undefined && _button.customForm != null) { $("#select_wxc_customForm").val(_button.customForm); } setCustomFormUrl(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); // alert("Error: " + xmlHttpRequest.status); } }); } function removeData() { var layerIndex = parent.layer.getFrameIndex(window.name); if (_mode == "modifyButton") { parent.removeButtonAndCloseLayer(layerIndex, _buttonIndex); } else if (_mode == "modifySubButton") { parent.removeSubButtonAndCloseLayer(layerIndex, _parentButtonIndex, _buttonIndex); } } function cancel() { var layerIndex = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 parent.layer.close(layerIndex); //再执行关闭 } </script> <div style="margin-left: 20px; margin-right: 20px; margin-top: 20px;"> <span id="spanTitle" class="font_black_24">添加菜单</span> </div> <div style="background-color: #ccc; margin-left: 20px; margin-right: 20px; margin-top: 10px; height: 1px;"> </div> <div style="position: absolute; overflow: auto; margin-top: 25px; left: 30px; right: 30px; bottom: 160px; top: 50px;"> <form id="form"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">类型:</td> <td> <select id="selectType" name="selectType" class="input_16" style="width: 96%;" keyenter="keyenter"> <option value="wxc_function">打开功能</option> <option value="wxc_campaign">打开活动</option> <option value="click">触发事件</option> <option value="wxc_information">分类信息</option> <option value="wxc_customForm">自定义表单</option> <option value="view">访问网址</option> <option value="mediaId">下发消息</option> </select> </td> </tr> </table> </form> <div id="divTableCollection"> <div id="div_wxc_function" buttontypediv="buttonTypeDiv" directurl="true"> <form id="form_wxc_function"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_wxc_function_name" name="txt_wxc_function_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">功能:</td> <td> <select id="select_wxc_function" name="select_wxc_function" class="input_16" style="width: 96%;" keyenter="keyenter"> <option value="portal" urlpath="Home/Portal">微主页</option> <option value="memberCenter" urlpath="Home/MemberCenter">会员中心</option> <option value="pointCommodity" urlpath="PointCommodity/PointCommodity">积分商城</option> <option value="pointCommodityOrderList" urlpath="PointCommodity/OrderList">积分订单</option> <option value="pointAccount" urlpath="Home/PointAccount">积分账户</option> <option value="cashAccount" urlpath="Pay/CashAccountTrack">现金账户</option> <option value="oneDollarBuying" urlpath="Campaign/OneDollarBuying">1元夺宝</option> <option value="personalInfo" urlpath="Home/PersonalInfo">个人信息</option> <option value="movieTimes" urlpath="Home/MovieTimes">电影排片</option> <option value="staff" urlpath="Staff/Home/Portal">后台入口</option> </select> </td> </tr> </table> </form> </div> <div id="div_view" buttontypediv="buttonTypeDiv" directurl="false"> <form id="form_view"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_view_name" name="txt_view_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">网址:</td> <td> <input id="txt_view_url" name="txt_view_url" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="256" /> </td> </tr> </table> </form> </div> <div id="div_wxc_campaign" buttontypediv="buttonTypeDiv" directurl="true"> <form id="form_wxc_campaign"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_wxc_campaign_name" name="txt_wxc_campaign_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">活动:</td> <td> <select id="select_wxc_campaign_type" name="select_wxc_campaign_type" class="input_16" style="width: 96%;" keyenter="keyenter"> <option value="1" urlpath="PictureVote">投票</option> <option value="2" urlpath="MemberQRCode">粉丝海报</option> <option value="3" urlpath="Lottery">定期抽奖</option> <option value="4" urlpath="LuckyTicket">聚人气抽奖</option> <option value="5" urlpath="ShakingLottery">摇一摇抽奖</option> <option value="6" urlpath="Donation">在线捐款</option> </select> </td> </tr> <tr> <td width="110" height="36"></td> <td> <select id="select_wxc_campaign" name="select_wxc_campaign" class="input_16" style="width: 96%;" keyenter="keyenter"></select> </td> </tr> </table> </form> </div> <div id="div_click" buttontypediv="buttonTypeDiv" directurl="false"> <form id="form_click"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_click_name" name="txt_click_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">事件:</td> <td> <select id="select_click_type" name="select_click_type" class="input_16" style="width: 96%;" keyenter="keyenter"> <option value="MemberQRCode">下发粉丝海报图片</option> </select> </td> </tr> <tr> <td width="110" height="36"></td> <td> <select id="select_click" name="select_click" class="input_16" style="width: 96%;" keyenter="keyenter"></select> </td> </tr> </table> </form> </div> <div id="div_wxc_information" buttontypediv="buttonTypeDiv" directurl="true"> <form id="form_wxc_information"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_wxc_information_name" name="txt_wxc_information_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">分类信息:</td> <td> <select id="select_wxc_information" name="select_wxc_information" class="input_16" style="width: 96%;" keyenter="keyenter"></select> </td> </tr> </table> </form> </div> <div id="div_wxc_customForm" buttontypediv="buttonTypeDiv" directurl="true"> <form id="form_wxc_customForm"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <input id="txt_wxc_customForm_name" name="txt_wxc_customForm_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </td> </tr> <tr> <td width="110" height="36">表单:</td> <td> <select id="select_wxc_customForm" name="select_wxc_customForm" class="input_16" style="width: 96%;" keyenter="keyenter"></select> </td> </tr> </table> </form> </div> <div id="div_mediaId" buttontypediv="buttonTypeDiv" directurl="false"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">名称:</td> <td> <form id="form_mediaId"> <input id="txt_mediaId_name" name="txt_mediaId_name" type="text" class="input_16" style="width: 96%;" keyenter="keyenter" maxlength="40" /> </form> </td> </tr> <tr> <td colspan="2"> @Helpers.MaterialSelect(false, true, true) </td> </tr> </table> </div> </div> </div> <div id="divDirectUrlArea" class="divBorder_lightgray" style="position: absolute; bottom: 75px; left: 20px; right: 20px; font-size: 13px; padding: 10px;"> 您也可以可通过微信官方后台将此 URL 添加到菜单: <div id="divUrl" style="word-wrap: break-word"> </div> </div> <div style="background-color: #ccc; position: absolute; bottom: 55px; left: 20px; right: 20px; height: 1px;"> </div> <div style="position: absolute; bottom: 15px; left: 20px; right: 20px;"> <div style="float: left;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" onclick="removeData()" style="display: none" /> </div> <div style="float: right"> <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保 存" onclick="save()" /> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" /> </div> <div style="clear: both"> </div> </div>
the_stack
@helper VipIcon() { <script> function vipIcon(){ layerAlert("只有 VIP 用户才可使用此功能。"); } </script> <span style="color:red;font-size:13px;font-style:italic;cursor:pointer" onclick="vipIcon()">VIP</span> } @helper InputForm() { <script type="text/html" id="divInputForm"> <div style="margin-left: 10px; margin-right: 10px; margin-top: 20px; margin-bottom: 10px;"> <div style="width: 100%;"> <div> <span style="margin-left: 20px;" id="spanInputFormTitle"></span> </div> <div style="width: 100%; margin-left: 0px; margin-top: 20px;"> <form id="formInputForm"> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="130" height="36"> <input name="txtInputForm_Text" type="text" class="input_16" style="width: 100%;" id="txtInputForm_Text" maxlength="100" /> </td> </tr> </table> </form> </div> <div style="width: 100%; margin-top: 20px; margin-left: 0px;"> <div style="float: right"> <input name="btnInputFormSave" type="button" class="btn_blue" id="btnInputFormSave" value="确 定" onclick="__inputFormSave()" /> <input name="btnInputFormCancel" type="button" class="btn_blue" id="btnInputFormCancel" value="取 消" onclick="__inputFormCancel()" /> </div> <div style="clear: both"> </div> </div> </div> </div> </script> <script type="text/javascript"> var __inputFormCallback; var __inputFormLayerIndex; var __inputFormRequired; var __inputFormDivHtml = $("#divInputForm").html(); function __showInputForm(callback,title,maxlength,required) { __inputFormCallback = callback; __inputFormRequired = required; __inputFormLayerIndex = layer.open({ type: 1, area: ['500px', '170px'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: __inputFormDivHtml, success: function (layero, index) { $("#spanInputFormTitle").html(title); $("#txtInputForm_Text").attr("maxlength",maxlength); $(layero).focus(); } }); } function __inputFormSave(){ if(__inputFormRequired){ if($("#formInputForm").validate({ onfocusout: false, onkeyup: false, showErrors: hightlightValidationErrors, rules: { "txtInputForm_Text": "required" }, messages: { "txtInputForm_Text": "*" } }).form() == false) return; } var text = $("#txtInputForm_Text").val(); layer.close(__inputFormLayerIndex); if (__inputFormCallback != undefined && __inputFormCallback != null) { __inputFormCallback(text); } } function __inputFormCancel() { layer.close(__inputFormLayerIndex); } </script> } @helper FileUpload() { <script type="text/javascript" src='/Scripts/jquery.form.js'></script> <script type="text/html" id="divUpload"> <div style="margin-left: 10px; margin-right: 10px; margin-top: 20px; margin-bottom: 10px;"> <div id="divFileUpload_Mask" style="display: none; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background-color: white"> <div style="margin-left: 30px; margin-top: 20px;">正在上传,请稍候...</div> </div> <div style="width: 100%;"> <div> <span class="font_blue_20">文件上传 </span> </div> <div style="width: 100%; margin-left: 0px; margin-top: 20px;"> <form id="formFileUpload"> <input type="hidden" id="txtFileUpload_Id" name="txtFileUpload_Id" /> <input type="hidden" id="txtFileUpload_UserId" name="txtFileUpload_UserId" /> <input type="hidden" id="txtFileUpload_Domain" name="txtFileUpload_Domain" /> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="130" height="36"> <input name="txtFileUpload_Name" type="file" class="input_16" style="width: 100%;" id="txtFileUpload_Name" /> </td> </tr> <tr> <td height="36"> <a href="http://docs.shengxunwei.com/Home/Browser/wxcm/003c0be0-ad31-4ef6-a4fa-9983f5655e60/d33ea213-09ce-4168-afd3-119068e46b39" target="_blank">上传图片文件之前请压缩图片以提高访问速度,点击查看</a> </td> </tr> </table> </form> </div> <div style="width: 100%; margin-top: 20px; margin-left: 0px;"> <div style="float: right"> <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="上 传" onclick="__fileUpload()" /> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="__closeFileUpload()" /> </div> <div style="clear: both"> </div> </div> </div> </div> </script> <script type="text/javascript"> var __fileUploadDivHtml; var __fileUploadLayerIndex; var __fileServiceAddress;//= "http://localhost:8012/"; //var _resultDomId; var __fileUploadCallback; var __fileUploadArgs; $(document).ready(function () { __fileUploadDivHtml = $("#divUpload").html(); $("#divUpload").html(""); }); function __showFileUpload(callback, fileUploadArgs) { //_resultDomId = resultDomId; __fileUploadCallback = callback; if (fileUploadArgs != undefined && fileUploadArgs != null) { __fileUploadArgs = fileUploadArgs; } else { __fileUploadArgs = new Object(); __fileUploadArgs.uploadMethod = "Upload"; __fileUploadArgs.getUploadResultApi = "/Api/Settings/GetFileUploadResult?fileId={0}"; } __fileUploadLayerIndex = layer.open({ type: 1, area: ['500px', '220px'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: __fileUploadDivHtml, success: function (layero, index) { $(layero).focus(); //请求文件上传参数 __getFileUploadParameter(function () { //跨域上传,通过HTTP返回代码判断结果 $("#formFileUpload").submit(function () { //alert($("#txtFileUpload_Id").val()); $("#formFileUpload").ajaxSubmit({ type: "post", dataType: "json", url: __fileServiceAddress + "File/" + __fileUploadArgs.uploadMethod, success: function (data) { __getUploadResult(); }, error: function (msg) { __getUploadResult(); //IE下虽然进ERROR,但返回200 //CHROME下连200状态都得不到,返回0 //alert("error:" + msg.status); ////{ "readyState": 4, "responseText": "", "status": 200, "statusText": "OK" } //if (msg.status == 200) //{ // var url = __fileServiceAddress + "File/Get?id=" + $("#txtFileUpload_Id").val(); // $("#" + resultDomId).val(url); // layer.close(__fileUploadLayerIndex); // if (callback != null && callback != undefined) // { // callback(); // } //} //else //{ // //alert(JSON.stringify(msg)); // alert(msg.responseText); //} } }); return false; }); }); } }); } function __getUploadResult() { var url = String.format(__fileUploadArgs.getUploadResultApi, $("#txtFileUpload_Id").val()); //alert(url); $.ajax({ url: url,//__fileUploadArgs.getUploadResultApi + "?fileId=" + $("#txtFileUpload_Id").val(), type: "POST", //如果用GET要注意浏览器缓存 dataType: "json", success: function (data, status, jqXHR) { //alert(JSON.stringify(data)); //FileUploadResult if (data.Success) { // var url = __fileServiceAddress + data.StoreFilePath; //$("#" + _resultDomId).val(url); layer.close(__fileUploadLayerIndex); if (__fileUploadCallback != undefined && __fileUploadCallback != null) { //__fileUploadCallback(__fileServiceAddress, data.Data); __fileUploadCallback(__fileServiceAddress, data); } } else { $("#divFileUpload_Mask").hide(); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { alert("Error: " + xmlHttpRequest.status); } }); } function __closeFileUpload() { layer.close(__fileUploadLayerIndex); } function __fileUpload() { var fileName = $("#txtFileUpload_Name").val(); if (fileName == "") { layerAlert("请选择要上传的文件。"); return; } var fileExtName = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();//获得文件后缀名 if (fileExtName != '.jpeg' && fileExtName != '.jpg' && fileExtName != '.gif' && fileExtName != '.png') { layerAlert("请上传图片文件,您可以上传的文件类型:jpeg,jpg,gif,png。"); return; } $("#divFileUpload_Mask").show(); $("#formFileUpload").submit(); } function __getFileUploadParameter(callback) { var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/UserContext/GetFileUploadParameter", type: "POST", //如果用GET要注意浏览器缓存 dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var parameter = data.Data; $("#txtFileUpload_Id").val(parameter.Id); $("#txtFileUpload_UserId").val(parameter.UserId); $("#txtFileUpload_Domain").val(parameter.DomainId); __fileServiceAddress = parameter.FileService; //alert(__fileServiceAddress); callback(); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } </script> } @helper MaterialSelect(bool text, bool image, bool article) { <style type="text/css"> .divImageMaterialContainer { width: 170px; background-color: #FFF; } .tableImageMaterialContainer { width: 100%; border-collapse: collapse; border: solid #E7E7EB; border-width: 1px 0 0 1px; } .tableImageMaterialContainer td { border: 1px solid #E7E7EB; } .divArticleMaterialContainer { width: 230px; background-color: #FFF; font-size: 13px; } .tableArticleMaterialContainer { width: 100%; border-collapse: collapse; border: solid #E7E7EB; border-width: 1px 0 0 1px; } .tableArticleMaterialContainer td { border: 1px solid #E7E7EB; } .tableNoBorder { border: 0px; } .tableNoBorder td { border: 0px; } .divFirstArticleTitle { position: absolute; line-height: 24px; padding-left: 7px; vertical-align: middle; left: 0px; right: 0px; bottom: 0px; height: 24px; background-color: #000000; color: white; filter: alpha(opacity=70); -moz-opacity: 0.7; -khtml-opacity: 0.7; opacity: 0.7; } .divArticleFirstItem { border: 2px solid #FFF; position: relative; height: 100px; } .divArticleItem { margin-top: 10px; margin-left: 5px; margin-right: 5px; border: 2px solid #FFF; } .divArticleItemActive { border: 2px solid skyblue; } </style> <script id="articleTemplate" type="text/html"> <div class="divArticleMaterialContainer"> <table class="tableArticleMaterialContainer"> <tr> <td valign="top"> <div> <div> <div class="divArticleFirstItem"> <div style="position: absolute; left: 0px; right: 0px; height: 100px; overflow: hidden"> <img src="{{ d[0].thumbUrl }}" style="width: 100%;"> </div> <div class="divFirstArticleTitle"> <a style="color: white" target="_blank" href="{{ d[0].url }}">{{ d[0].title }}</a> </div> </div> {{# for(var i = 1, len = d.length; i < len; i++){ }} <div class="divDotLine" style="margin-top: 10px;"> </div> <div class="divArticleItem"> <table class="tableNoBorder" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <a style="color: black" target="_blank" href="{{ d[i].url }}">{{ d[i].title }}</a> </td> <td width="75" align="right"> <img src="{{ d[i].thumbUrl }}" width="70" height="70"> </td> </tr> </table> </div> {{# } }} </div> </td> </tr> <tr> <td height="30" valign="middle" bgcolor="#F4F5F9"> <div> <div style="float: right; margin-right: 10px;"> <img src="/Content/Images/ico_remove.jpg" width="20" height="20" onclick="__removeMaterialArticle()"> </div> <div style="clear: both"></div> </div> </td> </tr> </table> </div> </script> <script id="tableMaterialImageTemplate" type="text/html"> <div class="divImageMaterialContainer"> <table class="tableImageMaterialContainer"> <tr> <td height="150" align="center"> <img style="max-width: 166px; max-height: 100%" src="{{ d.Url }}" /> </td> </tr> <tr> <td height="30" style="word-wrap: break-word; word-break: break-all;"> <span class="font_gray_15" style="margin-left: 10px;">{{ d.Name }}</span> </td> </tr> <tr> <td height="30" valign="middle" bgcolor="#F4F5F9"> <div> @*<div style="float: left; margin-left: 10px;"> <img src="/Content/Images/ico_edit.jpg" width="20" height="20"> </div>*@ <div style="float: right; margin-right: 10px;"> <img src="/Content/Images/ico_remove.jpg" width="20" height="20" onclick="__removeMaterialImage()"> </div> <div style="clear: both"></div> </div> </td> </tr> </table> </div> </script> <script type="text/javascript"> var __materialSelectAllowedText = @text.ToString().ToLower(); var __materialSelectAllowedImage = @image.ToString().ToLower(); var __materialSelectAllowedArticle = @article.ToString().ToLower(); //0文字 1图片 2图文 var __materialType = -1; //选择的图像对象 var __materialImage; var __materialArticleId; //选择图片或图文时,此处为mediaId var __materialSelect_mediaId; //选择图片或图文时,此处为本地Id var __materialSelect_materialId; var __materialSelectValidator_text; var __materialSelectValidator_image; var __materialSelectValidator_article; var __settedMaterial = false; $(document).ready(function () { __materialSelectValidator_text = $("#form_materialSelect_text").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtMaterialSelectTextContent": "required" }, messages: { "txtMaterialSelectTextContent": "请输入文字内容;" } }); __materialSelectValidator_image = $("#form_materialSelect_image").validate({ ignore: "", // 开启hidden验证, 1.9版本后默认关闭 onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtMaterialSelectImageMediaId": "required" }, messages: { "txtMaterialSelectImageMediaId": "请选择图片;" } }); __materialSelectValidator_article = $("#form_materialSelect_article").validate({ ignore: "", // 开启hidden验证, 1.9版本后默认关闭 onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtMaterialSelectArticleId": "required" }, messages: { "txtMaterialSelectArticleId": "请选择图文;" } }); if(__settedMaterial==false){ if(__materialSelectAllowedText){ __switchMaterialText(); }else if(__materialSelectValidator_image){ __switchMaterialImage(); } else if(__materialSelectValidator_article){ __switchMaterialArticle(); } } }); function __validateMaterialSelect() { //if (__materialType == -1) { // layerAlert("请选择资源。", function () { return false;}); //} switch (__materialType) { case 0: //文字 return __materialSelectValidator_text.form(); case 1: //图片 return __materialSelectValidator_image.form(); case 2: //图文 return __materialSelectValidator_article.form(); default: alert("验证失败"); break; } } function __setMaterial(materialType,text,materialId) { __settedMaterial = true; switch (materialType) { case 0: __showMaterialText(text); __switchMaterialText(); break; case 1: __loadMaterialImage(materialId); __switchMaterialImage(); break; case 2: __loadMaterialArticle(materialId); __switchMaterialArticle(); break; default: alert("未知 MaterialType"); break; } } function __loadMaterialImage(id) { var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Material/GetNormalMaterial?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { //图文素材被删除后返回null if (data.Data != null) { // alert(JSON.stringify(data.Data)); __materialImage = new Object(); __materialImage.Id = data.Data.Id; __materialImage.Name = data.Data.Name; __materialImage.MediaId = data.Data.MediaId; __materialImage.Url = data.Data.Url; __materialSelect_materialId = data.Data.Id; __materialSelect_mediaId = data.Data.MediaId; $("#txtMaterialSelectImageMediaId").val(__materialSelect_mediaId); var gettpl = document.getElementById('tableMaterialImageTemplate').innerHTML; laytpl(gettpl).render(data.Data, function (html) { document.getElementById('divMaterialImage_Image').innerHTML = html; }); $("#divMaterialImage_Select").hide(); $("#divMaterialImage_Image").show(); } else { //TODO:应该要有删除按钮,否则没法再选了 document.getElementById('divMaterialImage_Image').innerHTML = "指定的图片素材不存在,请确认是否已被删除。"; } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function __loadMaterialArticle(id) { __materialArticleId = id; $("#txtMaterialSelectArticleId").val(id); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Material/GetArticleMaterial?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { //图文素材被删除后返回null if (data.Data != null) { __materialSelect_materialId = data.Data.id; __materialSelect_mediaId = data.Data.mediaId; var gettpl = document.getElementById('articleTemplate').innerHTML; laytpl(gettpl).render(data.Data.articles, function (html) { $("#divMaterialArticle_Select").hide(); $("#divMaterialArticle_Article").show(); document.getElementById('divMaterialArticle_Article').innerHTML = html; }); } else { //TODO:要能删除重选 document.getElementById('divMaterialArticle_Article').innerHTML = "指定的图文素材不存在,请确认是否已被删除。"; } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function __switchMaterialText() { __materialType = 0; $("#divMaterialTab_Text").show(); $("#divMaterialTab_Image").hide(); $("#divMaterialTab_Article").hide(); $("#imgMaterialTitle_Text").attr("src", "/Content/Images/ico_edit2.jpg"); $("#spanMaterialTitle_Text").attr("class", "font_black_16"); $("#imgMaterialTitle_Image").attr("src", "/Content/Images/ico_image.jpg"); $("#spanMaterialTitle_Image").attr("class", "font_gray_16"); $("#imgMaterialTitle_Article").attr("src", "/Content/Images/ico_image.jpg"); $("#spanMaterialTitle_Article").attr("class", "font_gray_16"); } function __switchMaterialImage() { __materialType = 1; $("#divMaterialTab_Text").hide(); $("#divMaterialTab_Image").show(); $("#divMaterialTab_Article").hide(); $("#imgMaterialTitle_Text").attr("src", "/Content/Images/ico_edit.jpg"); $("#spanMaterialTitle_Text").attr("class", "font_gray_16"); $("#imgMaterialTitle_Image").attr("src", "/Content/Images/ico_image2.jpg"); $("#spanMaterialTitle_Image").attr("class", "font_black_16"); $("#imgMaterialTitle_Article").attr("src", "/Content/Images/ico_image.jpg"); $("#spanMaterialTitle_Article").attr("class", "font_gray_16"); if (__materialImage != undefined && __materialImage != null && __materialImage.MediaId != null) { $("#divMaterialImage_Select").hide(); $("#divMaterialImage_Image").show(); } else { $("#divMaterialImage_Select").show(); $("#divMaterialImage_Image").hide(); } } function __switchMaterialArticle() { __materialType = 2; $("#divMaterialTab_Text").hide(); $("#divMaterialTab_Image").hide(); $("#divMaterialTab_Article").show(); $("#imgMaterialTitle_Text").attr("src", "/Content/Images/ico_edit.jpg"); $("#spanMaterialTitle_Text").attr("class", "font_gray_16"); $("#imgMaterialTitle_Image").attr("src", "/Content/Images/ico_image.jpg"); $("#spanMaterialTitle_Image").attr("class", "font_gray_16"); $("#imgMaterialTitle_Article").attr("src", "/Content/Images/ico_image2.jpg"); $("#spanMaterialTitle_Article").attr("class", "font_black_16"); } function __showMaterialImageSelect() { layer.open({ type: 2, area: ['760px', '450px'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: '/Material/ImageSelect' }); } function __selectMaterialImageResult(image, layerIndex) { if (layerIndex != undefined && layerIndex != null) { layer.close(layerIndex); } __showMaterialImage(image); $("#divMaterialImage_Select").hide(); $("#divMaterialImage_Image").show(); } function __showMaterialImage(image) { __materialImage = image; __materialSelect_materialId = __materialImage.Id; __materialSelect_mediaId = __materialImage.MediaId; $("#txtMaterialSelectImageMediaId").val(__materialImage.MediaId); var gettpl = document.getElementById('tableMaterialImageTemplate').innerHTML; laytpl(gettpl).render(image, function (html) { document.getElementById('divMaterialImage_Image').innerHTML = html; }); } function __removeMaterialImage() { __materialImage = null; __materialSelect_materialId = null; __materialSelect_mediaId = null; $("#txtMaterialSelectImageMediaId").val(""); $("#divMaterialImage_Select").show(); $("#divMaterialImage_Image").hide(); } function __showMaterialText(content) { $("#txtMaterialSelectTextContent").val(content); } function __getMaterialText() { return $("#txtMaterialSelectTextContent").val(); } function __showMaterialArticleSelect() { layer.open({ type: 2, area: ['860px', '550px'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: '/Material/ArticleSelect' }); } function __selectMaterialArticleResult(id, layerIndex) { if (layerIndex != undefined && layerIndex != null) { layer.close(layerIndex); } __loadMaterialArticle(id); } function __removeMaterialArticle() { __materialArticleId = null; __materialSelect_materialId = null; __materialSelect_mediaId = null; $("#txtMaterialSelectArticleId").val(""); $("#divMaterialArticle_Select").show(); $("#divMaterialArticle_Article").hide(); } </script> <div> <div style="margin-top: 20px;"> @if (text) { <div id="divTitle_Text" style="float: left; cursor: pointer; margin-right: 20px;" onclick="__switchMaterialText()"> <img id="imgMaterialTitle_Text" src="/Content/Images/ico_edit2.jpg" /> <span class="font_black_16" id="spanMaterialTitle_Text"> 文字 </span> </div> } @if (image) { <div id="divTitle_Image" style="float: left; cursor: pointer; margin-right: 20px;" onclick="__switchMaterialImage()"> <img id="imgMaterialTitle_Image" src="/Content/Images/ico_image.jpg" /> <span class="font_gray_16" id="spanMaterialTitle_Image"> 图片 </span> </div> } @if (article) { <div id="divTitle_Article" style="float: left; cursor: pointer; margin-right: 20px;" onclick="__switchMaterialArticle()"> <img id="imgMaterialTitle_Article" src="/Content/Images/ico_image.jpg" /> <span class="font_gray_16" id="spanMaterialTitle_Article"> 图文消息 </span> </div> } <div style="clear: both"></div> </div> <div id="divMaterialTab_Text" class="divBorder_gray" style="margin-top: 20px; display: none"> <form id="form_materialSelect_text"> @*关键词自动回复中长度限制是300,不过是独立画面设置的,用的不是这个*@ <textarea name="txtMaterialSelectTextContent" rows="6" class="input_18_noBorder" id="txtMaterialSelectTextContent" maxlength="600"></textarea> </form> </div> <div id="divMaterialTab_Image" class="divBorder_gray" style="margin-top: 20px; display: none"> <form id="form_materialSelect_image"> <input type="hidden" id="txtMaterialSelectImageMediaId" name="txtMaterialSelectImageMediaId" /> <div id="divMaterialImage_Select"> <div class="divDotBorder_gray" style="width: 150px; height: 150px; cursor: pointer" onclick="__showMaterialImageSelect()"> <table height="100%" style="vertical-align: middle" width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="middle"> <div> <img src="/Content/Images/plus.jpg" width="35" height="35"> </div> <div style="margin-top: 10px;"> 从素材库选择 </div> </td> </tr> </table> </div> </div> <div id="divMaterialImage_Image"> </div> </form> </div> <div id="divMaterialTab_Article" class="divBorder_gray" style="margin-top: 20px; display: none"> <form id="form_materialSelect_article"> <input type="hidden" id="txtMaterialSelectArticleId" name="txtMaterialSelectArticleId" /> <div id="divMaterialArticle_Select"> <div class="divDotBorder_gray" style="width: 150px; height: 150px; cursor: pointer" onclick="__showMaterialArticleSelect()"> <table height="100%" style="vertical-align: middle" width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="middle"> <div> <img src="/Content/Images/plus.jpg" width="35" height="35"> </div> <div style="margin-top: 10px;"> 从素材库选择 </div> </td> </tr> </table> </div> </div> <div id="divMaterialArticle_Article"> </div> </form> </div> </div> } @helper CampaignBaseEdit() { <form id="formCampaign"> <input type="hidden" id="txtId" /> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="200" height="36">名称:</td> <td> <input id="txtName" name="txtName" type="text" class="input_16" style="width: 96%;" maxlength="50" /> </td> </tr> <tr> <td height="36">简要说明:</td> <td> <textarea name="txtIntroduction" rows="3" class="input_16" id="txtIntroduction" style="width: 96%;" maxlength="150"></textarea> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 显示在标题下方的简短说明。 </div> </td> </tr> <tr> <td height="36">详细说明:</td> <td> <div style="width:96%"> <div id="divDescriptionEditor" style='height:300px; '></div> </div> </td> </tr> <tr> <td>&nbsp;</td> <td> <div style="width:96%;"> <div style="float:right;"> <input name="btnUpload" type="button" class="btn_white" id="btnUpload" value="上传图片" onclick="uploadDescriptionFile()" /> </div> <div style="clear:both"></div> </div> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 说明内容将显示在活动的介绍页面上。 </div> </td> </tr> <tr> <td valign="top"> <div style="margin-top: 5px;"> 分享小图片: </div> </td> <td valign="top"> <div class="divBorder_gray" style="margin-bottom:5px;width:96%;"> <div style="padding:5px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110"> <img id="shareImage" src="" alt="" style="max-height:100px;" /> </td> <td align="right"> <input id="txtShareImageUrl" name="txtShareImageUrl" type="hidden" class="input_16" style="width: 96%;" maxlength="500" /> <a href="javascript:void(0)" onclick="uploadShareImage()">上传新图片</a><br /> <a href="javascript:void(0)" onclick="removeShareImage()">删除图片</a> </td> </tr> </table> </div> </div> </td> </tr> @*<tr> <td height="36">&nbsp;</td> <td> <input id="txtShareImageUrl" name="txtShareImageUrl" type="text" class="input_16" style="width: 96%;" maxlength="500" /> </td> </tr>*@ <tr> <td></td> <td valign="top"> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 在微信中分享活动时,使用的正方形小图片。 </div> </td> </tr> <tr> <td width="140" height="36">分享到朋友圈标题:</td> <td> <input id="txtShareTimelineTitle" name="txtShareTimelineTitle" type="text" class="input_16" style="width: 96%;" maxlength="50" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享到朋友圈时显示的标题文字。 </div> </td> </tr> <tr> <td width="140" height="36">分享给好友标题:</td> <td> <input id="txtShareAppMessageTitle" name="txtShareAppMessageTitle" type="text" class="input_16" style="width: 96%;" maxlength="50" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享给好友时显示的标题文字。 </div> </td> </tr> <tr> <td width="140" height="36">分享给好友描述:</td> <td> <input id="txtShareAppMessageDescription" name="txtShareAppMessageDescription" type="text" class="input_16" style="width: 96%;" maxlength="100" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 将活动页面分享给好友时显示的标题下方的一段描述文字。 </div> </td> </tr> <tr> <td valign="top"> <div style="margin-top: 5px;"> 主题图片: </div> </td> <td valign="top"> <div class="divBorder_gray" style="margin-bottom:5px;width:96%;"> <div style="padding:5px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="310"> <img id="image" src="" alt="" style="max-width: 300px;" /> </td> <td align="right"> <input id="txtImageUrl" name="txtImageUrl" type="hidden" class="input_16" style="width: 96%;" maxlength="500" /> <a href="javascript:void(0)" onclick="uploadImage()">上传新图片</a><br /> <a href="javascript:void(0)" onclick="removeImage()">删除图片</a> </td> </tr> </table> </div> </div> </td> </tr> <tr> <td></td> <td valign="top"> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 活动的主题图片。 </div> </td> </tr> <tr> <td height="36">仅关注者可参与:</td> <td> <select id="selectOnlyMember" name="selectOnlyMember" class="input_16" style="width: 130px;"> <option value="true">是</option> <option value="false">否</option> </select> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 当仅关注者才可参与时,未关注公众号者将被引导到“引导关注页面”。 </div> </td> </tr> <tr> <td width="140" height="36">分享朋友圈奖励积分:</td> <td> <input id="txtShareTimelinePoint" name="txtShareTimelinePoint" type="text" class="input_16" style="width: 130px;" value="1" /> </td> </tr> <tr> <td width="140" height="36">分享好友奖励积分:</td> <td> <input id="txtShareAppMessagePoint" name="txtShareAppMessagePoint" type="text" class="input_16" style="width: 130px;" value="1" /> </td> </tr> <tr> <td width="140" height="36">引导关注页面:</td> <td> <input id="txtGuideSubscribeUrl" name="txtGuideSubscribeUrl" type="text" class="input_16" style="width: 96%;" maxlength="500" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 如果留空,将以全局设置为准,也可以在此指定一个针对本活动的特殊引导关注页面。 </div> </td> </tr> <tr> <td width="140" height="36">备注:</td> <td> <input id="txtRemark" name="txtRemark" type="text" class="input_16" style="width: 96%;" maxlength="250" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 内部备注,关注者不可见。 </div> </td> </tr> <tr> <td width="140" height="36">最大参与人数:</td> <td> <input id="txtMaxParticipant" name="txtMaxParticipant" type="text" class="input_16" style="width: 130px;" value="0" /> </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 最多允许参与的人数,输入 0 表示不限制。 </div> </td> </tr> </table> </form> <link rel="stylesheet" type="text/css" href="/Scripts/wangEditor/css/wangEditor.min.css"> <script type="text/javascript" src='/Scripts/wangEditor/js/wangEditor.min.js'></script> <style> .wangEditor-container .wangEditor-txt p, .wangEditor-container .wangEditor-txt h1, .wangEditor-container .wangEditor-txt h2, .wangEditor-container .wangEditor-txt h3, .wangEditor-container .wangEditor-txt h4, .wangEditor-container .wangEditor-txt h5 { margin: 0px 0; line-height: 1.8; } </style> <script type="text/javascript"> var _campaign; var _editor; var _campaignBaseInfoValidator; $(document).ready(function () { $("#txtShareImageUrl").blur(function () { loadShareImage(); }); $("#txtImageUrl").blur(function () { loadImage(); }); _editor = new wangEditor('divDescriptionEditor'); _editor.config.menus = [ 'source', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor', '|','quote','fontfamily','fontsize','head','unorderlist','orderlist','alignleft','aligncenter','alignright', '|','link','unlink','table', '|','undo','redo','fullscreen' ]; _editor.create(); _campaignBaseInfoValidator = $("#formCampaign").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txtName": "required", "txtImageUrl": "required", "txtShareImageUrl": "required", "txtShareTimelineTitle":"required", "txtShareAppMessageTitle":"required", "txtShareAppMessageDescription":"required", "txtShareTimelinePoint": { required: true, number: true, digits: true, range: [0, 1000] }, "txtShareAppMessagePoint": { required: true, number: true, digits: true, range: [0, 1000] }, "txtMaxParticipant": { required: true, number: true, digits: true, range: [0, 99999] } }, messages: { "txtName": "请输入名称;", "txtImageUrl": "请选择主题图片;", "txtShareImageUrl": "请选择分享小图片;", "txtShareTimelineTitle":"请输入分享到朋友圈标题;", "txtShareAppMessageTitle":"请输入分享给好友标题;", "txtShareAppMessageDescription":"请输入分享给好友描述;", "txtShareTimelinePoint": { required: "请输入分享朋友圈奖励积分;", number: "分享朋友圈奖励积分请输入有效整数字;", digits: "分享朋友圈奖励积分请输入有效整数字;", range: "分享朋友圈奖励积分值请介于 0 到 1000 之间;" }, "txtShareAppMessagePoint": { required: "请输入分享好友奖励积分;", number: "分享好友奖励积分请输入有效整数字;", digits: "分享好友奖励积分请输入有效整数字;", range: "分享好友奖励积分值请介于 0 到 1000 之间;" }, "txtMaxParticipant": { required: "请输入最大参与人数;", number: "最大参与人数请输入有效整数字;", digits: "最大参与人数请输入有效整数字;", range: "最大参与人数请介于 0 到 99999 之间;" } } }); }); function uploadShareImage() { __showFileUpload(getUploadShareImageResult); } function getUploadShareImageResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; $("#txtShareImageUrl").val(url); loadShareImage(); } function loadShareImage() { $("#shareImage").attr("src", $("#txtShareImageUrl").val()); } function removeShareImage() { $("#txtShareImageUrl").val(""); loadShareImage(); } ////////// function uploadImage() { __showFileUpload(getUploadImageResult); } function getUploadImageResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; $("#txtImageUrl").val(url); loadImage(); } function loadImage() { $("#image").attr("src", $("#txtImageUrl").val()); } function removeImage() { $("#txtImageUrl").val(""); loadImage(); } ////详细图片 function uploadDescriptionFile() { __showFileUpload(getUploadDescriptionFileResult); } function getUploadDescriptionFileResult(fileServiceAddress, result) { var url = fileServiceAddress + result.Data.StoreFilePath; _editor.$txt.append("<img src='" + url + "' style='max-width:100%' />"); } function getCampaign() { if (_campaign == undefined || _campaign == null) { _campaign = new Object(); } var id = $("#txtId").val(); if (id != undefined && id != "") { _campaign.Id = id; } _campaign.Name = $("#txtName").val(); //_campaign.Introduction = $('#txtIntroduction').val(); _campaign.Introduction = $("#txtIntroduction").val().replace(new RegExp("\n", "gm"), "<br/>"); _campaign.Description = _editor.$txt.html(); _campaign.ShareImageUrl = $("#txtShareImageUrl").val(); _campaign.ShareTimelineTitle = $("#txtShareTimelineTitle").val(); _campaign.ShareAppMessageTitle = $("#txtShareAppMessageTitle").val(); _campaign.ShareAppMessageDescription = $("#txtShareAppMessageDescription").val(); _campaign.ImageUrl = $("#txtImageUrl").val(); _campaign.OnlyMember = $("#selectOnlyMember").val(); _campaign.GuideSubscribeUrl = $("#txtGuideSubscribeUrl").val(); _campaign.ShareTimelinePoint = $("#txtShareTimelinePoint").val(); _campaign.ShareAppMessagePoint = $("#txtShareAppMessagePoint").val(); _campaign.Remark = $("#txtRemark").val(); _campaign.MaxParticipant = $("#txtMaxParticipant").val(); return _campaign; } function setCampaign(campaign) { _campaign = campaign; $("#txtId").val(campaign.Id); $("#txtName").val(campaign.Name); //$("#txtIntroduction").val(campaign.Introduction); $("#txtIntroduction").val(campaign.Introduction.replace(new RegExp("<br/>", "gm"), "\n")); _editor.$txt.html(campaign.Description) $("#txtShareImageUrl").val(campaign.ShareImageUrl); $("#txtShareTimelineTitle").val(campaign.ShareTimelineTitle); $("#txtShareAppMessageTitle").val( campaign.ShareAppMessageTitle); $("#txtShareAppMessageDescription").val(campaign.ShareAppMessageDescription); $("#txtImageUrl").val(campaign.ImageUrl); $("#selectOnlyMember").find("option[value='" + campaign.OnlyMember + "']").attr("selected", true); $("#txtGuideSubscribeUrl").val(campaign.GuideSubscribeUrl); $("#txtShareTimelinePoint").val(campaign.ShareTimelinePoint); $("#txtShareAppMessagePoint").val(campaign.ShareAppMessagePoint); $("#txtRemark").val(campaign.Remark); $("#txtMaxParticipant").val(campaign.MaxParticipant); loadImage(); loadShareImage(); } function setOnlyMember() { $("#selectOnlyMember").find("option[value='true']").attr("selected", true); $("#selectOnlyMember").attr("disabled", "disabled"); } </script> } @helper MemberSelect() { <script type="text/javascript"> var __member; function __selectMember(){ layer.open({ type: 2, area: ['100%', '100%'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: '/Member/MemberSelect' }); } function __selectMemberResult(member, layerIndex) { if (layerIndex != undefined && layerIndex != null) { layer.close(layerIndex); } __showMember(member); } function __showMember(member){ __member = member; $("#__imgMemberHeadimgurl").attr("src",member.Headimgurl); $("#__spanMemberNickName").html(member.NickName); } function __clearMember(){ __member = null; $("#__imgMemberHeadimgurl").attr("src",""); $("#__spanMemberNickName").html(""); } function __setMember(id) { var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Member/GetMember?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { //图文素材被删除后返回null if (data.Data != null) { __showMember(data.Data); } else { __clearMember(); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } </script> <div class="divBorder_gray" style="width:100%; "> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="60" valign="middle"><img id="__imgMemberHeadimgurl" style="width:46px;" /></td> <td><span id="__spanMemberNickName"></span></td> <td valign="middle" align="right" width="160"> <input name="btnMemberSelect" type="button" class="btn_white" id="btnMemberSelect" value="选择" onclick="__selectMember()" /> <input name="btnMemberClear" type="button" class="btn_white" id="btnMemberClear" value="清除" onclick="__clearMember()" /> </td> </tr> </table> </div> } @helper AdvertisingSelect(string key) { <script type="text/javascript"> var __advertising@(key); function __selectAdvertising@(key)(){ layer.open({ type: 2, area: ['900px', '100%;'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: '/Settings/AdvertisingSelect?key=@(key)' }); } function ____selectAdvertisingResult@(key)(advertising, layerIndex) { if (layerIndex != undefined && layerIndex != null) { layer.close(layerIndex); } __showAdvertising@(key)(advertising); } function __showAdvertising@(key)(advertising){ __advertising@(key) = advertising; $("#__imgAdvertisingImage@(key)").attr("src",advertising.ImageUrl); $("#__spanAdvertisingName@(key)").html(advertising.Name); } function __clearAdvertising@(key)(){ __advertising@(key) = null; $("#__imgAdvertisingImage@(key)").attr("src",""); $("#__spanAdvertisingName@(key)").html(""); } function __setAdvertising@(key)(id) { var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Advertising/GetAdvertising?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { //图文素材被删除后返回null if (data.Data != null) { __showAdvertising@(key)(data.Data); } else { __clearAdvertising@(key)(); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } </script> <div class="divBorder_gray" style="width:100%; "> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="60" valign="middle"><img id="__imgAdvertisingImage@(key)" style="max-width:300px;" /></td> <td><span id="__spanAdvertisingName@(key)" style="margin-left:10px;"></span></td> <td valign="middle" align="right" width="160"> <input name="btnMemberSelect" type="button" class="btn_white" id="btnMemberSelect" value="选择" onclick="__selectAdvertising@(key)()" /> <input name="btnMemberClear" type="button" class="btn_white" id="btnMemberClear" value="清除" onclick="__clearAdvertising@(key)()" /> </td> </tr> </table> </div> }
the_stack
@{ ViewBag.Title = "Index"; Layout = null; } <!-- > Muaz Khan - https://github.com/muaz-khan > MIT License - https://www.webrtc-experiment.com/licence/ > Documentation - https://github.com/muaz-khan/RecordRTC > and - RecordRTC.org --> <!DOCTYPE html> <html lang="en"> <head> <title>RecordRTC to ASP.NET MVC | Muaz Khan</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <link rel="author" type="text/html" href="https://plus.google.com/+MuazKhan"> <meta name="author" content="Muaz Khan"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="stylesheet" href="https://cdn.webrtc-experiment.com/style.css"> <style> audio { vertical-align: bottom; width: 10em; } video { vertical-align: top;max-width: 100%; } input { border: 1px solid #d9d9d9; border-radius: 1px; font-size: 2em; margin: .2em; width: 30%; } p, .inner { padding: 1em; } li { border-bottom: 1px solid rgb(189, 189, 189); border-left: 1px solid rgb(189, 189, 189); padding: .5em; } label { display: inline-block; width: 8em; } </style> <script> document.createElement('article'); document.createElement('footer'); </script> <!-- script used for audio/video/gif recording --> <script src="https://cdn.webrtc-experiment.com/RecordRTC.js"> </script> </head> <body> <article> <header style="text-align: center;"> <h1> RecordRTC to ASP.NET MVC </h1> <p> <a href="https://www.webrtc-experiment.com/">HOME</a> <span> &copy; </span> <a href="http://www.MuazKhan.com/" target="_blank">Muaz Khan</a> . <a href="http://twitter.com/WebRTCWeb" target="_blank" title="Twitter profile for WebRTC Experiments">@@WebRTCWeb</a> . <a href="https://github.com/muaz-khan?tab=repositories" target="_blank" title="Github Profile">Github</a> . <a href="https://github.com/muaz-khan/RecordRTC/issues?state=open" target="_blank">Latest issues</a> . <a href="https://github.com/muaz-khan/RecordRTC/commits/master" target="_blank">What's New?</a> </p> </header> <div class="github-stargazers"></div> <section class="experiment"> <h2 class="header">Record and POST to Server! ( <a href="http://www.recordrtc.org/" title="Suggested to visit for RecordRTC demos and API Documentations">www.RecordRTC.org</a> )</h2> <p style="text-align:center;"> <video id="preview" controls style="border: 1px solid rgb(15, 158, 238); height: 240px; width: 320px;"></video> </p> <hr /> <button id="record">Record</button> <button id="stop" disabled>Stop</button> <button id="delete" disabled>Delete your webm/wav files from Server</button> <div id="container" style="padding:1em 2em;"></div> </section> <script> // PostBlob method uses XHR2 and FormData to submit // recorded blob to the PHP server function PostBlob(blob) { // FormData var formData = new FormData(); formData.append('video-filename', fileName); formData.append('video-blob', blob); // progress-bar var hr = document.createElement('hr'); container.appendChild(hr); var strong = document.createElement('strong'); strong.id = 'percentage'; strong.innerHTML = 'Video upload progress: '; container.appendChild(strong); var progress = document.createElement('progress'); container.appendChild(progress); // POST the Blob using XHR2 xhr('/RecordRTC/PostRecordedAudioVideo', formData, progress, percentage, function (fName) { container.appendChild(document.createElement('hr')); var mediaElement = document.createElement('video'); var source = document.createElement('source'); source.src = document.location.origin + '/uploads/' + fName.replace(/"/g, ''); source.type = 'video/webm; codecs="vp8, vorbis"'; mediaElement.appendChild(source); mediaElement.controls = true; container.appendChild(mediaElement); mediaElement.play(); progress.parentNode.removeChild(progress); strong.parentNode.removeChild(strong); hr.parentNode.removeChild(hr); }); } var record = document.getElementById('record'); var stop = document.getElementById('stop'); var deleteFiles = document.getElementById('delete'); var preview = document.getElementById('preview'); var container = document.getElementById('container'); var recordVideo; record.onclick = function () { record.disabled = true; navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia; navigator.getUserMedia({ audio: true, video: true }, function (stream) { preview.src = window.URL.createObjectURL(stream); preview.play(); recordVideo = RecordRTC(stream, { type: 'video' }); recordVideo.startRecording(); stop.disabled = false; }, function (error) { alert(error.toString()); }); }; var fileName; stop.onclick = function () { record.disabled = false; stop.disabled = true; preview.src = ''; fileName = (Math.round(Math.random() * 99999999) + 99999999) + '.webm'; recordVideo.stopRecording(function () { PostBlob(recordVideo.getBlob()); }); deleteFiles.disabled = false; }; deleteFiles.onclick = function () { deleteAudioVideoFiles(); }; function deleteAudioVideoFiles() { deleteFiles.disabled = true; if (!fileName) return; var formData = new FormData(); formData.append('delete-file', fileName); xhr('/RecordRTC/DeleteFile', formData, null, null, function (response) { console.log(response); }); fileName = null; container.innerHTML = ''; } function xhr(url, data, progress, percentage, callback) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (request.readyState == 4 && request.status == 200) { callback(request.responseText); } }; if (url.indexOf('/RecordRTC/DeleteFile') == -1) { request.upload.onloadstart = function () { percentage.innerHTML = 'Upload started...'; }; request.upload.onprogress = function (event) { progress.max = event.total; progress.value = event.loaded; percentage.innerHTML = 'Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%"; }; request.upload.onload = function () { percentage.innerHTML = 'Saved!'; }; } request.open('POST', url); request.send(data); } window.onbeforeunload = function () { if (!!fileName) { deleteAudioVideoFiles(); return 'It seems that you\'ve not deleted audio/video files from the server.'; } }; </script> <section class="experiment"> <p> RecordRTC is MIT licensed on Github! <a href="https://github.com/muaz-khan/RecordRTC" target="_blank">Documentation</a> </p> </section> <section class="experiment"> <h2 class="header" id="feedback">Feedback</h2> <div> <textarea id="message" style="border: 1px solid rgb(189, 189, 189); height: 8em; margin: .2em; outline: none; resize: vertical; width: 98%;" placeholder="Have any message? Suggestions or something went wrong?"></textarea> </div> <button id="send-message" style="font-size: 1em;">Send Message</button><small style="margin-left: 1em;">Enter your email too; if you want "direct" reply!</small> </section> <section class="experiment own-widgets latest-commits"> <h2 class="header" id="updates" style="color: red;padding-bottom: .1em;"><a href="https://github.com/muaz-khan/RecordRTC/commits/master" target="_blank">Latest Updates</a></h2> <div id="github-commits"></div> </section> </article> <a href="https://github.com/muaz-khan/RecordRTC/tree/master/RecordRTC-to-ASPNETMVC" class="fork-left"></a> <footer> <p> <a href="https://www.webrtc-experiment.com/">WebRTC Experiments</a> © <a href="https://plus.google.com/+MuazKhan" rel="author" target="_blank">Muaz Khan</a> <a href="mailto:muazkh@gmail.com" target="_blank">muazkh@gmail.com</a> </p> </footer> <!-- commits.js is useless for you! --> <script src="https://cdn.webrtc-experiment.com/commits.js" async> </script> </body> </html>
the_stack
@page @model ValidationModel @{ ViewData["Title"] = "Validation"; ViewData["PageName"] = "form_validation"; ViewData["Heading"] = "<i class='subheader-icon fal fa-edit'></i> Validation"; ViewData["Category1"] = "Form Stuff"; ViewData["PageDescription"] = "Provide valuable, actionable feedback to your users with HTML5 form validation. Choose from the browser default validation feedback, or implement custom messages with our built-in classes and starter JavaScript."; } <div class="alert alert-primary alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true"> <i class="@(Settings.Theme.IconPrefix) fa-times"></i> </span> </button> <div class="d-flex flex-start w-100"> <div class="mr-2 hidden-md-down"> <span class="icon-stack icon-stack-lg"> <i class="base base-6 icon-stack-3x opacity-100 color-primary-500"></i> <i class="base base-10 icon-stack-2x opacity-100 color-primary-300 fa-flip-vertical"></i> <i class="@(Settings.Theme.IconPrefix) fa-info icon-stack-1x opacity-100 color-white"></i> </span> </div> <div class="d-flex flex-fill"> <div class="flex-fill"> <p class="h6">How it works</p> <p>Validation styles are available for the following form controls and components: <code>&lt;input&gt;</code> and <code>&lt;textarea&gt;</code> with <code>.form-control</code> (including up to one <code>.form-control</code> in input groups), <code>&lt;select&gt;</code> with <code>.form-select</code> or <code>.custom-select</code>, <code>.form-check</code>, <code>.custom-checkbox</code> and <code>.custom-radio</code>, <code>.custom-file</code></p> Learn more about forms on bootstrap's <a href="https://getbootstrap.com/docs/@ViewBag.Bs4v/components/forms/#how-it-works" target="_blank">official documentation</a> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> Invalid <span class="fw-300"><i>form styles</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <form class="was-validated"> <div class="form-group"> <label class="form-label" for="simpleinputInvalid">Text input</label> <input type="text" class="form-control is-invalid" id="simpleinputInvalid" required> <div class="invalid-feedback"> Please enter a message in the textarea. </div> </div> <div class="form-group"> <label class="form-label" for="validationTextarea3">Textarea</label> <textarea class="form-control is-invalid" id="validationTextarea3" placeholder="Required example textarea" required rows="4"></textarea> <div class="invalid-feedback"> Please enter a message in the textarea. </div> </div> <div class="form-group"> <label class="form-label">Checkbox & Radio</label> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customControlValidation1" required> <label class="custom-control-label" for="customControlValidation1">Check this custom checkbox</label> <div class="invalid-feedback">Example invalid feedback text</div> </div> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="customControlValidation2" name="radio-stacked" required> <label class="custom-control-label" for="customControlValidation2">Toggle this custom radio</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="customControlValidation3" name="radio-stacked" required> <label class="custom-control-label" for="customControlValidation3">Or toggle this other custom radio</label> <div class="invalid-feedback">More example invalid feedback text</div> </div> </div> <div class="form-group"> <label class="form-label">Switch elements</label> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input is-invalid" id="customControlValidation4" required> <label class="custom-control-label" for="customControlValidation4">Toggle this switch element </label> </div> </div> <div class="form-group"> <label class="form-label" for="customControlValidation5">Custom select</label> <select class="custom-select" required id="customControlValidation5"> <option value="">Open this select menu</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <div class="invalid-feedback">Example invalid custom select feedback</div> </div> <div class="form-group"> <label class="form-label is-invalid" for="customControlValidation6">Multiple Select</label> <select id="customControlValidation6" multiple="" class="form-control" required> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <label class="form-label">Custom file input</label> <div class="custom-file"> <input type="file" class="custom-file-input" id="customControlValidation7" required> <label class="custom-file-label" for="customControlValidation7">Choose file...</label> <div class="invalid-feedback">Example invalid custom file feedback</div> </div> </div> </form> </div> </div> </div> <div id="panel-2" class="panel"> <div class="panel-hdr"> <h2> Custom <span class="fw-300"><i>Styles</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> <p>For custom Bootstrap form validation messages, you’ll need to add the <code>novalidate</code> boolean attribute to your <code>&lt;form&gt;</code>. This disables the browser default feedback tooltips, but still provides access to the form validation APIs in JavaScript. Try to submit the form below; our JavaScript will intercept the submit button and relay feedback to you. When attempting to submit, you’ll see the <code>:invalid</code> and <code>:valid</code> styles applied to your form controls.</p> <p>Custom feedback styles apply custom colors, borders, focus styles, and background icons to better communicate feedback. Background icons for <code>&lt;select&gt;</code>s are only available with <code>.custom-select</code>, and not <code>.form-control</code>.</p> </div> </div> <div class="panel-content p-0"> <form class="needs-validation" novalidate> <div class="panel-content"> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="form-label" for="validationCustom01">First name <span class="text-danger">*</span> </label> <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Codex" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationCustom02">Last name <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Lantern" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationCustomUsername">Username <span class="text-danger">*</span></label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend">@@</span> </div> <input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required> <div class="invalid-feedback"> Please choose a username. </div> </div> </div> </div> <div class="form-row form-group"> <div class="col-md-6 mb-3"> <label class="form-label" for="validationCustom03">City <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationCustom03" placeholder="City" required> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationCustom03">State <span class="text-danger">*</span></label> <select class="custom-select" required=""> <option value="">State</option> <option value="1">Michigan</option> <option value="2">New York</option> <option value="3">Oklahoma</option> </select> <div class="invalid-feedback"> Please provide a valid state. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationCustom05">Zip <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationCustom05" placeholder="Zip" required> <div class="invalid-feedback"> Please provide a valid zip. </div> </div> <div class="col-12 mb-3"> <label class="form-label" for="validationTextarea2">Comment <span class="text-danger">*</span></label> <textarea class="form-control" id="validationTextarea2" placeholder="Required example textarea" required=""></textarea> <div class="invalid-feedback"> Please enter a message in the textarea. </div> </div> <div class="col-12"> <label class="form-label mb-2">Please disclose your gender profile <span class="text-danger">*</span></label> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="GenderMale" name="radio-stacked" required=""> <label class="custom-control-label" for="GenderMale">Male</label> </div> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="GenderFemale" name="radio-stacked" required=""> <label class="custom-control-label" for="GenderFemale">Female</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="genderPrivate" name="radio-stacked" required=""> <label class="custom-control-label" for="genderPrivate">Prefer not to say</label> <div class="invalid-feedback">Please select at least one</div> </div> </div> </div> </div> <div class="panel-content border-faded border-left-0 border-right-0 border-bottom-0 d-flex flex-row align-items-center"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="invalidCheck" required> <label class="custom-control-label" for="invalidCheck">Agree to terms and conditions <span class="text-danger">*</span></label> <div class="invalid-feedback"> You must agree before submitting. </div> </div> <button class="btn btn-primary ml-auto" type="submit">Submit form</button> </div> </form> <script> // Example starter JavaScript for disabling form submissions if there are invalid fields (function() { 'use strict'; window.addEventListener('load', function() { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })(); </script> </div> </div> </div> <div id="panel-3" class="panel"> <div class="panel-hdr"> <h2> Server <span class="fw-300"><i>side</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> We recommend using client-side validation, but in case you require server-side validation, you can indicate invalid and valid form fields with <code>.is-invalid</code> and <code>.is-valid</code>. Note that <code>.invalid-feedback</code> is also supported with these classes </div> <form> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="form-label" for="validationServer01">First name</label> <input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationServer02">Last name</label> <input type="text" class="form-control is-valid" id="validationServer02" placeholder="Last name" value="Otto" required> <div class="valid-feedback"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationServerUsername">Username</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend3">@@</span> </div> <input type="text" class="form-control is-invalid" id="validationServerUsername" placeholder="Username" aria-describedby="inputGroupPrepend3" required> <div class="invalid-feedback"> Please choose a username. </div> </div> </div> </div> <div class="form-row"> <div class="col-md-6 mb-3"> <label class="form-label" for="validationServer03">City</label> <input type="text" class="form-control is-invalid" id="validationServer03" placeholder="City" required> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationServer04">State</label> <input type="text" class="form-control is-invalid" id="validationServer04" placeholder="State" required> <div class="invalid-feedback"> Please provide a valid state. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationServer05">Zip</label> <input type="text" class="form-control is-invalid" id="validationServer05" placeholder="Zip" required> <div class="invalid-feedback"> Please provide a valid zip. </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Agree to terms and conditions </label> <div class="invalid-feedback"> You must agree before submitting. </div> </div> </div> <button class="btn btn-primary" type="submit">Submit form</button> </form> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-4" class="panel"> <div class="panel-hdr"> <h2> Valid <span class="fw-300"><i>form styles</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <form class="was-validated"> <div class="form-group"> <label class="form-label" for="simpleinputInvalid2">Text input</label> <input type="text" class="form-control is-valid" id="simpleinputInvalid2" required value="test"> <div class="valid-feedback"> Please enter a message in the textarea. </div> </div> <div class="form-group"> <label class="form-label" for="validationTextarea">Textarea</label> <textarea class="form-control is-valid" id="validationTextarea" placeholder="Required example textarea" required rows="4">test</textarea> <div class="valid-feedback"> Please enter a message in the textarea. </div> </div> <div class="form-group"> <label class="form-label">Checkbox & Radio</label> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customControlValidationSuccess1" required checked=""> <label class="custom-control-label" for="customControlValidationSuccess1">Check this custom checkbox</label> <div class="valid-feedback">Example valid feedback text</div> </div> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="customControlValidationSuccess2" name="radio-stacked" required checked=""> <label class="custom-control-label" for="customControlValidationSuccess2">Toggle this custom radio</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="customControlValidationSuccess3" name="radio-stacked" required> <label class="custom-control-label" for="customControlValidationSuccess3">Or toggle this other custom radio</label> <div class="valid-feedback">More example valid feedback text</div> </div> </div> <div class="form-group"> <label class="form-label">Switch elements</label> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input is-valid" id="customControlValidationSuccess4" required checked=""> <label class="custom-control-label" for="customControlValidationSuccess4">Toggle this switch element </label> </div> </div> <div class="form-group"> <label class="form-label" for="customControlValidationSuccess5">Custom select</label> <select class="custom-select" required id="customControlValidationSuccess5"> <option value="">Open this select menu</option> <option value="1" selected="">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <div class="valid-feedback">Example valid custom select feedback</div> </div> <div class="form-group"> <label class="form-label" for="customControlValidationSuccess6">Multiple Select</label> <select id="customControlValidationSuccess6" multiple="" class="form-control is-valid" required> <option selected="">1</option> <option selected="">2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <label class="form-label">Custom file input</label> <div class="custom-file"> <input type="file" class="custom-file-input is-valid" id="customControlValidationSuccess7"> <label class="custom-file-label" for="customControlValidationSuccess7">Choose file...</label> <div class="valid-feedback">Example valid custom file feedback</div> </div> </div> </form> </div> </div> </div> <div id="panel-5" class="panel"> <div class="panel-hdr"> <h2> Tooltip <span class="fw-300"><i>Styles</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> <p>If your form layout allows it, you can swap the <code>.{valid|invalid}-feedback</code> classes for <code>.{valid|invalid}-tooltip</code> classes to display validation feedback in a styled tooltip. Be sure to have a parent with <code>position: relative</code> on it for tooltip positioning. In the example below, our column classes have this already, but your project may require an alternative setup.</p> </div> </div> <div class="panel-content p-0"> <form class="needs-validation" novalidate> <div class="panel-content"> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="form-label" for="validationTooltip01">First name <span class="text-danger">*</span> </label> <input type="text" class="form-control" id="validationTooltip01" placeholder="First name" value="Codex" required> <div class="valid-tooltip"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationTooltip02">Last name <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationTooltip02" placeholder="Last name" value="Lantern" required> <div class="valid-tooltip"> Looks good! </div> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationTooltip03">Username <span class="text-danger">*</span></label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend2">@@</span> </div> <input type="text" class="form-control" id="validationTooltip03" placeholder="Username" aria-describedby="inputGroupPrepend2" required> <div class="invalid-tooltip"> Please choose a username. </div> </div> </div> </div> <div class="form-row form-group"> <div class="col-md-6 mb-3"> <label class="form-label" for="validationTooltip04">City <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationTooltip04" placeholder="City" required> <div class="invalid-tooltip"> Please provide a valid city. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationTooltip05">State <span class="text-danger">*</span></label> <select class="custom-select" required="" id="validationTooltip05"> <option value="">State</option> <option value="1">Michigan</option> <option value="2">New York</option> <option value="3">Oklahoma</option> </select> <div class="invalid-tooltip"> Please provide a valid state. </div> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationTooltip06">Zip <span class="text-danger">*</span></label> <input type="text" class="form-control" id="validationTooltip06" placeholder="Zip" required> <div class="invalid-tooltip"> Please provide a valid zip. </div> </div> <div class="col-12 mb-3"> <label class="form-label" for="validationTooltip07">Comment <span class="text-danger">*</span></label> <textarea class="form-control" id="validationTooltip07" placeholder="Required example textarea" required=""></textarea> <div class="invalid-tooltip"> Please enter a message in the textarea. </div> </div> <div class="col-12"> <label class="form-label mb-2">Please disclose your gender profile <span class="text-danger">*</span></label> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="validationTooltipGenderMale" name="radio-stacked" required=""> <label class="custom-control-label" for="validationTooltipGenderMale">Male</label> </div> <div class="custom-control custom-radio mb-2"> <input type="radio" class="custom-control-input" id="validationTooltipGenderFemale" name="radio-stacked" required=""> <label class="custom-control-label" for="validationTooltipGenderFemale">Female</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="validationTooltipgenderPrivate" name="radio-stacked" required=""> <label class="custom-control-label" for="validationTooltipgenderPrivate">Prefer not to say</label> <div class="invalid-tooltip">Please select at least one</div> </div> </div> </div> </div> <div class="panel-content border-faded border-left-0 border-right-0 border-bottom-0 d-flex flex-row align-items-center"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="validationTooltipAgreement" required> <label class="custom-control-label" for="validationTooltipAgreement">Agree to terms and conditions <span class="text-danger">*</span></label> <div class="invalid-tooltip"> You must agree before submitting. </div> </div> <button class="btn btn-primary ml-auto" type="submit">Submit form</button> </div> </form> <script> // Example starter JavaScript for disabling form submissions if there are invalid fields (function() { 'use strict'; window.addEventListener('load', function() { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })(); </script> </div> </div> </div> <div id="panel-6" class="panel"> <div class="panel-hdr"> <h2> Browser <span class="fw-300"><i>defaults</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> <p> Not interested in custom validation feedback messages or writing JavaScript to change form behaviors? All good, you can use the browser defaults. Try submitting the form below. Depending on your browser and OS, you’ll see a slightly different style of feedback. </p> <p> While these feedback styles cannot be styled with CSS, you can still customize the feedback text through JavaScript. </p> </div> </div> <div class="panel-content p-0"> <form> <div class="panel-content"> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="form-label" for="validationDefault01">First name</label> <input type="text" class="form-control" id="validationDefault01" placeholder="First name" value="Mark" required> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationDefault02">Last name</label> <input type="text" class="form-control" id="validationDefault02" placeholder="Last name" value="Otto" required> </div> <div class="col-md-4 mb-3"> <label class="form-label" for="validationDefaultUsername">Username</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend4">@@</span> </div> <input type="text" class="form-control" id="validationDefaultUsername" placeholder="Username" aria-describedby="inputGroupPrepend4" required> </div> </div> </div> <div class="form-row mb-2"> <div class="col-md-6 mb-3"> <label class="form-label" for="validationDefault03">City</label> <input type="text" class="form-control" id="validationDefault03" placeholder="City" required> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationDefault04">State</label> <input type="text" class="form-control" id="validationDefault04" placeholder="State" required> </div> <div class="col-md-3 mb-3"> <label class="form-label" for="validationDefault05">Zip</label> <input type="text" class="form-control" id="validationDefault05" placeholder="Zip" required> </div> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="invalidCheck2" required=""> <label class="custom-control-label" for="invalidCheck2">Agree to terms and conditions</label> </div> </div> </div> <div class="panel-content border-faded border-left-0 border-right-0 border-bottom-0 d-flex flex-row"> <button class="btn btn-primary ml-auto" type="submit">Submit form</button> </div> </form> </div> </div> </div> </div> </div> @section ScriptsBlock { <script type="text/javascript"> // Example starter JavaScript for disabling form submissions if there are invalid fields /* (function() { 'use strict'; window.addEventListener('load', function() { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })();*/ </script> }
the_stack
@using YL.Core.Dto @using YL.Utils.Json @{ Layout = "_LayoutH"; @model RoleMenuDto } <div id="app" v-cloak> <form class="form form-horizontal" onsubmit="return false"> <div class="box-body"> <div class="form-group"> <label class="col-sm-2 control-label"><span class="c-red">*</span>角色名称:</label> <div class="col-sm-10"> <input v-model="RoleName" type="text" class="form-control" v-focus> </div> </div> @*<div class="row cl"> <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色名称:</label> <div class="formControls col-xs-8 col-sm-9"> <input v-model="RoleName" type="text" class="input-text" v-focus> </div> </div>*@ <div class="form-group"> <label class="control-label col-sm-2">备注:</label> <div class="col-sm-10"> <textarea v-model="Remark" class="form-control" rows="3" placeholder="备注...100个字符以内"></textarea> <p class="textarea-numberbar"><em class="textarea-length">{{count}}</em>/100</p> </div> </div> <div class="form-group"> <div class="col-sm-10"> <input v-on:click="checkAll" class="btn btn-primary radius" type="button" value="全选"> <input v-on:click="inverse" class="btn btn-primary radius" type="button" value="反选"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">系统角色:</label> <div class="col-sm-10"> <dl class="permission-list" v-for="item in list"> <dt> <label> <input type="checkbox" v-on:click="checkMenu(item,item.Children)" v-model="checkedNames" :value="item.Id"> {{item.Name}} </label> </dt> <dd> <dl class="cl permission-list2"> <dt v-for="item2 in item.Children"> <label> <input type="checkbox" v-model="checkedNames" :value="item2.Id"> {{item2.Name}} </label> </dt> </dl> </dd> </dl> </div> </div> <div class="box-footer"> <div class="pull-right box-tools"> <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit"> </div> </div> </div> </form> </div> @section styles{ <style> .permission-list { border: solid 1px #eee; } .permission-list > dt { background-color: #efefef; padding: 5px 10px; } .permission-list > dd { padding: 10px; padding-left: 30px; } .permission-list > dd > dl { border-bottom: solid 1px #eee; padding: 5px 0; } .permission-list > dd > dl > dt { display: inline-block; float: left; white-space: nowrap; width: 100px; } dl { margin-top: 0; /*margin-bottom:15px;*/ } label { display: inline-block; max-width: 100%; margin-bottom: 5px; font-weight: 700; } </style> } @section scripts{ <script> $(function () { //parent.$("span[class='layui-layer-setwin']")[0].childNodes[1].onclick = function () { // var index = parent.layer.getFrameIndex(window.name); // parent.$("#layui-layer-iframe" + index)[0].style.height = parent.document.body.clientHeight + "px"; //}; }); var app = new Vue({ el: "#app", data: { submit: "添加", RoleId:"@Model.RoleId", Remark: "@Model.Remark", RoleName: "@Model.RoleName", checked: "", updateList:@Html.Raw(Model.Children.JilToJson()), checkedNames: [], list: [] }, computed: { count: function () { return this.strLength(this.Remark, false); } }, watch: { updateList: function () { var _self = this; var obj = _self.updateList; var arr = []; if (obj.length > 0) { for (var item in obj) { arr.push(obj[item].MenuId.toString()); } } _self.checkedNames = arr; } }, mounted: function () { var _self = this; _self.$nextTick(function () { _self.loadL(); _self.updateList=@Html.Raw(Model.Children.JilToJson()); }); }, methods: { distinct: function (arr) { let result = [] let obj = {} for (let i of arr) { if (!obj[i]) { result.push(i) obj[i] = 1 } } return result; }, checkAll: function () { var _self = this; _self.list.forEach(function (item, index) { if (_self.checkedNames.indexOf(item.Id.toString()) < 0) { _self.checkedNames.push(item.Id.toString()); } item.Children.forEach(function (c, i) { if (_self.checkedNames.indexOf(c.Id.toString())<0) { _self.checkedNames.push(c.Id.toString()) } }); }); }, inverse: function () { var _self = this; _self.checkedNames = []; }, recursion: function (arr, id, c) { //for (var item in arr) { // if (arr[item].id == id) { // arr.splice(item, 1); // me.recursion(arr, id); // } //} for (var k in arr) { if (arr[k].toString() === id) { arr.splice(k, 1); } } for (var j in c) { if (c[j].ParentId.toString() === id) { var cid = c[j].Id.toString(); for (var i in arr) { if (arr[i].toString() === cid) { arr.splice(i, 1); } } } } }, checkMenu: function (p,c) { var _self = this; if (_self.checkedNames.indexOf(p.Id.toString()) > -1) { _self.recursion(_self.checkedNames, p.Id.toString(), c); } else { _self.checkedNames.push(p.Id.toString()); for (var i of c) { if (i.ParentId.toString() === p.Id.toString()) { _self.checkedNames.push(i.Id.toString()); } } } }, loadL: function () { var _self = this; axios.get('/Role/GetMenuList') .then(function (response) { _self.list = response.data; }) .catch(function (error) { layer.msg(error.message, { icon: 5 }); }); }, addL:function () { var _self = this; if (_self.RoleName.length <= 0) { layer.msg("角色名称不能为空", { icon: 2 }); return false; } if (_self.checkedNames.length <= 0) { layer.msg("请选择菜单", { icon: 2 }); return false; } var index = layer.load(1, { shade: [0.1, '#fff'] //0.1透明度的白色背景 }); var data = { id: _self.RoleId, menuId: _self.distinct(_self.checkedNames), RoleName: _self.RoleName, Remark: _self.Remark }; yui.$axiospostform('/Role/AddOrUpdate',data) .then(function (response) { if (response.data.Item1 === 101) { layer.tips(response.data.Item2, '.layui-layer-setwin', { tips: [1, '#3595CC'], time: 3000 }); layer.close(index); return false; } if (response.data.Item1) { layer.msg(response.data.Item2, { icon: 1, time: 1000 }); setTimeout(function () { yui.layer_close3(); }, 500); } else { layer.msg(response.data.Item2 || errorMsg, { icon: 5 }); } layer.close(index); }) .catch(function (error) { layer.close(index); }); } } }); </script> }
the_stack
@page @model SparklineModel @{ ViewData["Title"] = "Sparkline"; ViewData["PageName"] = "statistics_sparkline"; ViewData["Category1"] = "Statistics"; ViewData["Heading"] = "<i class='subheader-icon fal fa-chart-pie'></i> Sparkline <sup class='badge badge-primary fw-500'>ADDON</sup>"; ViewData["PageDescription"] = "Sparkline chart is a tiny chart in a worksheet cell that provides a visual representation of data."; } @section HeadBlock {} @section SubheaderBlock { <div class="subheader-block hidden-lg-down d-lg-flex align-items-center"> <div class="d-inline-flex flex-column justify-content-center mr-3"> <span class="fw-300 fs-xs d-block opacity-50"> <small>EXPENSES</small> </span> <span class="fw-500 fs-xl d-block color-info-500"> $47,000 </span> </div> <span class="sparklines" sparkType="bar" sparkBarColor="#0d8aee" sparkHeight="32px" values="1,4,3,6,5,3,9,6,5,9,7"></span> </div> <div class="subheader-block hidden-lg-down d-lg-flex align-items-center border-faded border-right-0 border-top-0 border-bottom-0 ml-3 pl-3"> <div class="d-inline-flex flex-column justify-content-center mr-3"> <span class="fw-300 fs-xs d-block opacity-50"> <small>MY PROFITS</small> </span> <span class="fw-500 fs-xl d-block color-danger-500"> $38,500 </span> </div> <span class="sparklines" sparkType="bar" sparkBarColor="#fe6bb0" sparkHeight="32px" values="1,4,3,6,5,3,9,6,5,9,7"></span> </div> } <div class="alert alert-primary"> <div class="d-flex flex-start w-100"> <div class="mr-2 hidden-md-down"> <span class="icon-stack icon-stack-lg"> <i class="base base-6 icon-stack-3x opacity-100 color-primary-500"></i> <i class="base base-10 icon-stack-2x opacity-100 color-primary-300 fa-flip-vertical"></i> <i class="ni ni-blog-read icon-stack-1x opacity-100 color-white"></i> </span> </div> <div class="d-flex flex-fill"> <div class="flex-fill"> <span class="h5">About</span> <p>This jQuery plugin generates sparklines (small inline charts) directly in the browser using data supplied either inline in the HTML, or via javascript. Use sparklines to show trends in a series of values, such as seasonal increases or decreases, economic cycles, or to highlight maximum and minimum values.</p> <p class="m-0"> Find tutorials, guidelines and more on Sparkline's <a href="https://omnipotent.net/jquery.sparkline/#s-docs" target="_blank">official documentation</a> </p> </div> </div> </div> </div> <div class="row"> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> Line <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Line charts are the default chart type, but to specify the type explicitly set an option called <code>type</code> to <code>line</code> </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#1dc9b7" sparkFillColor="false" sparkLineWidth="2" values="5,3,9,6,5,9,7,3,5,2"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#fd3995" sparkFillColor="false" sparkLineWidth="2" values="0,-3,-6,-4,-5,-4,-7,-3,-5,-2"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#ffba28" sparkFillColor="false" sparkLineWidth="2" values="-4,5,4,7,-3,-5,-2,0,3,-6,"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#2196F3" sparkFillColor="false" sparkLineWidth="2" values="-4,5,4,6,5,9,7,3,5,3,-6"></span> </div> </div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-2" class="panel"> <div class="panel-hdr"> <h2> Area <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> We take the line example to your right and add <code>fillColor</code> to fill the area </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#ffba28" sparkFillColor="#ffd274" sparkLineWidth="1" values="5,3,2,-1,-3,-2,2,3,5,2"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#886ab5" sparkFillColor="#a38cc6" sparkLineWidth="1" values="1,4,4,7,5,9,10,4,4,7,5,9,10"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#fd52a3" sparkFillColor="#fe85be" sparkLineWidth="1" values="-2,2,3,5,9,10,4,4,-7,-5,9,10"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="line" sparkHeight="40" sparkWidth="110" sparkLineColor="#2196F3" sparkFillColor="#9acffa" sparkLineWidth="1" values="4,5,4,6,5,9,7,3,5,3,6"></span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-3" class="panel"> <div class="panel-hdr"> <h2> Bar <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Set the <code>type</code> option to <code>bar</code> to generate bar charts. Values can be omitted by using the <code>null</code> value instead of a number. </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" sparkBarColor="#886ab5" values="5,3,9,6,5,9,7,5,2,6,2,1,5,3,6,7,5,7"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" sparkHeight="40" sparkBarColor="#21dfcb" sparkNegBarColor="#fd3995" values="4,-3,-6,-4,-5,7,-3,-5,2,3,1,-3,4,3,-6,-4,-7"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" sparkBarColor="#21dfcb" sparkNegBarColor="#fd3995" values="4,3,6,4,-5,4,3,5,-2,3,1,3,4,3,6,4,5"></span> </div> </div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-4" class="panel"> <div class="panel-hdr"> <h2> Composite <span class="fw-300"><i>Bar</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Composite charts are re-drawn on top of each other to display multiple data points stacked in a single row or column </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" values="4:7,5:8,-6:10,7:7,-5:-9,8:10,-7:-6,6:9,-6:4,7:7,4:5,5:9,4:4,3:5,7:10,1:3"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" values="4:7,5:8,6:10,4:5,5:9,8:10,7:6,6:9,6:4,-5:9,8:10,7:6,9:2,4:8,5:6,8:9"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bar" values="-4:7,-5:8,-7:7,-4:5,-5:9,-8:10,-7:6,-6:9,-6:-4,-5:-9,-8:-10,-7:-6,-6:-4,-5:-9,-3:-4,-5:-8"></span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-5" class="panel"> <div class="panel-hdr"> <h2> Tristate <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Tri-state charts are useful to show win-lose-draw information. You can also use the colorMap for different arbitrary positions </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="tristate" sparkPosBarColor="#51adf6" sparkNegBarColor="#ffc241" sparkBarSpacing="2px" sparkBarWidth="5px" values="1,1,0,1,-1,-1,1,-1,0,0,-1,1,-1,0,0,1,1,0,1,-1,-1,1,-1,0,0,1,1,0,1,-1"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="tristate" sparkPosBarColor="#13867a" sparkNegBarColor="#ce0262" sparkBarSpacing="2px" sparkBarWidth="5px" values="-1,1,-1,0,0,1,1,0,1,-1,1,1,0,1,-1,-1,1,-1,0,0,1,1,0,1,-1,-1,1,-1,0,0"></span> </div> </div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-6" class="panel"> <div class="panel-hdr"> <h2> Discrete <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Discrete charts provide a separated thin vertical line for each value. Set the "type" option to "discrete" to generate discrete charts </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="discrete" sparkLineColor="#fd3995" values="4,6,7,7,4,3,2,1,4,-4,5,6,7,6,6,-2,"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="discrete" sparkLineColor="#0d8aee" values="4,6,7,-7,4,3,2,1,4,4,5,6,-7,6,6,2,"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="discrete" sparkLineColor="#ffba28" values="-4,-6,-7,-5,4,3,-2,-1,4,3,4,6,7,7,4,3,2"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="discrete" sparkLineColor="#886ab5" values="-4,-7,6,3,7,6,-2,-8,4,6,2,6,4,-2,-4,-5"></span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-7" class="panel"> <div class="panel-hdr"> <h2> Bullet <span class="fw-300"><i>Graph</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> A bullet graph is inspired by a traditional thermometer charts, it serves as a replacement for dashboard gauges and meters. </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bullet" sparkHeight="50" values="10,12,12,9,7"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="bullet" sparkHeight="50" values="1,3,3,9,7"></span> </div> </div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-8" class="panel"> <div class="panel-hdr"> <h2> Pie <span class="fw-300"><i>Chart</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Set the "type" option to "pie" to generate pie charts. These little pie charts tend only to be useful with 2 or 3 values at most </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="pie" sparkHeight="50" sparkWidth="auto" values="4,6,7,7,4"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="pie" sparkHeight="50" sparkWidth="auto" values="4,6,7"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="pie" sparkHeight="50" sparkWidth="auto" values="1,3"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="pie" sparkHeight="50" sparkWidth="auto" values="1,7,3,7,9,3,5"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="pie" sparkHeight="50" sparkWidth="auto" values="7,10,33,50,100"></span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-xl-12"> <div class="row"> <div class="col-xl-6"> <div id="panel-9" class="panel"> <div class="panel-hdr"> <h2> Refresh <span class="fw-300"><i>Graph</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> The demo below uses jquery snippet to draw values from mouse movement and plots it intravenously into the graph </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span id="mousespeed-line"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span id="mousespeed-bar"></span> </div> </div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-10" class="panel"> <div class="panel-hdr"> <h2> Box <span class="fw-300"><i>Plots</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Boxplot is a method for graphically depicting groups of numerical data through their quartiles. Outliers may be plotted as individual points </div> <div class="demo d-flex justify-content-center flex-wrap d-sm-block"> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="box" values="4,27,34,52,54,59,61,68,78,82,85,87,91,93,100"></span> </div> <div class="p-3 w-auto text-center d-inline-flex border-faded"> <span class="sparklines" sparkType="box" sparkRaw="true" sparkShowOutliers="true" sparkTarget="6" , sparkBoxFillColor="#ffebc1" sparkBoxLineColor="#563d7c" sparkWhiskerColor="#563d7c" sparkMedianColor="#886ab5" sparkTargetColor="#fd3995" values="1, 3, 5, 8, 10, 15, 18"></span> </div> </div> </div> </div> </div> </div> </div> </div> </div> @section ScriptsBlock { <script src="~/js/statistics/sparkline/sparkline.bundle.js"></script> <script> /* * draw the little mouse speed animated graph this just attaches a handler to the mousemove event to see * (roughly) how far the mouse has moved and then updates the display a couple of times a second via * setTimeout() */ var drawMouseSpeedDemo = function() { var mrefreshinterval = 500, // update display every 500ms lastmousex = -1, lastmousey = -1, lastmousetime, mousetravel = 0, mpoints = [], mpoints_max = 30; $('html').mousemove(function (e) { var mousex = e.pageX, mousey = e.pageY; if (lastmousex > -1) { mousetravel += Math.max(Math.abs(mousex - lastmousex), Math.abs(mousey - lastmousey)); } lastmousex = mousex; lastmousey = mousey; }); var mdraw = function () { var md = new Date(); var timenow = md.getTime(); if (lastmousetime && lastmousetime != timenow) { var pps = Math.round(mousetravel / (timenow - lastmousetime) * 1000); mpoints.push(pps); if (mpoints.length > mpoints_max) mpoints.splice(0, 1); mousetravel = 0; $('#mousespeed-line').sparkline(mpoints, { type: 'line', width: 210, height: 40, lineColor: color.info._500, fillColor: color.info._50, tooltipSuffix: ' pixels per second' }); $('#mousespeed-bar').sparkline(mpoints, { type: 'bar', height: 40, tooltipSuffix: ' pixels per second' }); } lastmousetime = timenow; setTimeout(mdraw, mrefreshinterval); } // we could use setInterval instead, but I prefer to do it this way setTimeout(mdraw, mrefreshinterval); }; $(document).ready(function() { //start refresh chart drawMouseSpeedDemo(); }); </script> }
the_stack
@using OrchardCore.OpenId.ViewModels @using OrchardCore.OpenId.Settings @using System.Security.Cryptography.X509Certificates @model OpenIdServerSettingsViewModel <p class="alert alert-warning">@T["The current tenant will be reloaded when the settings are saved."]</p> <h3>@T["Endpoints"]</h3> <div class="form-group" asp-validation-class-for="EnableTokenEndpoint"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="EnableTokenEndpoint"> <label class="custom-control-label" asp-for="EnableTokenEndpoint">@T["Enable Token Endpoint"]</label> <span class="hint dashed">@T["Enables action"] /connect/token</span> </div> </div> <div class="form-group" asp-validation-class-for="EnableAuthorizationEndpoint"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="EnableAuthorizationEndpoint"> <label class="custom-control-label" asp-for="EnableAuthorizationEndpoint">@T["Enable Authorization Endpoint"]</label> <span class="hint dashed">@T["Enables action"] /connect/authorize</span> </div> </div> <div class="form-group" asp-validation-class-for="EnableLogoutEndpoint"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="EnableLogoutEndpoint"> <label class="custom-control-label" asp-for="EnableLogoutEndpoint">@T["Enable Logout Endpoint"]</label> <span class="hint dashed">@T["Enables action"] /connect/logout</span> </div> </div> <div class="form-group" asp-validation-class-for="EnableUserInfoEndpoint"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="EnableUserInfoEndpoint"> <label class="custom-control-label" asp-for="EnableUserInfoEndpoint">@T["Enable User Info Endpoint"]</label> <span class="hint dashed">@T["Enables action"] /connect/userinfo</span> </div> </div> <h3>@T["Flows"]</h3> <div class="form-group collapse" asp-validation-class-for="AllowAuthorizationCodeFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowAuthorizationCodeFlow"> <label class="custom-control-label" asp-for="AllowAuthorizationCodeFlow">@T["Allow Authorization Code Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth">http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth</a></span> </div> </div> <div class="form-group collapse" asp-validation-class-for="AllowImplicitFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowImplicitFlow"> <label class="custom-control-label" asp-for="AllowImplicitFlow">@T["Allow Implicit Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth">http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth</a></span> </div> </div> <div class="form-group collapse" asp-validation-class-for="AllowHybridFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowHybridFlow"> <label class="custom-control-label" asp-for="AllowHybridFlow">@T["Allow Hybrid Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="http://openid.net/specs/openid-connect-core-1_0.html#HybridFlowAuth">http://openid.net/specs/openid-connect-core-1_0.html#HybridFlowAuth</a></span> </div> </div> <div class="form-group collapse" asp-validation-class-for="AllowPasswordFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowPasswordFlow"> <label class="custom-control-label" asp-for="AllowPasswordFlow">@T["Allow Password Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="https://tools.ietf.org/html/rfc6749#section-1.3.3">https://tools.ietf.org/html/rfc6749#section-1.3.3</a></span> </div> </div> <div class="form-group collapse" asp-validation-class-for="AllowRefreshTokenFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowRefreshTokenFlow"> <label class="custom-control-label" asp-for="AllowRefreshTokenFlow">@T["Allow Refresh Token Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="http://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens">http://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens</a></span> </div> </div> <div class="form-group collapse" asp-validation-class-for="AllowClientCredentialsFlow"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="AllowClientCredentialsFlow"> <label class="custom-control-label" asp-for="AllowClientCredentialsFlow">@T["Allow Client Credentials Flow"]</label> <span class="hint dashed">@T["More info:"] <a href="https://tools.ietf.org/html/rfc6749#section-1.3.4">https://tools.ietf.org/html/rfc6749#section-1.3.4</a></span> </div> </div> <h3>@T["Advanced options"]</h3> <p class="alert alert-info">@T["These options are all optional and are for advanced users only."]</p> <div class="form-group" asp-validation-class-for="Authority"> <label asp-for="Authority">@T["Authority"]</label> <input asp-for="Authority" class="form-control" /> <span asp-validation-for="Authority"></span> <span class="hint">@T["The base URL of the identity server (this site). If none is provided, a default value based on the site host is automatically computed."]</span> </div> <div class="form-group" asp-validation-class-for="EncryptionCertificateStoreLocation"> <label asp-for="EncryptionCertificateStoreLocation">@T["Encryption Certificate Store Location"]</label> <select asp-for="EncryptionCertificateStoreLocation" class="form-control"> <option value="">@T["None"]</option> @foreach (StoreLocation location in Enum.GetValues(typeof(StoreLocation))) { <option value="@location" selected="@(Model.EncryptionCertificateStoreLocation == location)">@location.ToString()</option> } </select> <span asp-validation-for="EncryptionCertificateStoreLocation"></span> <span class="hint">@T["Select the encryption certificate location."]</span> </div> <div class="form-group" asp-validation-class-for="EncryptionCertificateStoreName"> <label asp-for="EncryptionCertificateStoreName">@T["Encryption Certificate Store Name"]</label> <select asp-for="EncryptionCertificateStoreName" class="form-control"> <option value="">@T["None"]</option> @foreach (StoreName store in Enum.GetValues(typeof(StoreName))) { <option value="@store" selected="@(Model.EncryptionCertificateStoreName == store)">@store.ToString()</option> } </select> <span asp-validation-for="EncryptionCertificateStoreName"></span> <span class="hint">@T["Select the encryption certificate store."]</span> </div> <div class="form-group" asp-validation-class-for="EncryptionCertificateThumbprint"> @if (Model.AvailableCertificates.Count != 0) { <label asp-for="EncryptionCertificateThumbprint">@T["Encryption Certificate"]</label> <select asp-for="EncryptionCertificateThumbprint" class="form-control"> <option value="">@T["None"]</option> @foreach (var certificate in Model.AvailableCertificates) { var selectedCertificate = Model.EncryptionCertificateThumbprint == certificate.ThumbPrint && Model.EncryptionCertificateStoreLocation.HasValue && Model.EncryptionCertificateStoreLocation.Value == certificate.StoreLocation && Model.EncryptionCertificateStoreName.HasValue && Model.EncryptionCertificateStoreName == certificate.StoreName; if (string.IsNullOrWhiteSpace(certificate.ThumbPrint)) { <option value="" data-StoreLocation="@certificate.StoreLocation" data-StoreName="@certificate.StoreName" selected="@(selectedCertificate)"></option> continue; } var friendlyName = certificate.FriendlyName; if (string.IsNullOrWhiteSpace(friendlyName) && !string.IsNullOrWhiteSpace(certificate.ThumbPrint)) { friendlyName = "No Friendly Name"; } <option value="@certificate.ThumbPrint" data-StoreLocation="@certificate.StoreLocation" data-StoreName="@certificate.StoreName" selected="@(selectedCertificate)"> @friendlyName [@certificate.NotBefore.ToString("dd/MM/yy") - @certificate.NotAfter.ToString("dd/MM/yy")] @certificate.Subject </option> } </select> <span asp-validation-for="EncryptionCertificateThumbprint"></span> <span class="hint">@T["Select the encryption certificate."]</span> } else { <div class="alert alert-warning" asp-validation-for="CertificateThumbprint">@T["You need to add a certificate to your server for setting up OpenID Connect module."]</div> } </div> <div class="form-group" asp-validation-class-for="SigningCertificateStoreLocation"> <label asp-for="SigningCertificateStoreLocation">@T["Signing Certificate Store Location"]</label> <select asp-for="SigningCertificateStoreLocation" class="form-control"> <option value="">@T["None"]</option> @foreach (StoreLocation location in Enum.GetValues(typeof(StoreLocation))) { <option value="@location" selected="@(Model.SigningCertificateStoreLocation == location)">@location.ToString()</option> } </select> <span asp-validation-for="SigningCertificateStoreLocation"></span> <span class="hint">@T["Select the signing certificate location."]</span> </div> <div class="form-group" asp-validation-class-for="SigningCertificateStoreName"> <label asp-for="SigningCertificateStoreName">@T["Signing Certificate Store Name"]</label> <select asp-for="SigningCertificateStoreName" class="form-control"> <option value="">@T["None"]</option> @foreach (StoreName store in Enum.GetValues(typeof(StoreName))) { <option value="@store" selected="@(Model.SigningCertificateStoreName == store)">@store.ToString()</option> } </select> <span asp-validation-for="SigningCertificateStoreName"></span> <span class="hint">@T["Select the signing certificate store."]</span> </div> <div class="form-group" asp-validation-class-for="SigningCertificateThumbprint"> @if (Model.AvailableCertificates.Count != 0) { <label asp-for="SigningCertificateThumbprint">@T["Signing Certificate"]</label> <select asp-for="SigningCertificateThumbprint" class="form-control"> <option value="">@T["None"]</option> @foreach (var certificate in Model.AvailableCertificates) { var selectedCertificate = Model.SigningCertificateThumbprint == certificate.ThumbPrint && Model.SigningCertificateStoreLocation.HasValue && Model.SigningCertificateStoreLocation.Value == certificate.StoreLocation && Model.SigningCertificateStoreName.HasValue && Model.SigningCertificateStoreName == certificate.StoreName; if (string.IsNullOrWhiteSpace(certificate.ThumbPrint)) { <option value="" data-StoreLocation="@certificate.StoreLocation" data-StoreName="@certificate.StoreName" selected="@(selectedCertificate)"></option> continue; } var friendlyName = certificate.FriendlyName; if (string.IsNullOrWhiteSpace(friendlyName) && !string.IsNullOrWhiteSpace(certificate.ThumbPrint)) { friendlyName = "No Friendly Name"; } <option value="@certificate.ThumbPrint" data-StoreLocation="@certificate.StoreLocation" data-StoreName="@certificate.StoreName" selected="@(selectedCertificate)"> @friendlyName [@certificate.NotBefore.ToString("dd/MM/yy") - @certificate.NotAfter.ToString("dd/MM/yy")] @certificate.Subject </option> } </select> <span asp-validation-for="SigningCertificateThumbprint"></span> <span class="hint">@T["Select the signing certificate."]</span> } else { <div class="alert alert-warning" asp-validation-for="CertificateThumbprint">@T["You need to add a certificate to your server for setting up OpenID Connect module."]</div> } </div> <div class="form-group" asp-validation-class-for="DisableRollingRefreshTokens"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="DisableRollingRefreshTokens"> <label class="custom-control-label" asp-for="DisableRollingRefreshTokens">@T["Disable Rolling Refresh Tokens"]</label> <span class="hint dashed">@T["When this option is enabled, refresh tokens are not marked as redeemed and can be reused until they expire."]</span> </div> </div> <div class="form-group" asp-validation-class-for="AccessTokenFormat"> <label asp-for="AccessTokenFormat">@T["Token Format"]</label> <select asp-for="AccessTokenFormat" class="form-control"> <option value="@OpenIdServerSettings.TokenFormat.DataProtection" selected="@(Model.AccessTokenFormat == OpenIdServerSettings.TokenFormat.DataProtection)"> @T["ASP.NET Core Data Protection"] </option> <option value="@OpenIdServerSettings.TokenFormat.JsonWebToken" selected="@(Model.AccessTokenFormat == OpenIdServerSettings.TokenFormat.JsonWebToken)"> @T["JSON Web Token (JWT)"] </option> </select> <span asp-validation-for="AccessTokenFormat"></span> </div> <div class="form-group" asp-validation-class-for="DisableAccessTokenEncryption"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="DisableAccessTokenEncryption"> <label class="custom-control-label" asp-for="DisableAccessTokenEncryption">@T["Disable Access Token Encryption (only for JWT tokens)"]</label> <span class="hint dashed">@T["When this option is enabled, the JWT access token tokens are not encrypted."]</span> </div> </div> <div class="form-group" asp-validation-class-for="UseReferenceAccessTokens"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" asp-for="UseReferenceAccessTokens"> <label class="custom-control-label" asp-for="UseReferenceAccessTokens">@T["Use Reference Access Tokens"]</label> <span class="hint dashed">@T["When this option is enabled, the access token are stored in the database and fixed size tokens are returned to the client, which can be useful when storing a very large number of claims. Important: this option cannot be currently enabled when other tenants are configured to use this server."]</span> </div> </div> <script at="Foot"> ////<![CDATA[ window.onload = function () { refreshEncryptionCertificates(); refreshSigningCertificates(); refreshEndpoints(); refreshDisableAccessTokenEncryption(); $("#@Html.IdFor(m => m.AccessTokenFormat)").change(function () { refreshDisableAccessTokenEncryption(); }); $("#@Html.IdFor(m => m.EncryptionCertificateStoreLocation)").change(function () { refreshEncryptionCertificates(); }); $("#@Html.IdFor(m => m.EncryptionCertificateStoreName)").change(function () { refreshEncryptionCertificates(); }); $("#@Html.IdFor(m => m.SigningCertificateStoreLocation)").change(function () { refreshSigningCertificates(); }); $("#@Html.IdFor(m => m.SigningCertificateStoreName)").change(function () { refreshSigningCertificates(); }); $("#@Html.IdFor(m => m.EnableTokenEndpoint), #@Html.IdFor(m => m.EnableAuthorizationEndpoint), #@Html.IdFor(m => m.AllowPasswordFlow), #@Html.IdFor(m => m.AllowAuthorizationCodeFlow), #@Html.IdFor(m => m.AllowAuthorizationCodeFlow), #@Html.IdFor(m => m.AllowHybridFlow)").change(function () { refreshEndpoints(); }); function refreshEncryptionCertificates() { var location = $("#@Html.IdFor(m => m.EncryptionCertificateStoreLocation)"), name = $("#@Html.IdFor(m => m.EncryptionCertificateStoreName)"), thumbprint = $("#@Html.IdFor(m => m.EncryptionCertificateThumbprint)"); if (location.val()) { name.parent().show(); if (name.val()) { thumbprint.parent().show(); thumbprint.children("option[value!='']").hide(); thumbprint.children("option[data-StoreLocation=" + location.val() + "][data-StoreName=" + name.val() + "]").show(); } else { thumbprint.parent().hide(); thumbprint.val(""); } } else { name.parent().hide(); name.val(""); thumbprint.parent().hide(); thumbprint.val(""); } } function refreshSigningCertificates() { var location = $("#@Html.IdFor(m => m.SigningCertificateStoreLocation)"), name = $("#@Html.IdFor(m => m.SigningCertificateStoreName)"), thumbprint = $("#@Html.IdFor(m => m.SigningCertificateThumbprint)"); if (location.val()) { name.parent().show(); if (name.val()) { thumbprint.parent().show(); thumbprint.children("option[value!='']").hide(); thumbprint.children("option[data-StoreLocation=" + location.val() + "][data-StoreName=" + name.val() + "]").show(); } else { thumbprint.parent().hide(); thumbprint.val(""); } } else { name.parent().hide(); name.val(""); thumbprint.parent().hide(); thumbprint.val(""); } } function refreshEndpoints() { refreshEnableTokenEndpoint(); refreshAllowAuthorizationCodeFlowVisibility(); refreshEnableAuthorizationEndpoint(); refreshAllowHybridFlowVisibility(); refreshAllowRefreshTokenFlowVisibility(); } function refreshDisableAccessTokenEncryption() { var accessTokenFormat = $("#@Html.IdFor(m => m.AccessTokenFormat)"); var disableAccessTokenEncryption = $("#@Html.IdFor(m => m.DisableAccessTokenEncryption)"); if (accessTokenFormat.val() === '@OpenIdServerSettings.TokenFormat.JsonWebToken') { disableAccessTokenEncryption.removeAttr("disabled"); } else { disableAccessTokenEncryption.attr('disabled', true); disableAccessTokenEncryption.prop("checked", false); } } function refreshEnableTokenEndpoint() { var enableTokenEndpoint = $("#@Html.IdFor(m => m.EnableTokenEndpoint)"); var allowPasswordFlow = $("#@Html.IdFor(m => m.AllowPasswordFlow)"); var allowClientCredentialsFlow = $("#@Html.IdFor(m => m.AllowClientCredentialsFlow)"); if (!enableTokenEndpoint.prop("checked")) { allowPasswordFlow.prop("checked", false); allowClientCredentialsFlow.prop("checked", false); } var showOrHide = enableTokenEndpoint.prop("checked") ? "show" : "hide"; allowPasswordFlow.parent().parent().collapse(showOrHide); allowClientCredentialsFlow.parent().parent().collapse(showOrHide); } function refreshEnableAuthorizationEndpoint() { var enableAuthorizationEndpoint = $("#@Html.IdFor(m => m.EnableAuthorizationEndpoint)"); var allowImplicitFlow = $("#@Html.IdFor(m => m.AllowImplicitFlow)"); if (!enableAuthorizationEndpoint.prop("checked")) { allowImplicitFlow.prop("checked", false); } allowImplicitFlow.parent().parent().collapse(enableAuthorizationEndpoint.prop("checked") ? "show" : "hide"); } function refreshAllowAuthorizationCodeFlowVisibility() { var allowAuthorizationCodeFlow = $("#@Html.IdFor(m => m.AllowAuthorizationCodeFlow)"); if ($("#@Html.IdFor(m => m.EnableTokenEndpoint)").prop("checked") && $("#@Html.IdFor(m => m.EnableAuthorizationEndpoint)").prop("checked")) { allowAuthorizationCodeFlow.parent().parent().collapse("show"); } else { allowAuthorizationCodeFlow.prop("checked", false); allowAuthorizationCodeFlow.parent().parent().collapse("hide"); } } function refreshAllowHybridFlowVisibility() { var allowHybridFlow = $("#@Html.IdFor(m => m.AllowHybridFlow)"); if ($("#@Html.IdFor(m => m.EnableTokenEndpoint)").prop("checked") && $("#@Html.IdFor(m => m.EnableAuthorizationEndpoint)").prop("checked")) { allowHybridFlow.parent().parent().collapse("show"); } else { allowHybridFlow.prop("checked", false); allowHybridFlow.parent().parent().collapse("hide"); } } function refreshAllowRefreshTokenFlowVisibility() { var allowRefreshTokenFlow = $("#@Html.IdFor(m => m.AllowRefreshTokenFlow)"); if ($("#@Html.IdFor(m => m.EnableTokenEndpoint)").prop("checked") && ($("#@Html.IdFor(m => m.AllowPasswordFlow)").prop("checked") || $("#@Html.IdFor(m => m.AllowAuthorizationCodeFlow)").prop("checked") || $("#@Html.IdFor(m => m.AllowHybridFlow)").prop("checked"))) { allowRefreshTokenFlow.parent().parent().collapse("show"); } else { allowRefreshTokenFlow.prop("checked", false); allowRefreshTokenFlow.parent().parent().collapse("hide"); } } }; //]]> </script>
the_stack
@model ProductDetailsModel @using Nop.Core @using Nop.Core.Domain.Seo; @using Nop.Core.Infrastructure; @using Nop.Services.Localization; @using Nop.Web.Models.Catalog; @using Nop.Web.Extensions; @using Nop.Web.Controllers; @functions { public List<ProductOverviewModel> GetProducts(dynamic itemset) { if (itemset == null) return new List<ProductOverviewModel>(); object[] ids = (object[])itemset; var productService = EngineContext.Current.Resolve<Nop.Services.Catalog.IProductService>(); var products = productService.GetProductsByIds(ids.Cast<string>().Select(id => int.Parse(id)).ToArray()); var controller = EngineContext.Current.Resolve<ProductController>(); return controller.PrepareProductOverviewModels( EngineContext.Current.Resolve<IWorkContext>(), EngineContext.Current.Resolve<IStoreContext>(), EngineContext.Current.Resolve<Nop.Services.Catalog.ICategoryService>(), productService, EngineContext.Current.Resolve<Nop.Services.Catalog.ISpecificationAttributeService>(), EngineContext.Current.Resolve<Nop.Services.Catalog.IPriceCalculationService>(), EngineContext.Current.Resolve<Nop.Services.Catalog.IPriceFormatter>(), EngineContext.Current.Resolve<Nop.Services.Security.IPermissionService>(), EngineContext.Current.Resolve<ILocalizationService>(), EngineContext.Current.Resolve<Nop.Services.Tax.ITaxService>(), EngineContext.Current.Resolve<Nop.Services.Directory.ICurrencyService>(), EngineContext.Current.Resolve<Nop.Services.Media.IPictureService>(), EngineContext.Current.Resolve<IWebHelper>(), EngineContext.Current.Resolve<Nop.Core.Caching.ICacheManager>(), EngineContext.Current.Resolve<Nop.Core.Domain.Catalog.CatalogSettings>(), EngineContext.Current.Resolve<Nop.Core.Domain.Media.MediaSettings>(), products, true, true, null, false, false).ToList<ProductOverviewModel>(); } public dynamic GetJsonObject(string uri, string userName, string password) { var request = WebRequest.Create(uri); request.ContentType = "application/json"; request.Method = "GET"; request.Credentials = new NetworkCredential(userName, password); try { var response = request.GetResponse(); if (response.ContentLength > 0) { StreamReader reader = new StreamReader(response.GetResponseStream()); var data = reader.ReadToEnd(); return Json.Decode(data); } } catch { // just return null when errors occur } return null; } } @{ Layout = "~/Views/Shared/_ColumnsTwo.cshtml"; //title, meta Html.AddTitleParts(!String.IsNullOrEmpty(Model.MetaTitle) ? Model.MetaTitle : Model.Name); Html.AddMetaDescriptionParts(Model.MetaDescription); Html.AddMetaKeywordParts(Model.MetaKeywords); var seoSettings = EngineContext.Current.Resolve<SeoSettings>(); //canonical URL if (seoSettings.CanonicalUrlsEnabled) { var productUrl = Url.RouteUrl("Product", new { SeName = Model.SeName }, this.Request.Url.Scheme); Html.AddCanonicalUrlParts(productUrl); } //open graph META tags if (seoSettings.OpenGraphMetaTags) { var storeName = EngineContext.Current.Resolve<IStoreContext>().CurrentStore.GetLocalized(x => x.Name); Html.AddHeadCustomParts("<meta property=\"og:type\" content=\"product\" />"); Html.AddHeadCustomParts("<meta property=\"og:title\" content=\"" + Html.Encode(Model.Name) + "\" />"); Html.AddHeadCustomParts("<meta property=\"og:description\" content=\"" + Html.Encode(Model.MetaDescription) + "\" />"); Html.AddHeadCustomParts("<meta property=\"og:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />"); Html.AddHeadCustomParts("<meta property=\"og:url\" content=\"" + Request.Url.AbsoluteUri + "\" />"); Html.AddHeadCustomParts("<meta property=\"og:site_name\" content=\"" + Html.Encode(storeName) + "\" />"); } //Twitter META tags if (seoSettings.TwitterMetaTags) { var storeName = EngineContext.Current.Resolve<IStoreContext>().CurrentStore.GetLocalized(x => x.Name); Html.AddHeadCustomParts("<meta property=\"twitter:card\" content=\"summary\" />"); Html.AddHeadCustomParts("<meta property=\"twitter:site\" content=\"" + Html.Encode(storeName) + "\" />"); Html.AddHeadCustomParts("<meta property=\"twitter:title\" content=\"" + Html.Encode(Model.Name) + "\" />"); Html.AddHeadCustomParts("<meta property=\"twitter:description\" content=\"" + Html.Encode(Model.MetaDescription) + "\" />"); Html.AddHeadCustomParts("<meta property=\"twitter:image\" content=\"" + Model.DefaultPictureModel.ImageUrl + "\" />"); Html.AddHeadCustomParts("<meta property=\"twitter:url\" content=\"" + Request.Url.AbsoluteUri + "\" />"); } // for code clarity var Product = Model; } <!--product breadcrumb--> @Html.Partial("_ProductBreadcrumb", Model.Breadcrumb) @Html.Widget("productdetails_after_breadcrumb", Model.Id) <div class="page product-details-page"> <div class="page-body"> @Html.Widget("productdetails_top", Model.Id) @using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" })) { <div itemscope itemtype="http://schema.org/Product" data-productid="@Model.Id"> <div class="product-essential"> @Html.Widget("productdetails_before_pictures", Model.Id) <!--product pictures--> @Html.Partial("_ProductDetailsPictures", Model) @Html.Widget("productdetails_after_pictures", Model.Id) <div class="overview"> <div class="product-name"> <h1 itemprop="name"> @Model.Name </h1> </div> @if (!String.IsNullOrEmpty(Model.ShortDescription)) { <div class="short-description"> @Html.Raw(Model.ShortDescription) </div> } @Html.Widget("productdetails_overview_top", Model.Id) <!--product SKU, manufacturer part number, stock info--> @Html.Partial("_SKU_Man_Stock", Model) <!--Back in stock subscription--> @Html.Partial("_BackInStockSubscription", Model) <!--product manufacturers--> @Html.Partial("_ProductManufacturers", Model.ProductManufacturers) <!--product reviews--> @Html.Partial("_ProductReviewOverview", Model.ProductReviewOverview) <!--sample download--> @Html.Partial("_DownloadSample", Model) <!--attributes--> @{ var dataDictAttributes = new ViewDataDictionary(); dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id); @Html.Partial("_ProductAttributes", Model.ProductVariantAttributes, dataDictAttributes) } <!--gift card--> @{ var dataDictGiftCard = new ViewDataDictionary(); dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id); @Html.Partial("_GiftCardInfo", Model.GiftCard, dataDictGiftCard) } <!--price & add to cart--> @{ var dataDictPrice = new ViewDataDictionary(); dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id); @Html.Partial("_ProductPrice", Model.ProductPrice, dataDictPrice) var dataDictAddToCart = new ViewDataDictionary(); dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id); @Html.Partial("_AddToCart", Model.AddToCart, dataDictAddToCart) } @Html.Partial("_ProductEmailAFriendButton", Model) @Html.Partial("_CompareProductsButton", Model) @Html.Partial("_ShareButton", Model) @Html.Widget("productdetails_overview_bottom", Model.Id) </div> @if (!String.IsNullOrEmpty(Model.FullDescription)) { <div class="full-description" itemprop="description"> @Html.Raw(Model.FullDescription) </div> } </div> @Html.Widget("productdetails_before_collateral", Model.Id) <div class="product-collateral"> @Html.Partial("_ProductTierPrices", Model.TierPrices) @Html.Partial("_ProductSpecifications", Model.ProductSpecifications) @Html.Partial("_ProductTags", Model.ProductTags) @{ // Call the Marketplace api to get the Frequently Bought Together products for this product var prediction = GetJsonObject("https://api.datamarket.azure.com/data.ashx/amla/mba/v1/Score?Id=<YOUR_MODEL_NAME>&Item=" + Product.Id, "AccountKey", "<YOUR_API_KEY>"); // Get the product information from the Database List<ProductOverviewModel> boughtTogether = GetProducts(prediction.ItemSet); } <!-- Apply HTML template for the Frequently Bought Together Products --> @Html.Partial("FrequentlyBoughtTogether", boughtTogether) @Html.Action("ProductsAlsoPurchased", "Product", new { productId = Model.Id }) @Html.Action("RelatedProducts", "Product", new { productId = Model.Id }) </div> </div> } @Html.Widget("productdetails_bottom", Model.Id) </div> </div>
the_stack
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width" /> <title>张寿宴玉雕工作室</title> @*@Scripts.Render("~/Scripts/UserAgent.js")*@ @*<script type="text/javascript"> var _userAgent = new userAgentObj(navigator.userAgent); if (_userAgent.device != __device_PC) { window.location.href = "/M/Home/Login"; } </script>*@ @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/common") @Scripts.Render("~/Scripts/jquery-1.10.2.min.js") @Scripts.Render("~/Scripts/validate/jquery.validate.min.js") @Scripts.Render("~/Scripts/layer/layer.js") @Scripts.Render("~/bundles/md5") <style type="text/css"> body { font-size: 15px; background-image: url(/Content/Images/login_bg2.jpg); background-size: 100%; /*background-position: right top;*/ /*background-repeat: no-repeat;*/ } input.watermark { color: #999; } .input_login { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -o-box-sizing: border-box; font-size: 15px; padding: 8px; width: 100%; border: 1px solid #D7D7D7; } .btn_login { font-size: 16px; color: #FFF; background-color: #36B5F8; /*padding-right: 20px; padding-left: 20px;*/ border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; padding-top: 8px; padding-bottom: 8px; width: 100%; cursor: pointer; } .btn_login:hover, .btn_login:focus { text-decoration: none; background-color: #09A4F7; } .btn_login:active, .btn_login.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn_login:disabled { text-decoration: none; background-color: #CCCCCC; } .btn_register { color: #F16777; font-size: 16px; background-color: white; border: 1px solid #F16777; padding-top: 8px; padding-bottom: 8px; width: 100%; cursor: pointer; } .btn_register:hover, .btn_register:focus { color: white; text-decoration: none; background-color: #F16777; } .btn_register:active, .btn_register.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn_register:disabled { text-decoration: none; background-color: #CCCCCC; } #divLoginAreaBackground { background-color: #FFF; height: 285px; width: 400px; margin-left: auto; margin-right: auto; /*filter: alpha(opacity=20); -moz-opacity: 0.2; -khtml-opacity: 0.2; opacity: 0.2;*/ z-index: 12; } #divLoginArea { /*color: white;*/ width: 400px; z-index: 13; } #divLoginContent { height: 450px; width: 460px; margin-top: 150px; margin-left: auto; margin-right: auto; background-color: #FFF; padding: 30px; box-sizing: border-box; box-shadow: 0px 0px 38px #fff; } #divLoginAreaMaskContent { z-index: 15; } </style> <script type="text/javascript"> var _password; var _returnUrl; $(document).ready(function () { watermark(); _returnUrl = getQueryString("returnUrl"); if (_returnUrl != null && _returnUrl != "") { _returnUrl = decodeURIComponent(_returnUrl); } ///// var account = getCookie("account"); _password = getCookie("password"); if (account != undefined && account != "") { $("#txtAccount").val(account); $("#chkRememberAccount").attr("checked", "checked"); } if (_password != undefined && _password != "") { $('#txtPassword').attr("type", "password"); $("#txtPassword").val(_password); $("#chkRememberPassword").attr("checked", "checked"); } if (account != undefined && account != "" && _password != undefined && _password != "") { login(); } $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { login(); } }); }); function watermark() { var accountWatermark = '账户'; $('#txtAccount').val(accountWatermark).addClass('watermark'); $('#txtAccount').blur(function () { if ($(this).val().length == 0) { $(this).val(accountWatermark).addClass('watermark'); } }); $('#txtAccount').focus(function () { if ($(this).val() == accountWatermark) { $(this).val('').removeClass('watermark'); } }); var passwordWatermark = '密码'; $('#txtPassword').val(passwordWatermark).addClass('watermark'); $('#txtPassword').blur(function () { if ($(this).val().length == 0) { $(this).val(passwordWatermark).addClass('watermark').attr("type", "text"); } }); $('#txtPassword').focus(function () { if ($(this).val() == passwordWatermark) { $(this).val('').removeClass('watermark').attr("type", "password"); } }); } function onLogin() { _password = null; login(); } function login() { if ($("#form").validate({ rules: { "txtAccount": "required", "txtPassword": "required" }, messages: { "txtAccount": "!", "txtPassword": "!" } }).form() == false) return; var args = new Object(); args.Account = $("#txtAccount").val(); if (_password != undefined && _password != "") { args.Password = _password; } else { args.Password = hex_md5($("#txtPassword").val()).toLowerCase(); } args.ReturnUrl = _returnUrl; showMask(); $.ajax({ url: "/Api/UserContext/Login", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { //alert(JSON.stringify(data)); if (data.Successful) { // if ($("#chkRememberPassword").is(":checked")) { setCookie("account", args.Account,30); setCookie("password", args.Password, 30); } else { removeCookie("password"); if ($("#chkRememberAccount").is(":checked")) { setCookie("account", args.Account, 30); } else { removeCookie("account"); } } //判断跳转地址 //encodeURIComponent("http://www.163.com") //"http%3A%2F%2Fwww.baidu.com" //http://localhost:3276/Home/Login?returnUrl=http%3A%2F%2Fwww.baidu.com if (_returnUrl == null || _returnUrl == "") { window.location.href = "/Member/Member"; } else { if (_returnUrl.indexOf("?") >= 0) { _returnUrl += "&"; } else { _returnUrl += "?"; } _returnUrl += "token=" + data.Data.Token; window.location.href = _returnUrl; } } else { hideMask(); layerAlert(data.Message, function () { $("#txtPassword").focus(); }); } }, error: function (xmlHttpRequest) { hideMask(); alert("Error: " + xmlHttpRequest.status); } }); } function showMask() { $("#btn_login").attr("disabled","disabled"); layer.load(0, { shade: [0.2, '#fff'] }); } function hideMask() { $("#btn_login").removeAttr("disabled"); layer.closeAll(); } </script> </head> <body> <div id="divLoginContent"> <div id="divLogin" style="text-align:center;"> <table style="width:100%" border="0" cellspacing="0"> <tr> <td align="center"><img src="/Content/Images/logo2.png" alt="" style="height:100px;" /></td> </tr> </table> </div> <div id="divLoginArea"> <form id="form"> <table width="100%" height="285" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td valign="top"> <div style="margin-left:30px;margin-top:30px; margin-right:30px;"> <div style="color:#36B5F8;font-size:17px;">张寿宴玉雕工作室</div> <div style="margin-top:20px;"> <input name="txtAccount" type="text" class="input_login" id="txtAccount" keyenter=keyenter /> </div> <div style="margin-top:10px;"> <input name="txtPassword" type="text" class="input_login" id="txtPassword" keyenter=keyenter /> </div> <div style="margin-top:10px;"> <div style="float:left"> <input name="" id="chkRememberAccount" type="checkbox" value="" /> <label for="chkRememberAccount">记住帐户</label> </div> <div style="float:left; margin-left:30px;"> <input name="" id="chkRememberPassword" type="checkbox" value="" /> <label for="chkRememberPassword">自动登录</label> </div> @*<div style="float:left; margin-left:30px;"> <a href="/Home/ResetPassword" style="color:black">找回密码</a> </div>*@ <div style="clear:both"></div> </div> <div style="margin-top:20px;"> <input name="btnLogin" type="button" class="btn_login" id="btnLogin" value="登 录" onclick="onLogin()" /> </div> </div> </td> </tr> </table> </form> </div> </div> </body> </html>
the_stack
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Sketch2Code - Transform sketches into HTML markup automagically!</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"> <link href="~/Content/octicons.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800"> <script src="~/Scripts/modernizr-2.6.2.js"></script> <script src="~/Scripts/html2canvas.min.js"></script> <link href="~/Content/Site.css" rel="stylesheet" type="text/css" /> @RenderSection("Content", required: false) <script type='text/javascript'> var appInsights = window.appInsights || function (config) { function r(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, u = document, e = window, o = 'script', s = u.createElement(o), i, f; for (s.src = config.url || '//az416426.vo.msecnd.net/scripts/a/ai.0.js', u.getElementsByTagName(o)[0].parentNode.appendChild(s), t.cookie = u.cookie, t.queue = [], i = ['Event', 'Exception', 'Metric', 'PageView', 'Trace', 'Ajax']; i.length;)r('track' + i.pop()); return r('setAuthenticatedUserContext'), r('clearAuthenticatedUserContext'), config.disableExceptionTracking || (i = 'onerror', r('_' + i), f = e[i], e[i] = function (config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o), s }), t }({ instrumentationKey: '0bf8d80a-82a1-4966-947c-9d7b15bf42d8' }); window.appInsights = appInsights; appInsights.trackPageView(); </script> </head> <body> <div id="disclaimer" class="disclaimer text-white hide" aria-hidden="true"> This site uses cookies for analytics, personalized content and ads. By continuing to browse this site, you agree to this use. <a class="learn-more" href="https://privacy.microsoft.com/en-US/">Learn more</a> <button class="close" id="cookie-consent" aria-label="Close">X</button> </div> <div> <div class="container-fl"> <div class="row header-row"> <div class="col-lg-2 col-xl-2 col-md-2 col-6"><img alt="Microsoft Logo" class="img-fluid float-left d-flex flex-column justify-content-end center-logo" src="~/content/img/logo_MS.png"></div> <div class="col header-column justify-content-center"> @RenderSection("Steps") </div> <div class="col-lg-2 col-xl-2 col-md-2 col-6 float-left d-flex flex-column justify-content-start"><a class="link d-flex flex-column justify-content-end" target="_blank" href="https://www.ailab.microsoft.com/">AI Lab</a></div> </div> </div> <div class="container-fl"> @RenderBody() </div> <div class="fixed-bottom"> <div class="row"> <div class="col float-left d-flex flex-column justify-content-end align-items-start"><img alt="Microsoft Logo" class="img-fluid float-left d-flex flex-column justify-content-end center-logo-bottom" src="~/content/img/logo_MS.png"></div> <div class="col"><img alt="Logo web" class="img-fluid float-right hidden-responsive" src="/content/img/img_spareMobile.svg" id="img_bottomRight"></div> </div> <div class="row2"> <div class="col footer step"> <span>Your picture may be used to improve the underlying AI.</span> <div class="footer-links"> <div class="col col-0 line-block" style="margin-left:6px!important; margin-bottom:2em;"></div> <div class="col col-0" style="margin-bottom:2em;"><a target="_blank" href="https://www.ailab.microsoft.com/">AI Lab</a></div> <div class="col col-0 line-block" style="margin-bottom:2em;"><a target="_blank" href="https://support.microsoft.com/en-us/contactus">Contact Us</a></div> <div class="col col-0 line-block" style="margin-bottom:2em;"><a target="_blank" href="https://go.microsoft.com/fwlink/?LinkId=521839">Privacy &amp; Cookies</a></div> <div class="col col-0 line-block" style="margin-bottom:2em;"><a target="_blank" href="https://go.microsoft.com/fwlink/?LinkID=206977">Terms of use</a></div> <div class="col col-0 line-block" style="margin-bottom:2em;"><a target="_blank" href="https://www.microsoft.com/trademarks">Trademarks</a></div> <div class="col col-0 line-block" style="margin-bottom:2em;"><span>© Microsoft 2018<br></span></div> <div class="col col-0 line-block"></div> </div> </div> </div> </div> </div> <script src="~/Scripts/jquery-3.0.0.js"></script> <script src="~/Scripts/bootstrap.js"></script> @RenderSection("Scripts", required: false) <script type="text/javascript"> var consent = function () { return (document.cookie.indexOf("Sketchconsent") != -1); } $(document).ready(function () { var setConsentCookie = function () { var d = new Date(); d.setTime(d.getTime() + (99999 * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = "Sketchconsent=1;" + expires + ";path=/"; $("#disclaimer").hide(); }; if (!consent()) { $("#disclaimer").show(); $("#cookie-consent").click(function () { setConsentCookie(); }); $("a").click(function () { setConsentCookie(); }); } }); </script> <!--Adobe analytics--> <script src="https://az725175.vo.msecnd.net/scripts/jsll-4.js" type="text/javascript"> </script> <script> const config = { syncMuid: awa.utils.isValueAssigned(window.awa.cookie.getCookie('Sketchconsent')), userConsentCookieName: 'Sketchconsent', autoCapture: { lineage: true, scroll: true }, coreData: { appId: 'Sketch2Code', env: 'prod', market: 'en-us', pageName: 'Sketch2Code', pageType: 'html' }, useShortNameForContentBlob: true }; if (consent()) awa.init(config); </script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-121469252-4"></script> <script> if (consent()) { window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-121469252-4'); } </script> <!-- Facebook Pixel Code --> <script> if (consent()) { !function (f, b, e, v, n, t, s) { if (f.fbq) return; n = f.fbq = function () { n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments) }; if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0; t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s) }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '435868603227390'); fbq('track', 'PageView'); } </script> <noscript> <img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=435868603227390&ev=PageView&noscript=1" /> </noscript> <!-- End Facebook Pixel Code --> <!-- Twitter universal website tag code --> <script> if (consent()) { !function (e, t, n, s, u, a) { e.twq || (s = e.twq = function () { s.exe ? s.exe.apply(s, arguments) : s.queue.push(arguments); }, s.version = '1.1', s.queue = [], u = t.createElement(n), u.async = !0, u.src = '//static.ads-twitter.com/uwt.js', a = t.getElementsByTagName(n)[0], a.parentNode.insertBefore(u, a)) }(window, document, 'script'); // Insert Twitter Pixel ID and Standard Event data below twq('init', 'nv9r3'); twq('track', 'PageView'); } </script> <!-- End Twitter universal website tag code --> <!-- Twitter universal website tag code --> <img height="1" width="1" style="display:none;" alt="" src="https://analytics.twitter.com/i/adsct?p_id=Twitter&p_user_id=0&txn_id=nv9r3&events=%5B%5B%22pageview%22%2Cnull%5D%5D&tw_sale_amount=0&tw_order_quantity=0" /> <img height="1" width="1" style="display:none;" alt="" src="//t.co/i/adsct?p_id=Twitter&p_user_id=0&txn_id=nv9r3&events=%5B%5B%22pageview%22%2Cnull%5D%5D&tw_sale_amount=0&tw_order_quantity=0" /> <!-- End Twitter universal website tag code --> <!-- LinkedIn--> <script type="text/javascript"> _linkedin_data_partner_id = "7850"; </script> <script type="text/javascript"> if (consent()) { (function () { var s = document.getElementsByTagName("script")[0]; var b = document.createElement("script"); b.type = "text/javascript"; b.async = true; b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js"; s.parentNode.insertBefore(b, s); })(); } </script> <noscript> <img height="1" width="1" style="display:none;" alt="" src="https://dc.ads.linkedin.com/collect/?pid=7850&fmt=gif" /> </noscript> </body> </html>
the_stack
@{ ViewBag.Title = "权限管理"; Layout = "~/Views/Shared/_Layout.cshtml"; } <link rel="stylesheet" href="~/js/plugins/zTree/3.5/metroStyle/metroStyle.css?201811201906" /> <style> body{ min-width: 800px; overflow-x: auto; } div { display: inline; } div.left { float: left; width: 250px; height: 80%; overflow: auto; } div.right { float: left; width: 500px; height: 100%; overflow: auto; } div.middle { float: left; width: 100px; height: 80%; overflow: auto; padding-top: 250px; text-align: center; } .ztree li span.button.chk.checkbox_true_full { background-position: -26px -5px; background-color: #05ef834d; } </style> <div class="left"> <ul id="tree" class="ztree"></ul> </div> <div class="middle"> <button type="button" class="btn btn-success authorization" style="display: none" action-id="role-action-save" v-on:click="RoleActionSave" action-name="提交保存"> 提交保存 </button> </div> <div class="right" style="display: none" v-show="showControl"> <div class="searchAreaBox"> <div class="searchArea"> <input type="text" name="searchArea" placeholder="输入搜索关键字"> <i class="searchAreaBtn fa fa-search"></i> </div> <div class="clearft"></div> </div> <ul id="tree2" class="ztree"></ul> </div> @section Scripts{ <script src="~/js/plugins/zTree/3.5/jquery.ztree.all.min.js?201811201906"></script> <script type="text/javascript"> var vm = new Vue({ el: 'body', data: { showControl: false, currentRow: {} }, computed: {}, methods: { RoleActionSave: function () { var tree1Obj = $.fn.zTree.getZTreeObj("tree"); var nodes1 = tree1Obj.getSelectedNodes(); if (nodes1.length !== 1) { swal({ title: "提交失败!", text: '没有要修改的!', type: "error" }); return; } var node = nodes1[0].getParentNode(); if (node == null) { swal({ title: "提交失败!", text: '获取数据失败!', type: "error" }); return; } var selectNodes = getSelectedNodes(); QQT.ajax('/Admin/Role/AddRoleActions', 'POST', { ActionId: nodes1[0].ActionId, MenuId: node.Tid, ActionList: selectNodes }, true) .done(function (response) { swal("成功啦!", "操作成功!", "success"); }); } }, ready: function () { auth(); $(window).resize(function () { //设置tree的初始化高度 $('.left').css('height',$(window).height()); $('.right').css('height',$(window).height()); $('.right').css('width',$(window).width()-250-100); }); $('.left').css('height',$(window).height()); $('.right').css('height',$(window).height()); $('.right').css('width',$(window).width()-250-100); //获取总的数据 QQT.ajax('/Admin/Home/GetMenuActionTree', 'Post', {}) .done(function (response) { ready(response.Data); }); QQT.ajax('/Admin/Home/GetControllerActions', 'Post', {}) .done(function (response) { ready2(response.Data); }); } }); function ready(zNodes) { var setting = { view: { selectedMulti: false }, check: { enable: false }, callback: { onClick: onClick }, usericon:{ // 折叠icon OPEN: "open fa ftopen fa-folder-open", // 打开文件图标 CLOSE: "close fa ftclose fa-folder", // 折叠文件图标 OPENDK:'open icon-folder ace-icon tree-minus', // 打开状态图标 CLOSEZD:'close icon-folder ace-icon tree-plus', // 折叠状态图标 DOCU: "docu", // 子节点图标 CHILDRENNODE: "fa-book", // 复选框图标 UNFACHECK: "fa fa-check", FACHECKED: "fa fa-times", // 编辑图标 EDIT: "fa-pencil-square-o", // 移除图标 REMOVE: "fa-eraser", // 增加节点图标 ADDNODE: "fa-plus-square" } }; $.fn.zTree.init($("#tree"), setting, zNodes); var treeObj = $.fn.zTree.getZTreeObj("tree"); treeObj.expandAll(true); } function ready2(zNodes) { var setting = { view: { selectedMulti: true }, check: { enable: true }, usericon:{ // 折叠icon OPEN: "open fa ftopen fa-folder-open", // 打开文件图标 CLOSE: "close fa ftclose fa-folder", // 折叠文件图标 OPENDK:'open icon-folder ace-icon tree-minus', // 打开状态图标 CLOSEZD:'close icon-folder ace-icon tree-plus', // 折叠状态图标 DOCU: "docu", // 子节点图标 CHILDRENNODE: "fa-book", // 复选框图标 UNFACHECK: "fa fa-check", FACHECKED: "fa fa-times", // 编辑图标 EDIT: "fa-pencil-square-o", // 移除图标 REMOVE: "fa-eraser", // 增加节点图标 ADDNODE: "fa-plus-square" } }; $.fn.zTree.init($("#tree2"), setting, zNodes); var treeObj = $.fn.zTree.getZTreeObj("tree2"); treeObj.expandAll(true); } function onClick(event, treeId, treeNode, clickFlag) { if (treeNode.Tid !== 0) { vm.showControl = false; return; } QQT.ajax('/Admin/Role/GetRoleActions', 'POST', { ActionId: treeNode.ActionId, MenuId: treeNode.getParentNode().Tid }) .done(function (response) { $.fn.zTree.destroy("tree2"); ready2(response.Data); vm.showControl = true; }); } function getSelectedNodes() { var treeObj = $.fn.zTree.getZTreeObj("tree2"); var nodes = treeObj.getCheckedNodes(true); var re = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (node.children != null) continue; re.push(node.getParentNode().Name + ',' + node.Name); } return re; } // 地区搜索 var parentArray = []; var childArray = []; // 递归获取目标节点所有父节点 function getParentsNode(treeNode){ var thisParentNode = treeNode.getParentNode(); //得到该节点的父节点 if( thisParentNode != null ){ // 父节点存在 parentArray.push(thisParentNode); // 储存至数组 getParentsNode(thisParentNode); // 重调 }else{ return false; } } // 递归获取目标节点所有子节点 function getChildrenNode(treeNode){ var thisIsParent = treeNode.isParent; // 获取目标节点 isParent 属性,判断是否为父节点 if( thisIsParent == true ){ var thisChildrenNode = treeNode.children; // 得到该节点的子节点集合 for(var i=0;i<thisChildrenNode.length;i++){ childArray.push(thisChildrenNode[i]); // 将该子节点加入数组中 getChildrenNode(thisChildrenNode[i]); // 重调 } }else{ return false; } } //匹配节点 function matchNode(treeNode,num){ var inputArea = $("input[name='searchArea']"); var name = treeNode.name; var entityCode = treeNode.entity_code|| ''; var val = inputArea.val(); // 获取检索值 var numName = name.indexOf(val); var numCode = entityCode.indexOf(val); var num = -1; if( numName != -1 || numCode !=-1 ){ num = 1; } if( numName == -1 && numCode == -1 ){ num = -1; } return num; } // 节点匹配成功 function checkTrueArray(arr,treeNode){ var thisTid = treeNode.tId; var thisLi = $("#"+thisTid); for(var n=0;n<arr.length;n++){ var thisNodeId = arr[n].tId; var thisNodeLi = $("#"+thisNodeId); thisLi.show(); thisNodeLi.show(); } } // 节点匹配失败 function checkFalseArray(arr,treeNode){ var result = []; var result2 = []; var thisTid = treeNode.tId; var thisLi = $("#"+thisTid); var val = inputArea.val(); // 获取检索值 var thisParent = treeNode.getParentNode(); // 获取目标节点父节点 if( thisParent != null ){ // 有父节点 var thisBrotherArr = treeNode.getParentNode().children; // 得到包含自身的兄弟数组 for(var m=0;m<arr.length;m++){ // 匹配父节点 var num = matchNode(arr[m]); if( num != -1 ){ result.push(arr[m]); } } var resultLength = result.length; for( var m=0;m<thisBrotherArr.length;m++ ){ // 匹配兄弟节点 var num = matchNode(thisBrotherArr[m]); if( num != -1 ){ result2.push(thisBrotherArr[m]); } } var resultLength2 = result2.length; // 对于自身匹配失败的节点,要显示必须满足有父节点匹配成功,且兄弟级节点都匹配失败 if( (resultLength == 0 && resultLength2 == 0) || resultLength2 != 0 ){ thisLi.hide(); } if( resultLength !=0 && resultLength2 == 0 ){ thisLi.show(); } }else{ thisLi.hide(); } } // 目标节点匹配失败 目标节点即有父节点又有子节点 function checkAllArray(arr,arr2,treeNode){ var result = []; var result2 = []; var thisTid = treeNode.tId; var thisLi = $("#"+thisTid); var val = inputArea.val(); // 获取检索值 for(var m=0;m<arr.length;m++){ // 匹配子节点或父节点 var num = matchNode(arr[m]); if( num != -1 ){ result.push(arr[m]); // 匹配成功储存至数组 } } var resultLength = result.length; // 获取匹配成功后返回的数组长度 for(var m=0;m<arr2.length;m++){ // 匹配子节点或父节点 var num = matchNode(arr2[m]); if( num != -1 ){ result2.push(arr2[m]); // 匹配成功储存至数组 } } var resultLength2 = result2.length; // 获取匹配成功后返回的数组长度 if( resultLength == 0 && resultLength2 == 0 ){ // 子节点和父节点都匹配失败 thisLi.hide(); }else{ thisLi.show(); // 有一种匹配成功或都匹配成功 } } function searchArea(treeId, treeNode){ // 定义搜索方法 var inputArea = $("input[name='searchArea']"); var val = inputArea.val(); // 获取检索值 var treeObj=$.fn.zTree.getZTreeObj("tree2"); // 设置根节点 var node = treeObj.getNodes(); // 获取根节点 var nodes = treeObj.transformToArray(node); // 获取所有节点 console.log(nodes); for(var i=0;i<nodes.length;i++){ var thisNodePid = nodes[i].pId; var thisParentNode = parentArray = []; childArray = []; getParentsNode(nodes[i]); // 获取目标节点所有父节点 返回数组 getChildrenNode(nodes[i]); // 获取目标节点所有子节点 返回数组 var num = matchNode(nodes[i]); if( nodes[i].isParent == false ){ if( num != -1 ){ checkTrueArray(parentArray,nodes[i]); }else{ checkFalseArray(parentArray,nodes[i]); } } if( nodes[i].isParent == true ){ if( num != -1 ){ checkTrueArray(parentArray,nodes[i]); checkTrueArray(childArray,nodes[i]); }else{ checkAllArray(parentArray,childArray,nodes[i]); } } } } // 调用搜索方法 $(".searchAreaBtn").click(function(treeId, treeNode){ searchArea(treeId, treeNode); }); var inputArea = $("input[name='searchArea']"); inputArea.keyup(function(treeId, treeNode,e){ var e = event || window.event; var val = inputArea.val(); if( e.keyCode == 13 || val == "" ){ searchArea(treeId, treeNode); } }); </script> }
the_stack
@page "/" @inject JobsService JobsService @inject Blazored.Storage.ILocalStorage LocalStorage @inject IJSRuntime JSRuntime @inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper @using Benchmarks.UI.App.Services @using System.Web @using System.Text @using System.IO @using Newtonsoft.Json; <!-- Nav tabs --> <ul class="nav nav-pills" role="tablist"> <li class="nav-item"><NavLink href="#home" class="nav-link " role="tab" data-toggle="tab" Match=NavLinkMatch.All>Current Job</NavLink></li> <li class="nav-item"><NavLink href="#saved" class="nav-link" role="tab" data-toggle="tab" >Saved Jobs</NavLink></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane show active" id="home" role="tabpanel"> <div class="row"> <div class="form-group col-md-4 col-xl-2"> <label>Server</label> <select class="form-control" bind="@currentServer"> @foreach (var serverDefinition in JobsService.GetServerDefinitions()) { <option value="@serverDefinition.Arguments">@serverDefinition.DisplayName</option> } </select> <span class="text-muted form-text small">The hardware to run the scenarios on.</span> </div> <div class="form-group col-md-4 col-xl-2"> <label>Host</label> <select class="form-control" bind="@host"> <option value="">Default</option> <option value="KestrelSockets">Kestrel/Sockets</option> <option value="KestrelLibuv">Kestrel/Libuv</option> <option value="HttpSys">HTTPSys</option> <option value="IISInProcess">IIS In Proc</option> <option value="IISOutOfProcess">IIS Out Of Proc</option> <option value="Docker">Docker</option> </select> <span class="text-muted form-text small">The scenario type to run.</span> </div> <div class="form-group col-md-4 col-xl-2"> <label>AspNetCore</label> <select class="form-control" bind="@aspnetcore"> <option value="Latest">Latest (3.0.*)</option> <option value="2.2">2.2.x</option> <option value="2.2.*">2.2.x servicing</option> <option value="2.1">2.1.x</option> <option value="2.1.*">2.1.x servicing</option> <option value="Custom">Custom</option> </select> <span class="text-muted form-text small">The ASP.NET Core version to use.</span> </div> <div class="form-group col-md-4 col-xl-2"> <label>Runtime</label> <select class="form-control" bind="@runtime"> <option value="">Matching ASP.NET Core</option> <option value="3.0.*">Latest (3.0.*)</option> <option value="2.2">2.2.*</option> <option value="2.2.*">2.2 servicing</option> <option value="2.1">2.1.*</option> <option value="2.1.*">2.1 servicing</option> <option value="Custom">Custom</option> </select> <span class="text-muted form-text small">The .NET Core runtime version to use.</span> </div> </div> <div class="row"> <div class="form-group col-md-6 col-lg-2"> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="saveCheckbox" onchange="@OnSaveCheckboxChanged" /> <label class="custom-control-label" for="saveCheckbox">Save results</label> <span class="text-muted form-text small">Check to save the results for later comparison.</span> </div> <div class="form-group"> <label for="descriptionInput">Description</label> <input class="form-control" type="text" id="descriptionInput" bind="description" /> <span class="text-muted form-text small">Provide a description for the saved results.</span> </div> </div> @if (savedJobs.Any()) { <div class="form-group col-md-6 col-lg-2"> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="compareCheckbox" onchange="@OnCompareCheckboxChanged" /> <label class="custom-control-label" for="compareCheckbox">Compare to</label> <span class="text-muted form-text small">Check to compare the results to a previously saved job.</span> </div> @if (compare) { <select class="form-control" bind="@compareToJob"> @foreach (var savedJob in savedJobs) { <option value="@savedJob.Key">@savedJob.Key</option> } </select> } </div> } <div class="form-group col-md-4 col-xl-2"> @if (aspnetcore == "Custom") { <input type="text" class="form-control" bind="customAspNetCore" /> <span class="text-muted form-text small">Specific version of ASP.NET Core. <a target="_blank" href="https://dotnet.myget.org/feed/aspnetcore-dev/package/nuget/Microsoft.AspNetCore.App">Complete list.</a></span> } </div> <div class="form-group col-md-4 col-xl-2"> @if (runtime == "Custom") { <input type="text" class="form-control" bind="customRuntime" /> <span class="text-muted form-text small">Specific version of.NET Core. <a target="_blank" href="https://dotnet.myget.org/feed/dotnet-core/package/nuget/Microsoft.NetCore.App">Complete list.</a></span> } </div> </div> <div class="row"> </div> <div class="row"> <div class="form-group col-md-4 col-xl-2"> <label>Scenario</label> <select class="form-control" bind="@scenario"> @foreach (var jobDefinition in JobsService.GetJobDefinitions()) { <option value="@jobDefinition.Arguments">@jobDefinition.DisplayName</option> } </select> <span class="text-muted form-text small">The scenario type to run.</span> </div> <div class="form-group col-md-4 col-xl-2"> <label>Database</label> <select class="form-control" bind="@database"> <option value="">None</option> <option value="--database PostgreSql">Postgres</option> <option value="--database SqlServer">SQL Server</option> <option value="--database MySql">MySQL</option> <option value="--database MongoDb">MongoDB</option> </select> <span class="text-muted form-text small">The scenario type to run.</span> </div> <div class="form-group col-md-4 col-xl-1"> <label>Warmup</label> <input type="text" class="form-control" bind="warmup" /> <span class="text-muted form-text small">Warmup time, in seconds. '0' to disable it.</span> </div> <div class="form-group col-md-4 col-xl-1"> <label>Duration</label> <input type="text" class="form-control" bind="duration" /> <span class="text-muted form-text small">Duration of the run, in seconds.</span> </div> <div class="form-group col-md-4 col-xl-1"> <label>Samples</label> <input type="text" class="form-control" bind="samples" /> <span class="text-muted form-text small">Number of benchmarks to run.</span> </div> <div class="form-group col-md-4 col-xl-1"> <label>Extremes</label> <input type="text" class="form-control" bind="extremes" /> <span class="text-muted form-text small">Number of benchmarks to exclude from the samples.</span> </div> </div> <div class="row"> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="quietCheckbox" bind="quiet" /> <label class="custom-control-label" for="quietCheckbox">Quiet mode</label> <span class="text-muted form-text small">Check to only display the results.</span> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="markdownCheckbox" bind="markdown" /> <label class="custom-control-label" for="markdownCheckbox">Markdown</label> <span class="text-muted form-text small">Check to display the results in Markdown.</span> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="collectCheckbox" bind="collect" /> <label class="custom-control-label" for="collectCheckbox">Collect Trace</label> <span class="text-muted form-text small">Check to collect a trace.</span> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="eventPipeCheckbox" bind="eventpipe" /> <label class="custom-control-label" for="eventPipeCheckbox">Event Pipe</label> <span class="text-muted form-text small">Check to enable Event Pipe.</span> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="fetchCheckbox" bind="fetch" /> <label class="custom-control-label" for="fetchCheckbox">Fetch deployed application</label> <span class="text-muted form-text small">Check to fetch the published output of the application.</span> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="selfContainedCheckbox" bind="selfContained" /> <label class="custom-control-label" for="selfContainedCheckbox">Self-contained</label> <span class="text-muted form-text small">Check to publish a self-contained app.</span> </div> </div> <div class="row"> <div class="form-group col-lg-3"> <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" ref="outputFile" onchange="@UploadOutputFile" /> <label class="custom-file-label" for="customFile">Custom Files</label> <span class="text-muted form-text small">This file will be copied in the published folder.</span> </div> <ul class="list-group"> @foreach (var entry in _outputFiles) { <li class="list-group-item"> <code>@entry.Value</code> <a class="btn btn-danger btn-sm float-right ml-1" role="button" href="#" onclick="@(() => DeleteOutputFile(entry.Key))">Delete</a> </li> } </ul> </div> </div> <div class="row"> <div class="form-group col-lg-3"> <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" ref="nugetPackage" onchange="@UploadNugetPackage" /> <label class="custom-file-label" for="customFile">Nuget Packages</label> <span class="text-muted form-text small">These files will be extracted in the published folder.</span> </div> <ul class="list-group"> @foreach (var entry in _nugetPackages) { <li class="list-group-item"> <code>@entry.Value</code> <a class="btn btn-danger btn-sm float-right ml-1" role="button" href="#" onclick="@(() => DeleteNugetPackage(entry.Key))">Delete</a> </li> } </ul> </div> </div> <div class="form-group"> <a class="btn btn-primary" role="button" href="#" onclick="@RunJob">Run</a> <a class="btn btn-danger" role="button" href="#" onclick="@StopJob">Stop</a> <a class="btn btn-secondary" role="button" href="#" onclick="@Print">Print</a> <a class="btn btn-secondary" role="button" href="#" onclick="@Share">Permalink</a> </div> <div class="row"> <div class="col-12"> <label>Output</label> <pre class="output" ref="outputPre">@standardOutput</pre> </div> @if (_artifacts.Count > 0) { <div class="col-md-6"> <label>Artifacts</label> <ul class="list-group col-lg-4"> @foreach (var filename in _artifacts) { var url = "api/download/" + filename; <li class="list-group-item"> <a class="nav-link" href="@url" target="_blank"> @filename </a> </li> } </ul> </div> } </div> </div> <div class="tab-pane" id="saved" role="tabpanel"> <h1>Saved Jobs</h1> <div class="row"> <div class="col-md-6 col-lg-2"> <ul class="list-group"> @foreach (var key in savedCommands.Keys) { <li class="list-group-item "> @key <a class="btn btn-danger btn-sm float-right ml-1" role="button" href="#" onclick="@(() => DeleteCommand(key))">Delete</a> <a class="btn btn-primary btn-sm float-right ml-1" role="button" href="#" onclick="@(() => LoadCommand(key))">Load</a> </li> } </ul> </div> </div> <div class="form-inline row"> <div class="mx-sm-3 mt-1"> <input class="form-control" type="text" id="saveCommandInput" bind="commandName" placeholder="Name"/> </div> <a class="btn btn-primary mr-sm-2 mt-1" role="button" href="#" onclick="@SaveCommand">Save</a> </div> </div> </div> @functions { string currentServer; string scenario; string warmup, duration, samples, extremes, database, host; string processId; string jobUniqueId, comparedToUniqueId; bool quiet, markdown, collect, eventpipe, fetch, selfContained; bool save, compare; string description, compareToJob; string aspnetcore, runtime; string customAspNetCore, customRuntime; Dictionary<string, string> savedJobs = new Dictionary<string, string>(); ElementRef outputFile, nugetPackage, outputPre; Dictionary<string, string> _nugetPackages = new Dictionary<string, string>(); Dictionary<string, string> _outputFiles = new Dictionary<string, string>(); List<string> _artifacts = new List<string>(); DateTime _lastOutputChangedUTC; StringBuilder standardOutput = new StringBuilder(); // Commands Dictionary<string, Command> savedCommands = new Dictionary<string, Command>(); string commandName; protected override async Task OnInitAsync() { var queryString = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(new Uri(UriHelper.GetAbsoluteUri()).Query); if (queryString.ContainsKey("command")) { try { var command = JsonConvert.DeserializeObject<Command>(queryString["command"]); await LoadCommand(command); } catch { } } else { currentServer = JobsService.GetServerDefinitions().First().Arguments; scenario = JobsService.GetJobDefinitions().First().Arguments; warmup = "15"; duration = "15"; samples = "1"; extremes = "0"; database = ""; host = ""; quiet = false; markdown = false; aspnetcore = "Latest"; runtime = ""; } savedJobs = await GetSavedJobs(); compareToJob = savedJobs.FirstOrDefault().Key; savedCommands = await GetSavedCommands(); } async Task RunJob() { if (save && String.IsNullOrWhiteSpace(description)) { standardOutput.Clear(); standardOutput.Append("The 'description' field is mandatory when using the 'save' option."); return; } if (aspnetcore == "Custom") { // Matching ASP.NET Core is not available in this case if (String.IsNullOrWhiteSpace(runtime)) { standardOutput.Append("The 'runtime' field has to be a specific version when using a custom ASP.NET Core version."); return; } if (String.IsNullOrWhiteSpace(customAspNetCore)) { standardOutput.Append("A custom ASP.NET Core version needs to be specified."); return; } } if (runtime == "Custom") { if (String.IsNullOrWhiteSpace(customRuntime)) { standardOutput.Append("A custom.NET Core version needs to be specified."); return; } } // Stop any running Job await StopJob(); standardOutput.Clear(); _artifacts.Clear(); jobUniqueId = Guid.NewGuid().ToString("n"); var arguments = await BuildArguments(); _lastOutputChangedUTC = DateTime.UtcNow; processId = JobsService.StartDriver(arguments, standardOutput, OnStandardOutputChanged, OnJobFinished); } async void OnStandardOutputChanged() { StateHasChanged(); try { await JSRuntime.InvokeAsync<string>("scrollToBottom", outputPre); } catch { // async void errors crash the process, if we can't scroll to the bottom it's not a big deal } } async Task StopJob() { standardOutput.AppendLine("STOPPING ..."); await JobsService.StopProcess(processId); standardOutput.AppendLine("STOPPED !!!"); await JSRuntime.InvokeAsync<string>("scrollToBottom", outputPre); } async Task Print() { standardOutput.Clear(); standardOutput.Append(await BuildArguments()); await JSRuntime.InvokeAsync<string>("scrollToBottom", outputPre); } async Task Share() { var uri = UriHelper.GetAbsoluteUri(); uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(uri, "command", JsonConvert.SerializeObject(await SerializeCommand())); standardOutput.Clear(); standardOutput.Append(uri); } async Task OnJobFinished() { if (save) { var jobResultsFilename = JobsService.GetDriverFileName(jobUniqueId + ".bench.json"); if (File.Exists(jobResultsFilename)) { savedJobs = await GetSavedJobs(); savedJobs[description] = File.ReadAllText(jobResultsFilename); await LocalStorage.SetItem("SavedJobs", savedJobs); File.Delete(jobResultsFilename); StateHasChanged(); } } standardOutput.AppendLine("FINISHED !!!"); await JSRuntime.InvokeAsync<string>("scrollToBottom", outputPre); var output = standardOutput.ToString(); foreach(var marker in new[] {"Downloading trace: ", "Creating published archive: "}) { var index = 0; do { index = output.IndexOf(marker, index); if (index != -1) { index = index + marker.Length; var filename = output.Substring(index, output.IndexOfAny(new char[] { '\n', '\r' }, index) - index); _artifacts.Add(filename); } } while (index != -1); } StateHasChanged(); } MarkupString FormatOutput(string output) { return new MarkupString(HttpUtility.HtmlEncode(output).Replace(Environment.NewLine, "<br />")); } async Task<string> BuildArguments() { var args = new StringBuilder(); args.Append(currentServer).Append(" "); args.Append(scenario).Append(" "); args.Append($"--warmup {warmup} "); args.Append($"--duration {duration} "); if (extremes != "0") { args.Append($"-x {extremes} ").Append(" "); } if (samples != "1") { args.Append($"-i {samples} "); } if (!String.IsNullOrEmpty(database)) { args.Append($"{database} "); } if (!String.IsNullOrEmpty(host)) { args.Append($"--webHost {host} "); } foreach (var nugetPackage in _nugetPackages.Keys) { args.Append($"--nuget-package \"{nugetPackage}\" "); } foreach (var outputFile in _outputFiles.Keys) { args.Append($"--outputFile \"{outputFile}\" "); } if (quiet) { args.Append($"--quiet "); } if (markdown) { args.Append($"--markdown "); } if (save) { // Create a new unique local file. It will then be saved on local storage using the user provided name and deleted. args.Append($"--save {jobUniqueId} "); } if (compare) { var serverJobs = await GetSavedJobs(); if (serverJobs.TryGetValue(compareToJob, out var job)) { comparedToUniqueId = Guid.NewGuid().ToString("n"); File.WriteAllText(JobsService.GetDriverFileName(comparedToUniqueId + ".bench.json"), job); args.Append($"--diff {comparedToUniqueId} "); } } if (!String.IsNullOrWhiteSpace(description)) { args.Append($"--description \"{description}\" "); } if (aspnetcore == "Custom") { args.Append($"--aspNetCoreVersion \"{customAspNetCore}\" "); if (runtime == "Custom") { args.Append($"--runtimeVersion \"{customRuntime}\" "); } else { args.Append($"--runtimeVersion \"{runtime}\" "); } } else { args.Append($"--aspNetCoreVersion \"{aspnetcore}\" "); if (String.IsNullOrEmpty(runtime)) { args.Append($"--runtimeVersion \"{aspnetcore}\" "); } else if (runtime == "Custom") { args.Append($"--runtimeVersion \"{customRuntime}\" "); } else { args.Append($"--runtimeVersion \"{runtime}\" "); } } if (collect) { args.Append($"--collect-trace "); } if (eventpipe) { args.Append($"--enable-eventpipe"); } if (fetch) { args.Append($"--fetch "); } if (selfContained) { args.Append($"--self-contained "); } return args.ToString(); } async Task UploadOutputFile() { var fileNameParts = await JSRuntime.InvokeAsync<string>("getFileData", outputFile); var fileNameSegments = fileNameParts.Split(';'); _outputFiles.Add(fileNameSegments[0], fileNameSegments[1]); selfContained = true; } Task DeleteOutputFile(string key) { _outputFiles.Remove(key); StateHasChanged(); return Task.CompletedTask; } async Task UploadNugetPackage() { var fileNameParts = await JSRuntime.InvokeAsync<string>("getFileData", nugetPackage); var fileNameSegments = fileNameParts.Split(';'); _nugetPackages.Add(fileNameSegments[0], fileNameSegments[1]); selfContained = true; } Task DeleteNugetPackage(string key) { _nugetPackages.Remove(key); StateHasChanged(); return Task.CompletedTask; } void OnSaveCheckboxChanged(UIChangeEventArgs e) { save = (bool)e.Value; // TODO: Show/Hide saveInput //return Task.CompletedTask; } async Task OnCompareCheckboxChanged(UIChangeEventArgs e) { savedJobs = await GetSavedJobs(); compare = (bool)e.Value; StateHasChanged(); } async Task<Dictionary<string, string>> GetSavedJobs() { return await LocalStorage.GetItem<Dictionary<string, string>>("SavedJobs") ?? new Dictionary<string, string>(); } async Task<Dictionary<string, Command>> GetSavedCommands() { var serialized = await LocalStorage.GetItem<string>("SavedCommands"); if (String.IsNullOrEmpty(serialized)) { return new Dictionary<string, Command>(); } return JsonConvert.DeserializeObject<Dictionary<string, Command>>(serialized) ; } Task<Command> SerializeCommand() { var command = new Command(); command.CurrentServer = currentServer; command.Scenario = scenario; command.Warmup = warmup; command.Duration = duration; command.Samples = samples; command.Extremes = extremes; command.Database = database; command.Host = host; command.Quiet = quiet; command.Markdown = markdown; command.AspNetCore = aspnetcore; command.Runtime = runtime; command.OutputFiles = new Dictionary<string, string>(_outputFiles); command.NugetPackages = new Dictionary<string, string>(_nugetPackages); // We should be able to save files too, as they are in a temp folder of the server // But it needs to be a folder outside of the Docker image return Task.FromResult(command); } Task LoadCommand(string key) { if (!savedCommands.TryGetValue(key, out var command)) { return Task.CompletedTask; } return LoadCommand(command); } Task LoadCommand(Command command) { currentServer = command.CurrentServer; scenario = command.Scenario; warmup = command.Warmup; duration = command.Duration; samples = command.Samples; extremes = command.Extremes; database = command.Database; host = command.Host; quiet = command.Quiet; markdown = command.Markdown; aspnetcore = command.AspNetCore; runtime = command.Runtime; _outputFiles = new Dictionary<string, string>(command.OutputFiles); _nugetPackages = new Dictionary<string, string>(command.NugetPackages); StateHasChanged(); return Task.CompletedTask; } Task DeleteCommand(string key) { savedCommands.Remove(key); StateHasChanged(); return SaveCommands(); } async Task SaveCommand() { if (String.IsNullOrWhiteSpace(commandName)) { return; } var command = await SerializeCommand(); savedCommands[commandName] = command; StateHasChanged(); await SaveCommands(); } Task SaveCommands() { return LocalStorage.SetItem("SavedCommands", JsonConvert.SerializeObject(savedCommands)); } }
the_stack
@* Generator: Template GeneratePrettyNames: true *@ @using System @using System.Collections.Generic @using System.Linq @using System.Security.Cryptography @using System.Text @using Humanizer @using Newtonsoft.Json @using Newtonsoft.Json.Linq @using RazorGenerator.Templating @using Templates.CodeGen @using Templates.CodeGen.Util @using Templates.Metadata @using Z.ExtensionMethods @inherits BaseTemplate @functions { public string ClassName { get; set; } public string Superclass { get; set; } public string TermName { get; set; } public JObject TermMeta { get; set; } public Dictionary<string, JObject> AllTerms { get; set; } public override RazorTemplateBase UseParentLayout(RazorTemplateBase child) { return new AstSubclassTemplate() { ClassName = this.ClassName, Superclass = this.Superclass, TermName = this.TermName, TermMeta = this.TermMeta, AllTerms = this.AllTerms, ChildTemplate = child }; } private string[] RenderSigArgs(Signature.SigArg[] sigArgs) { return sigArgs.Select(arg => $"{ArgumentType(arg.Type)} {ArgumentVariable(arg.Var)}").ToArray(); } protected static Dictionary<string, string[]> EnumerableHelpers = new Dictionary<string, string[]>() { { "GetAll", new[] {"ICollection<string>", "ICollection<Guid>"} }, { "HasFields", new[] {"ICollection<string>"} } , { "WithFields", new[] {"ICollection<string>"} } , { "Pluck", new[] {"ICollection<string>"} } , { "Without", new[] {"ICollection<string>"} } , { "IndexStatus", new[] {"ICollection<string>"} } , { "IndexWait", new[] {"ICollection<string>"} } }; } @helper RenderCtorXmlDoc(string term) { Documentation doc; if( MetaDb.Docs.TryGetValue(term, out doc) ) { @:/// <summary> @:/// @doc.Description @:/// </summary> @:/// <example>@doc.Example</example> }; } @section Ctors{ @if( this.TermName != null ) { @RenderCtorXmlDoc(this.TermName) @:public @Class(ClassName) (object arg) : this(new Arguments(arg), null) { @:} @RenderCtorXmlDoc(this.TermName) @:public @Class(ClassName) (Arguments args) : this(args, null) { @:} @RenderCtorXmlDoc(this.TermName) @:public @Class(ClassName) (Arguments args, OptArgs optargs) @: : base(TermType.@TermName, args, optargs) { @:} } else { @:protected @Class(ClassName) (TermType termType, Arguments args, OptArgs optargs) : base(termType, args, optargs) @:{ @:} } } @section StaticFactories{ } @section OptArgs{ @if( TermMeta?["optargs"] != null ) { var optArgs = TermMeta["optargs"] as JObject; @:///<summary> @:/// @optArgs.ToString().Trim('{', '}').Trim().Replace("\n","\n///") @:///</summary> @:public @Class(ClassName) this[object optArgs] { @: get @: { @: var newOptArgs = OptArgs.FromMap(this.OptArgs).With(optArgs); @: @: return new @Class(ClassName) (this.Args, newOptArgs); @: } @:} @: @:///<summary> @:/// @optArgs.ToString().Trim('{', '}').Trim().Replace("\n", "\n///") @:///</summary> @:public @Class(ClassName) this[OptArgs optArgs] { @: get @: { @: var newOptArgs = OptArgs.FromMap(this.OptArgs).With(optArgs); @: @: return new @Class(ClassName) (this.Args, newOptArgs); @: } @:} @: @:///<summary> @:/// @optArgs.ToString().Trim('{', '}').Trim().Replace("\n","\n///") @:///</summary> @:public @Class(ClassName) OptArg(string key, object val){ @: @: var newOptArgs = OptArgs.FromMap(this.OptArgs).With(key, val); @: @: return new @Class(ClassName) (this.Args, newOptArgs); @:} @:internal @Class(ClassName) optArg(string key, object val){ @: @: return this.OptArg(key, val); @:} } } @section ReqlExprHelpers{ @* C# Method Overload Resolution requires us to define these at the class level to avoid conflicting operator resolution between this[object anonTypeOptArg) and this[string bracket]. For example, if A.Foo(string) and B.Foo(object) exists, and B derives from A, then B.Foo("my string") resolves to B.Foo(object) NOT A.Foo(string). A.Foo(string) seems like the more logical choice, but not to the compiler. So, we need to re-define these [string] indexers here along side the OptArgs indexers so the compiler resolving Term[] doesn't get it twisted. Originally I had this in partial ReqlExpr, but operator resolution didn't work for ReQL terms that had this[object] optArg indexers. *@ @if (Superclass == "ReqlExpr") { @:/// <summary> @:/// Get a single field from an object. If called on a sequence, gets that field from every object in the sequence, skipping objects that lack it. @:/// </summary> @:/// <param name="bracket"></param> @* DO NOT USE OVERRIDE KEYWORD, USE NEW *@ @:public new Bracket this[string bracket] => base[bracket]; @: @:/// <summary> @:/// Get the nth element of a sequence, counting from zero. If the argument is negative, count from the last element. @:/// </summary> @:/// <param name="bracket"></param> @:/// <returns></returns> @* DO NOT USE OVERRIDE KEYWORD, USE NEW *@ @:public new Bracket this[int bracket] => base[bracket]; } } //AUTOGENERATED, DO NOTMODIFY. //Do not edit this file directly. #pragma warning disable 1591 // Missing XML comment for publicly visible type or member // ReSharper disable CheckNamespace using System; using RethinkDb.Driver.Ast; using RethinkDb.Driver.Model; using RethinkDb.Driver.Proto; using System.Collections; using System.Collections.Generic; @RenderSection("add_imports") namespace RethinkDb.Driver.Ast { public partial class @Class(ClassName) : @Superclass { @RenderSection("MemberVars") @RenderSection("Ctors") @RenderSection("StaticFactories") @RenderSection("OptArgs") @RenderSection("ReqlExprHelpers") @RenderBody() @RenderSection("SpecialMethods") @foreach( var termInfo in AllTerms ) { var term = termInfo.Key; var info = termInfo.Value; if( info["include_in"].ToObject<string[]>().Any(inc => string.Equals(inc, ClassName, StringComparison.OrdinalIgnoreCase)) ) { // is the current term included in this class we're generating? foreach( var rawMethodName in info["methodnames"].ToObject<string[]>() ) { foreach( var signature in info["signatures"].ToObject<Signature[]>() ) { if( signature.FirstArg == ClassName ) { Signature.SigArg[] remainingArgs; if( signature.Args[0].IsParams() ) // for r.term(params object[] foo) { remainingArgs = signature.Args; } else { remainingArgs = signature.Args.Skip(1).ToArray(); } var className = Class(info["classname"].ToString()); var methodName = Method(rawMethodName); var internalMethodName = MethodInternalName(rawMethodName); @RenderCtorXmlDoc(term) @:public @className @methodName ( @string.Join(", ", RenderSigArgs(remainingArgs) ) ) @:{ @: Arguments arguments = new Arguments(this); foreach( var param in remainingArgs ) { if( param.IsParams() ) { @:arguments.CoerceAndAddAll(@ArgumentVariable(param.Var)); } else { @:arguments.CoerceAndAdd(@ArgumentVariable(param.Var)); } } @: return new @className (arguments ); @:} //Create a IList helper overload for "params object[] args" string[] helperSigs; if (signature.OnlyHasParams() && EnumerableHelpers.TryGetValue(methodName, out helperSigs)) { foreach (var helperSig in helperSigs) { @RenderCtorXmlDoc(term) @:/// <param name="args">Same as calling params object[] overload, except the collection is applied as object[] params.</param> @:public @className @methodName ( @helperSig args ) @:{ @:var arguments = new Arguments(this); @:arguments.CoerceAndAddAll(args); @:return new @className (arguments); @:} } } //Internal API for Unit Tests @:internal @className @internalMethodName ( @string.Join(", ", RenderSigArgs(remainingArgs) ) ) @:{ @: return @methodName ( @string.Join(", ", remainingArgs.Select(arg => $"{ArgumentVariable(arg.Var)}").ToArray()) ); @:} } } } } } } }
the_stack
#r "nuget:Newtonsoft.Json,10.0.3" #load "CauldronBuilderData.csx" #load "NugetMetaDataJson.csx" #load "NuspecInfo.csx" using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Runtime.CompilerServices; private const string Authors = "Alexander Schunk, Capgemini Deutschland GmbH"; private const string Copyright = "Copyright (c) 2016 Capgemini Deutschland GmbH"; private static CauldronBuilderData data; var startingLocation = new DirectoryInfo(Args == null || Args.Count() == 0 ? Path.GetDirectoryName(GetCurrentFileName()) : Args[0]); data = CauldronBuilderData.GetConfig(startingLocation); var version = data.IsBeta ? data.CurrentPackageVersion + "-beta" : data.CurrentPackageVersion; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Version {version} / {data.CurrentAssemblyVersion}"); Console.WriteLine($"Path {startingLocation.FullName}"); Console.ResetColor(); try { var packages = new DirectoryInfo(Path.Combine(startingLocation.FullName, "Nuget\\Packages")); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Do you want to build the projects? Y/N"); if (Console.ReadKey().Key == ConsoleKey.Y) { Console.WriteLine(""); var fodyProjects = Directory.GetFiles(Path.Combine(startingLocation.FullName, "Fody"), "*.csproj", SearchOption.AllDirectories).Select(x => new FileInfo(x)).ToArray(); var netStandardProjects = Directory.GetFiles(Path.Combine(startingLocation.FullName, "NetStandard"), "*.csproj", SearchOption.AllDirectories).Select(x => new FileInfo(x)).ToArray(); var uwpProjects = Directory.GetFiles(Path.Combine(startingLocation.FullName, "UWP"), "*.csproj", SearchOption.AllDirectories).Select(x => new FileInfo(x)).ToArray(); var win32Projects = Directory.GetFiles(Path.Combine(startingLocation.FullName, "Win32"), "*.csproj", SearchOption.AllDirectories).Select(x => new FileInfo(x)).ToArray(); var solutionPath = new FileInfo(Path.Combine(startingLocation.FullName, "Cauldron.sln")); foreach (var project in fodyProjects.Concat(netStandardProjects).Concat(uwpProjects).Concat(win32Projects)) { ModifyAssemblyInfo(project); ChangeVersion(project, version); } // Build the Fody stuff first Console.WriteLine("Compiling Fody Add-in"); for (int i = 0; i < fodyProjects.Length; i++) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Compiling [{i + 1}/{fodyProjects.Length}] " + fodyProjects[i].Name); BuildProject(solutionPath, fodyProjects[i], "Release"); } Console.WriteLine("Compiling NetStandard and UWP projects"); Parallel.ForEach(new List<FileInfo[]> { netStandardProjects, uwpProjects }, projects => { for (int i = 0; i < projects.Length; i++) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Compiling [{i + 1}/{projects.Length}] " + projects[i].Name); BuildProject(solutionPath, projects[i], "Release"); } }); // We have to build the win32 projects for all NET Framework targets Parallel.ForEach(new string[] { "-Net45", "-Net451", "-Net452", "-Net46", "-Net461", "-Net462", "" }, target => { Console.WriteLine("Compiling Net Classic projects - " + target); for (int i = 0; i < win32Projects.Length; i++) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Compiling [{i + 1}/{win32Projects.Length}] {target} {win32Projects[i].Name}"); BuildProject(solutionPath, win32Projects[i], "Release" + target); } }); // Clean the package directory foreach (var file in Directory.GetFiles(packages.FullName, "*.nupkg")) File.Delete(file); // Move all packages to the Package directory foreach (var nuget in Directory.GetFiles(startingLocation.FullName, "*.nupkg", SearchOption.AllDirectories) .Where(x => x.Contains("\\Release\\"))) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Moving " + Path.GetFileName(nuget)); File.Move(nuget, Path.Combine(startingLocation.FullName, "Nuget\\Packages", Path.GetFileName(nuget))); } data.IncrementAndSave(); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Do you want to build the Nuget packages? Y/N"); if (Console.ReadKey().Key == ConsoleKey.Y) { // Build nugets of non NetStandard2.0 projects Parallel.ForEach(Directory.GetFiles(Path.Combine(startingLocation.FullName, "Nuget"), "*.nuspec").Select(x => new FileInfo(x)), nuget => { try { Console.WriteLine($"{nuget.FullName}"); ModifyNuspec(nuget, version); BuildNuGetPackage(nuget.FullName, packages.FullName, version); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{nuget.FullName} " + e.Message); Console.ResetColor(); throw; } }); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Do you want to upload the packages? Y/N"); if (Console.ReadKey().Key == ConsoleKey.Y) { Console.WriteLine(""); foreach (var package in Directory.GetFiles(packages.FullName, "*.nupkg", SearchOption.TopDirectoryOnly) .Where(x => x.IndexOf(".symbols.", StringComparison.InvariantCultureIgnoreCase) < 0)) UploadNugetPackage(package); } CreateReadmeFromNuspec(startingLocation, version); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Do you want to rebuild the documentations? Y/N"); if (Console.ReadKey().Key == ConsoleKey.Y) foreach (var project in Directory.GetFiles(startingLocation.FullName, "*.shfbproj", SearchOption.AllDirectories)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Compiling {Path.GetFileName(project)}"); BuildProject(new FileInfo(Path.Combine(startingLocation.FullName, "Cauldron.sln")), new FileInfo(project), "Release"); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(GetStackTrace(e)); Console.WriteLine("\r\n\r\nCancelled"); Console.Read(); } finally { Console.ResetColor(); } private static string GetCurrentFileName([CallerFilePath] string fileName = null) => fileName; private static void BuildNuGetPackage(string path, string targetDirectory, string version) { var filename = new FileInfo(Path.Combine(Path.GetDirectoryName(GetCurrentFileName()), "..\\Nuget\\nuget.exe")); var startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; startInfo.WorkingDirectory = Path.GetDirectoryName(path); startInfo.FileName = filename.FullName; startInfo.Arguments = string.Format("pack \"{0}\" -Symbols -OutputDir Packages -version {2}", path, targetDirectory, version); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Compiling " + startInfo.Arguments); var process = Process.Start(startInfo); var error = process.StandardError.ReadToEnd(); var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(10000); Console.WriteLine(output); if (process.ExitCode != 0) throw new Exception(error); } private static void BuildProject(FileInfo solutionPath, FileInfo path, string configuration) { var filename = new FileInfo(@"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe"); var startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; startInfo.WorkingDirectory = solutionPath.DirectoryName; startInfo.FileName = filename.FullName; startInfo.Arguments = string.Format("\"{0}\" /target:Clean;Rebuild /p:Configuration=" + configuration, path.FullName); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; var process = Process.Start(startInfo); var error = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) throw new Exception(error); } private static void ChangeVersion(FileInfo path, string version) { var projectFileBody = File.ReadAllText(path.FullName); if (projectFileBody.StartsWith(@"<Project Sdk=""Microsoft.NET.Sdk"">")) // This is a NetStandard project { var packageVersion = projectFileBody.EnclosedIn("<Version>", "</Version>"); if (packageVersion != null) projectFileBody = projectFileBody.Replace(packageVersion, $"<Version>{version}</Version>"); var assemblyVersion = projectFileBody.EnclosedIn("<AssemblyVersion>", "</AssemblyVersion>"); if (assemblyVersion != null) projectFileBody = projectFileBody.Replace(assemblyVersion, $"<AssemblyVersion>{data.CurrentAssemblyVersion}</AssemblyVersion>"); else Insert(ref projectFileBody, $"<AssemblyVersion>{data.CurrentAssemblyVersion}</AssemblyVersion>\r\n"); var fileVersion = projectFileBody.EnclosedIn("<FileVersion>", "</FileVersion>"); if (fileVersion != null) projectFileBody = projectFileBody.Replace(fileVersion, $"<FileVersion>{data.CurrentAssemblyVersion}</FileVersion>"); else Insert(ref projectFileBody, $"<FileVersion>{data.CurrentAssemblyVersion}</FileVersion>\r\n"); File.WriteAllText(path.FullName, projectFileBody); } else { // Lets look for AssemblyInfo.cs var assemblyInfo = Path.Combine(path.Directory.FullName, "Properties\\AssemblyInfo.cs"); if (!File.Exists(assemblyInfo)) return; var assemblyInfoBody = File.ReadAllText(assemblyInfo); var assemblyVersion = assemblyInfoBody.EnclosedIn("[assembly: AssemblyVersion(\"", "\")]"); if (assemblyVersion != null) assemblyInfoBody = assemblyInfoBody.Replace(assemblyVersion, $"[assembly: AssemblyVersion(\"{data.CurrentAssemblyVersion}\")]"); var fileVersion = assemblyInfoBody.EnclosedIn("[assembly: AssemblyFileVersion(\"", "\")]"); if (fileVersion != null) assemblyInfoBody = assemblyInfoBody.Replace(fileVersion, $"[assembly: AssemblyFileVersion(\"{data.CurrentAssemblyVersion}\")]"); File.WriteAllText(assemblyInfo, assemblyInfoBody); } } private static bool Contains(this XmlElement element, string key) { try { var result = element[key]; return result != null; } catch { return false; } } private static void CreateReadmeFromNuspec(DirectoryInfo startingLocation, string currentVersion) { var nugetbag = new ConcurrentBag<string>(); var historybag = new ConcurrentBag<NuspecInfo>(); Parallel.ForEach(Directory.GetFiles(Path.Combine(startingLocation.FullName, "Nuget"), "*.nuspec").Select(x => new FileInfo(x)), nuget => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Getting Information for " + nuget); var nuspec = new XmlDocument(); nuspec.Load(nuget.FullName); var name = nuspec["package"]["metadata"]["id"].InnerText; var description = nuspec["package"]["metadata"]["description"].InnerText?.Replace("\r\n", "<br/>"); var nugetLink = nuspec["package"]["metadata"]["id"].InnerText; if (name.StartsWith("Capgemini.")) name = name.Substring("Capgemini.".Length); if (description.StartsWith("<br/>")) description = description.Substring("<br/>".Length).Trim(); nugetLink = $"[![NuGet](https://img.shields.io/nuget/v/{nugetLink}.svg)](https://www.nuget.org/packages/{nugetLink}/)"; nugetbag.Add($"**{name}** | {description} | {nugetLink}"); var nugetInfos = GetNugetInfo(Path.GetFileNameWithoutExtension(nuget.Name)).Result; var nugetInfo = nugetInfos?.Items .SelectMany(x => x.Items) .Select(x => x.CatalogEntry) .Concat(new CatalogEntry[] { new CatalogEntry { Version = currentVersion, Published = DateTime.Now } }) .OrderBy(x => x.Published) .ToArray(); if (nugetInfo == null) return; var versionInfo = nuspec["package"]["metadata"]["releaseNotes"]?.InnerText?.Split("\r\n") .Select(x => { if (string.IsNullOrEmpty(x)) return null; var cleanLine = x.Trim(); if (string.IsNullOrEmpty(cleanLine)) return null; var itemDate = DateTime.TryParse(cleanLine.Substring(0, 10), out DateTime date) ? date : (DateTime?)null; var metaData = nugetInfo.FirstOrDefault(y => y.Published >= itemDate); return new NuspecInfo { Date = itemDate ?? DateTime.Now, Type = cleanLine.EnclosedIn("[", "]"), Description = $"__{Path.GetFileNameWithoutExtension(nuget.Name)}:__ _{cleanLine.Substring(cleanLine.IndexOf(']') + 1)?.Trim() ?? ""}_", Version = new Version(metaData.Version.Split('-')[0]), IsBeta = metaData.Version.IndexOf("beta") > 0 }; }); if (versionInfo == null) return; foreach (var item in versionInfo) historybag.Add(item); }); var versionHistory = historybag .Where(x => x != null) .GroupBy(x => x.Version) .Select(x => new { Version = x.Key, IsBeta = x.Any(y => y.IsBeta), Types = x.GroupBy(y => y.Type).Select(y => new { Type = y.Key, Log = y.ToArray() }) }) .OrderByDescending(x => x.Version) .ThenBy(x => x.Types) .ToArray(); var historyNugetInfo = new List<string>(); foreach (var version in versionHistory) { if (version.IsBeta) historyNugetInfo.Add($"### __{version.Version} BETA__"); else historyNugetInfo.Add($"### __{version.Version}__"); foreach (var type in version.Types) { switch (type.Type) { case "[A]": historyNugetInfo.Add("#### Added"); break; case "[B]": historyNugetInfo.Add("#### Bugfix"); break; case "[C]": historyNugetInfo.Add("#### Change"); break; } foreach (var text in type.Log) historyNugetInfo.Add($"- {text.Description}"); } } var template = File.ReadAllText(Path.Combine(startingLocation.FullName, "Nuget", "Readme-template-.md")); var nugetPackages = string.Join("\r\n", nugetbag.OrderBy(x => x)); File.WriteAllText(Path.Combine(startingLocation.FullName, "README.md"), template .Replace("<NUGET_PACKAGES>", nugetPackages) .Replace("<RELEASE_NOTES>", string.Join("\r\n", historyNugetInfo))); } private static string EnclosedIn(this string target, string start, string end) { if (string.IsNullOrEmpty(target)) return null; int startPos = target.IndexOf(start); if (startPos < 0) return null; int endPos = target.IndexOf(end, startPos + 1); if (endPos <= startPos) return null; return target.Substring(startPos, endPos - startPos + end.Length); } private static async Task<CatalogRoot> GetNugetInfo(string packageName) { using (var client = new HttpClient()) { var response = await client.GetAsync($"https://api.nuget.org/v3/registration3/{packageName.ToLower()}/index.json"); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<CatalogRoot>(data); } } return null; } private static string GetStackTrace(Exception e) { var sb = new StringBuilder(); var ex = e; do { sb.AppendLine("Exception Type: " + ex.GetType().Name); sb.AppendLine("Source: " + ex.Source); sb.AppendLine(ex.Message); sb.AppendLine("------------------------"); sb.AppendLine(ex.StackTrace); sb.AppendLine("------------------------"); ex = ex.InnerException; } while (ex != null); return sb.ToString(); } private static void Insert(ref string body, string data) { int position = body.IndexOf("</PropertyGroup>"); if (position < 0) return; body = body.Insert(position, data); } private static void ModifyAssemblyInfo(FileInfo path) { var projectFileBody = File.ReadAllText(path.FullName); if (projectFileBody.StartsWith(@"<Project Sdk=""Microsoft.NET.Sdk"">")) // This is a NetStandard project { var authors = projectFileBody.EnclosedIn("<Authors>", "</Authors>"); if (authors != null) projectFileBody = projectFileBody.Replace(authors, $"<Authors>{Authors}</Authors>"); else Insert(ref projectFileBody, $"<Authors>{Authors}</Authors>\r\n"); var copyright = projectFileBody.EnclosedIn("<Copyright>", "</Copyright>"); if (copyright != null) projectFileBody = projectFileBody.Replace(copyright, $"<Copyright>{Copyright}</Copyright>"); else Insert(ref projectFileBody, $"<Copyright>{Copyright}</Copyright>\r\n"); File.WriteAllText(path.FullName, projectFileBody); } else { // Lets look for AssemblyInfo.cs var assemblyInfo = Path.Combine(path.Directory.FullName, "Properties\\AssemblyInfo.cs"); if (!File.Exists(assemblyInfo)) return; var assemblyInfoBody = File.ReadAllText(assemblyInfo); var authors = assemblyInfoBody.EnclosedIn("[assembly: AssemblyCompany(\"", "\")]"); if (authors != null) assemblyInfoBody = assemblyInfoBody.Replace(authors, $"[assembly: AssemblyCompany(\"{Authors}\")]"); var copyright = assemblyInfoBody.EnclosedIn("[assembly: AssemblyCopyright(\"", "\")]"); if (copyright != null) assemblyInfoBody = assemblyInfoBody.Replace(copyright, $"[assembly: AssemblyCopyright(\"{Copyright}\")]"); File.WriteAllText(assemblyInfo, assemblyInfoBody); } } private static void ModifyNuspec(FileInfo path, string version) { var nuspec = new XmlDocument(); nuspec.Load(path.FullName); var dependencies = nuspec["package"]["metadata"]["dependencies"]; foreach (XmlElement item in dependencies.Contains("group") ? dependencies["group"] : dependencies) { if (item.Attributes["id"].Value.Contains("Cauldron")) item.Attributes["version"].Value = version; } nuspec["package"]["metadata"]["owners"].InnerText = Authors; nuspec["package"]["metadata"]["authors"].InnerText = Authors; nuspec["package"]["metadata"]["requireLicenseAcceptance"].InnerText = "true"; nuspec["package"]["metadata"]["licenseUrl"].InnerText = "https://raw.githubusercontent.com/Capgemini/Cauldron/master/LICENSE"; nuspec["package"]["metadata"]["projectUrl"].InnerText = "https://github.com/Capgemini/Cauldron"; nuspec["package"]["metadata"]["iconUrl"].InnerText = "https://raw.githubusercontent.com/Capgemini/Cauldron/master/cauldron.png"; nuspec["package"]["metadata"]["copyright"].InnerText = Copyright; nuspec["package"]["metadata"]["id"].InnerText = Path.GetFileNameWithoutExtension(path.FullName); nuspec.Save(path.FullName); } private static void UploadNugetPackage(string path) { var filename = new FileInfo(Path.Combine(Path.GetDirectoryName(GetCurrentFileName()), "..\\Nuget\\nuget.exe")); var startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; startInfo.WorkingDirectory = Path.GetDirectoryName(path); startInfo.FileName = filename.FullName; startInfo.Arguments = string.Format("push \"{0}\" -Source https://www.nuget.org/api/v2/package", path); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Uploading " + startInfo.Arguments); Console.ResetColor(); var process = Process.Start(startInfo); var output = process.StandardOutput.ReadToEnd(); var error = process.StandardError.ReadToEnd(); process.WaitForExit(); Console.WriteLine(output); if (process.ExitCode != 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(error); Console.ResetColor(); } }
the_stack
<!-- MAIN CONTENT --> <div id="content"> <!-- Bread crumb is created dynamically --> <!-- row --> <div class="row"> <!-- col --> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <!-- PAGE HEADER --> <i class="fa-fw fa fa-bar-chart-o"></i> Graphs <span> > Chart.js </span> </h1> </div> <!-- end col --> <!-- right side of the page with the sparkline graphs --> <!-- col --> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> <!-- sparks --> <ul id="sparks"> <li class="sparks-info"> <h5> My Income <span class="txt-color-blue">$47,171</span></h5> <div class="sparkline txt-color-blue hidden-mobile hidden-md hidden-sm"> 1300, 1877, 2500, 2577, 2000, 2100, 3000, 2700, 3631, 2471, 2700, 3631, 2471 </div> </li> <li class="sparks-info"> <h5> Site Traffic <span class="txt-color-purple"><i class="fa fa-arrow-circle-up" data-rel="bootstrap-tooltip" title="Increased"></i>&nbsp;45%</span></h5> <div class="sparkline txt-color-purple hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> <li class="sparks-info"> <h5> Site Orders <span class="txt-color-greenDark"><i class="fa fa-shopping-cart"></i>&nbsp;2447</span></h5> <div class="sparkline txt-color-greenDark hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> </ul> <!-- end sparks --> </div> <!-- end col --> </div> <!-- end row --> <!-- The ID "widget-grid" will start to initialize all widgets below You do not need to use widgets if you dont want to. Simply remove the <section></section> and you can use wells or panels instead --> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-0" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Line Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="lineChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-1" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Radar Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="radarChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-3" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Polar Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="polarChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-2" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Bar Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="barChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-4" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Doughnut Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="doughnutChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-6" data-widget-colorbutton="false" data-widget-fullscreenbutton="false" data-widget-editbutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <h2>Pie Chart </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> <input class="form-control" type="text"> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <!-- this is what the user will see --> <canvas id="pieChart" height="120"></canvas> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> <!-- row --> <div class="row"> <!-- a blank row to get started --> <div class="col-sm-12"> <!-- your contents here --> </div> </div> <!-- end row --> </section> <!-- end widget grid --> </div> <!-- END MAIN CONTENT --> @section pagespecific { <script type="text/javascript"> /* DO NOT REMOVE : GLOBAL FUNCTIONS! * * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS * * // activate tooltips * $("[rel=tooltip]").tooltip(); * * // activate popovers * $("[rel=popover]").popover(); * * // activate popovers with hover states * $("[rel=popover-hover]").popover({ trigger: "hover" }); * * // activate inline charts * runAllCharts(); * * // setup widgets * setup_widgets_desktop(); * * // run form elements * runAllForms(); * ******************************** * * pageSetUp() is needed whenever you load a page. * It initializes and checks for all basic elements of the page * and makes rendering easier. * */ pageSetUp(); /* * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE * eg alert("my home function"); * * var pagefunction = function() { * ... * } * loadScript("/js/plugin/_PLUGIN_NAME_.js", pagefunction); * * TO LOAD A SCRIPT: * var pagefunction = function (){ * loadScript(".../plugin.js", run_after_loaded); * } * * OR you can load chain scripts by doing * * loadScript(".../plugin.js", function(){ * loadScript("../plugin.js", function(){ * ... * }) * }); */ var LineConfig, barChartData, RadarConfig, DoughtnutConfig, PolarConfig, PieConfig; // pagefunction var pagefunction = function () { // clears the variable if left blank // reference: http://www.chartjs.org/docs/ var randomScalingFactor = function () { return Math.round(Math.random() * 100); //return 0; }; var randomColorFactor = function () { return Math.round(Math.random() * 255); }; var randomColor = function (opacity) { return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; }; LineConfig = { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ], }, { label: "My Second dataset", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ], } ] }, options: { responsive: true, tooltips: { mode: 'label' }, hover: { mode: 'dataset' }, scales: { xAxes: [ { display: true, scaleLabel: { show: true, labelString: 'Month' } } ], yAxes: [ { display: true, scaleLabel: { show: true, labelString: 'Value' }, ticks: { suggestedMin: 0, suggestedMax: 100, } } ] } } }; $.each(LineConfig.data.datasets, function (i, dataset) { dataset.borderColor = 'rgba(0,0,0,0.15)'; dataset.backgroundColor = randomColor(0.5); dataset.pointBorderColor = 'rgba(0,0,0,0.15)'; dataset.pointBackgroundColor = randomColor(0.5); dataset.pointBorderWidth = 1; }); // bar chart example barChartData = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: 'Dataset 1', backgroundColor: "rgba(220,220,220,0.5)", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ] }, { label: 'Dataset 2', backgroundColor: "rgba(151,187,205,0.5)", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ] }, { label: 'Dataset 3', backgroundColor: "rgba(151,187,205,0.5)", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ] } ] }; // radar example RadarConfig = { type: 'radar', data: { labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], datasets: [ { label: "My First dataset", backgroundColor: "rgba(220,220,220,0.2)", pointBackgroundColor: "rgba(220,220,220,1)", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ] }, { label: "My Second dataset", backgroundColor: "rgba(151,187,205,0.2)", pointBackgroundColor: "rgba(151,187,205,1)", hoverPointBackgroundColor: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor() ] }, ] }, options: { legend: { position: 'top', }, scale: { reverse: false, ticks: { beginAtZero: true } } } }; // doughnut example DoughtnutConfig = { type: 'doughnut', data: { datasets: [ { data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], label: 'Dataset 1' } ], labels: [ "Red", "Green", "Yellow", "Grey", "Dark Grey" ] }, options: { responsive: true, legend: { position: 'top', } } }; // polar chart example PolarConfig = { data: { datasets: [ { data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], label: 'My dataset' // for legend } ], labels: [ "Red", "Green", "Yellow", "Grey", "Dark Grey" ] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Our Favorite Dataset' }, scale: { ticks: { beginAtZero: true }, reverse: false }, animateRotate: false } }; // pie chart example PieConfig = { type: 'pie', data: { datasets: [ { data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], } ], labels: [ "Red", "Green", "Yellow", "Grey", "Dark Grey" ] }, options: { responsive: true } }; myLine = new Chart(document.getElementById("lineChart"), LineConfig); myBar = new Chart(document.getElementById("barChart"), { type: 'bar', data: barChartData, options: { responsive: true, } }); myRadar = new Chart(document.getElementById("radarChart"), RadarConfig); myDoughnut = new Chart(document.getElementById("doughnutChart"), DoughtnutConfig); myPolarArea = Chart.PolarArea(document.getElementById("polarChart"), PolarConfig); myPie = new Chart(document.getElementById("pieChart"), PieConfig); }; // end pagefunction // destroy generated instances // pagedestroy is called automatically before loading a new page // only usable in AJAX version! var pagedestroy = function () { //destroy all charts myLine.destroy(); LineConfig = null; myBar.destroy(); barChartData = null; myRadar.destroy(); RadarConfig = null; myDoughnut.destroy(); DoughtnutConfig = null; myPolarArea.destroy(); PolarConfig = null; myPie.destroy(); PieConfig = null; if (debugState) { root.console.log("✔ Chart.js charts destroyed"); } }; // end destroy pagefunction(); </script> }
the_stack
 <!-- MAIN CONTENT --> <div id="content"> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-desktop fa-fw "></i> UI Elements <span> > JQuery UI </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> <ul id="sparks" class=""> <li class="sparks-info"> <h5> My Income <span class="txt-color-blue">$47,171</span></h5> <div class="sparkline txt-color-blue hidden-mobile hidden-md hidden-sm"> 1300, 1877, 2500, 2577, 2000, 2100, 3000, 2700, 3631, 2471, 2700, 3631, 2471 </div> </li> <li class="sparks-info"> <h5> Site Traffic <span class="txt-color-purple"><i class="fa fa-arrow-circle-up" data-rel="bootstrap-tooltip" title="Increased"></i>&nbsp;45%</span></h5> <div class="sparkline txt-color-purple hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> <li class="sparks-info"> <h5> Site Orders <span class="txt-color-greenDark"><i class="fa fa-shopping-cart"></i>&nbsp;2447</span></h5> <div class="sparkline txt-color-greenDark hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> </ul> </div> </div> <!-- row --> <div class="row"> <div class="col-sm-6 col-md-6 col-lg-6"> <div class="well well-sm well-light"> <h3>Dialogue</h3> <a href="#" id="dialog_link" class="btn btn-info"> Open Dialog </a> &nbsp; <a href="#" id="modal_link" class="btn bg-color-purple txt-color-white"> Open Modal Dialog </a> </div> <div class="well well-sm well-light"> <h3> Jquery Tabs <br> <small>Simple Tabs</small> </h3> <div id="tabs"> <ul> <li> <a href="#tabs-a">First</a> </li> <li> <a href="#tabs-b">Second</a> </li> <li> <a href="#tabs-c">Third</a> </li> </ul> <div id="tabs-a"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> <div id="tabs-b"> <p> Phasellus mattis tincidunt nibh. Cras orci urna, blandit id, pretium vel, aliquet ornare, felis. Maecenas scelerisque sem non nisl. Fusce sed lorem in enim dictum bibendum. </p> </div> <div id="tabs-c"> <p> Nam dui erat, auctor a, dignissim quis, sollicitudin eu, felis. Pellentesque nisi urna, interdum eget, sagittis et, consequat vestibulum, lacus. Mauris porttitor ullamcorper augue. </p> </div> </div> <hr class="simple"> <h3> Dynamic Tabs <br> <small>Click button to add another tab</small> </h3> <p> <button id="add_tab" class="btn btn-primary"> Add Tab </button> </p> <div id="tabs2"> <ul> <li> <a href="#tabs-1">Nunc tincidunt</a> </li> </ul> <div id="tabs-1"> <p> Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus. </p> </div> </div> <!-- Demo --> <div id="addtab" title=" <div class='widget-header'><h4><i class='fa fa-plus'></i> Add another tab</h4></div>"> <form> <fieldset> <input name="authenticity_token" type="hidden"> <div class="form-group"> <label>Tab Title</label> <input class="form-control" id="tab_title" value="" placeholder="Text field" type="text"> </div> <div class="form-group"> <label>Content</label> <textarea class="form-control" name="tab_content" id="tab_content" placeholder="Tab Content" rows="3"></textarea> </div> </fieldset> </form> </div> </div> <div class="well well-sm well-light"> <h3> Slider <br> <small>Horizontal Slider with tooltip</small> </h3> <input type="text" class="slider slider-primary" id="g1" value="" data-slider-max="500" data-slider-value="185" data-slider-selection="before" data-slider-handle="round"> <input type="text" class="slider slider-success" id="g2" value="" data-slider-max="1000" data-slider-step="1" data-slider-value="[150,760]" data-slider-handle="squar"> <h3>Usage <small>Its so simple...</small> </h3> <pre> <code><strong>&lt;input class="slider slider-primary" data-slider-min="10" .. /></strong></code> data-slider-min="10" <span class="text-muted"> // slider min value</span> data-slider-max="500" <span class="text-muted"> // slider max value</span> data-slider-value="315" <span class="text-muted"> // handler position on slider</span> data-slider-handle="round" <span class="text-muted"> // round or square</span> </pre> </div> <div class="well well-sm well-light"> <h3>Spinner</h3> <div class="row"> <div class="col-sm-6 col-md-6 col-lg-6"> <div class="form-group"> <label>Spinner Right</label> <input class="form-control" id="spinner-decimal" name="spinner-decimal" value="7.99"> </div> </div> <div class="col-sm-6 col-md-6 col-lg-6"> <div class="form-group"> <label>Spinner Left</label> <input class="form-control spinner-left" id="spinner" name="spinner" value="1" type="text"> </div> </div> </div> </div> </div> <div class="col-sm-6 col-md-6 col-lg-6"> <div class="well well-sm well-light"> <h3>Menu <br> <small>Easy Menu List</small></h3> <ul id="menu"> <li> <a href="javascript:void(0);" class="ui-state-disabled">Aberdeen (disabled)</a> </li> <li> <a href="javascript:void(0);">Ada</a> </li> <li> <a href="javascript:void(0);">Adamsville</a> </li> <li> <a href="javascript:void(0);">Addyston</a> </li> <li> <a href="javascript:void(0);">Delphi</a> <ul> <li> <a href="javascript:void(0);">Ada</a> </li> <li> <a href="javascript:void(0);">Saarland</a> </li> <li> <a href="javascript:void(0);">Salzburg</a> </li> </ul> </li> <li> <a href="javascript:void(0);">Saarland</a> </li> <li> <a href="javascript:void(0);">Salzburg</a> <ul> <li> <a href="javascript:void(0);">Delphi</a> <ul> <li> <a href="javascript:void(0);" class="ui-state-disabled">Ada</a> </li> <li> <a href="javascript:void(0);">Saarland</a> </li> <li> <a href="javascript:void(0);">Salzburg</a> </li> </ul> </li> <li> <a href="?Delphi">Delphi</a> <ul> <li> <a href="javascript:void(0);">Ada</a> </li> <li> <a href="javascript:void(0);">Saarland</a> </li> <li> <a href="javascript:void(0);">Salzburg</a> </li> </ul> </li> <li> <a href="javascript:void(0);">Perch</a> </li> </ul> </li> </ul> </div> <div class="well well-sm well-light"> <h3> Auto Complete <br> <small>Type something to reveal autocompelete tags</small> </h3> <input class="form-control" placeholder="Type something..." type="text" data-autocomplete='[ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"]'> <p class="note"> Usage: data-autocomplete= ' ["this", "message", "bold", "text"] ' </p> <h3> Auto Complete Ajax <br> <small>Fetches data from JSON url</small> </h3> <input class="form-control" placeholder="City..." type="text" id="city"> <div id="log" class="font-xs margin-top-10 text-danger"></div> </div> <div class="well well-sm well-light"> <h3> Accordion <br> <small>With fontawesome icons</small> </h3> <div id="accordion"> <div> <h4>First</h4> <div class="padding-10"> Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus. </div> </div> <div> <h4>Second</h4> <div class="padding-10"> Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus. </div> </div> <div> <h4>Third</h4> <div class="padding-10"> Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus. </div> </div> </div> </div> <div class="well well-sm well-light"> <h3> Progress Bar <br> <small>Default progress bar.</small> </h3> <div id="progressbar"></div> </div> </div> </div> <!-- end row --> <!-- ui-dialog --> <div id="dialog_simple" title="Dialog Simple Title"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> <div id="dialog-message" title="Dialog Simple Title"> <p> This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon. </p> <div class="hr hr-12 hr-double"></div> Currently using <b>36% of your storage space</b> <div class="progress progress-striped active no-margin"> <div class="progress-bar progress-primary" role="progressbar" style="width: 36%"></div> </div> </div><!-- #dialog-message --> </div> <!-- END MAIN CONTENT --> @section pagespecific { <script type="text/javascript"> // DO NOT REMOVE : GLOBAL FUNCTIONS! $(document).ready(function () { // menu $("#menu").menu(); /* * AUTO COMPLETE AJAX */ function log(message) { $("<div>").text(message).prependTo("#log"); $("#log").scrollTop(0); } $("#city").autocomplete({ source: function (request, response) { $.ajax({ url: "http://ws.geonames.org/searchJSON", dataType: "jsonp", data: { featureClass: "P", style: "full", maxRows: 12, name_startsWith: request.term }, success: function (data) { response($.map(data.geonames, function (item) { return { label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, value: item.name } })); } }); }, minLength: 2, select: function (event, ui) { log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value); } }); /* * Spinners */ $("#spinner").spinner(); $("#spinner-decimal").spinner({ step: 0.01, numberFormat: "n" }); $("#spinner-currency").spinner({ min: 5, max: 2500, step: 25, start: 1000, numberFormat: "C" }); /* * CONVERT DIALOG TITLE TO HTML * REF: http://stackoverflow.com/questions/14488774/using-html-in-a-dialogs-title-in-jquery-ui-1-10 */ $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, { _title: function (title) { if (!this.options.title) { title.html("&#160;"); } else { title.html(this.options.title); } } })); /* * DIALOG SIMPLE */ // Dialog click $('#dialog_link').click(function () { $('#dialog_simple').dialog('open'); return false; }); $('#dialog_simple').dialog({ autoOpen: false, width: 600, resizable: false, modal: true, title: "<div class='widget-header'><h4><i class='fa fa-warning'></i> Empty the recycle bin?</h4></div>", buttons: [{ html: "<i class='fa fa-trash-o'></i>&nbsp; Delete all items", "class": "btn btn-danger", click: function () { $(this).dialog("close"); } }, { html: "<i class='fa fa-times'></i>&nbsp; Cancel", "class": "btn btn-default", click: function () { $(this).dialog("close"); } }] }); /* * DIALOG HEADER ICON */ // Modal Link $('#modal_link').click(function () { $('#dialog-message').dialog('open'); return false; }); $("#dialog-message").dialog({ autoOpen: false, modal: true, title: "<div class='widget-header'><h4><i class='icon-ok'></i> jQuery UI Dialog</h4></div>", buttons: [{ html: "Cancel", "class": "btn btn-default", click: function () { $(this).dialog("close"); } }, { html: "<i class='fa fa-check'></i>&nbsp; OK", "class": "btn btn-primary", click: function () { $(this).dialog("close"); } }] }); /* * Remove focus from buttons */ $('.ui-dialog :button').blur(); /* * Just Tabs */ $('#tabs').tabs(); /* * Simple tabs adding and removing */ $('#tabs2').tabs(); // Dynamic tabs var tabTitle = $("#tab_title"), tabContent = $("#tab_content"), tabTemplate = "<li style='position:relative;'> <span class='air air-top-left delete-tab' style='top:7px; left:7px;'><button class='btn btn-xs font-xs btn-default hover-transparent'><i class='fa fa-times'></i></button></span></span><a href='#{href}'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #{label}</a></li>", tabCounter = 2; var tabs = $("#tabs2").tabs(); // modal dialog init: custom buttons and a "close" callback reseting the form inside var dialog = $("#addtab").dialog({ autoOpen: false, width: 600, resizable: false, modal: true, buttons: [{ html: "<i class='fa fa-times'></i>&nbsp; Cancel", "class": "btn btn-default", click: function () { $(this).dialog("close"); } }, { html: "<i class='fa fa-plus'></i>&nbsp; Add", "class": "btn btn-danger", click: function () { addTab(); $(this).dialog("close"); } }] }); // addTab form: calls addTab function on submit and closes the dialog var form = dialog.find("form").submit(function (event) { addTab(); dialog.dialog("close"); event.preventDefault(); }); // actual addTab function: adds new tab using the input from the form above function addTab() { var label = tabTitle.val() || "Tab " + tabCounter, id = "tabs-" + tabCounter, li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label)), tabContentHtml = tabContent.val() || "Tab " + tabCounter + " content."; tabs.find(".ui-tabs-nav").append(li); tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>"); tabs.tabs("refresh"); tabCounter++; // clear fields $("#tab_title").val(""); $("#tab_content").val(""); } // addTab button: just opens the dialog $("#add_tab").button().click(function () { dialog.dialog("open"); }); // close icon: removing the tab on click $("#tabs2").on("click", 'span.delete-tab', function () { var panelId = $(this).closest("li").remove().attr("aria-controls"); $("#" + panelId).remove(); tabs.tabs("refresh"); }); /* * ACCORDION */ //jquery accordion var accordionIcons = { header: "fa fa-plus", // custom icon class activeHeader: "fa fa-minus" // custom icon class }; $("#accordion").accordion({ autoHeight: false, heightStyle: "content", collapsible: true, animate: 300, icons: accordionIcons, header: "h4", }) /* * PROGRESS BAR */ $("#progressbar").progressbar({ value: 25, create: function (event, ui) { $(this).removeClass("ui-corner-all").addClass('progress').find(">:first-child").removeClass("ui-corner-left").addClass('progress-bar progress-bar-success'); } }); }) </script> }
the_stack
@page @{ ViewData["Title"] = "Privacy Policy"; } <h1>AllReady Privacy Policy</h1> <div> This privacy policy has been compiled to better serve those who are concerned with how their 'Personally Identifiable Information' (PII) is being used online. PII, as described in US privacy law and information security, is information that can be used on its own or with other information to identify, contact, or locate a single person, or to identify an individual in context. Please read our privacy policy carefully to get a clear understanding of how we collect, use, protect or otherwise handle your Personally Identifiable Information in accordance with our website. </div> <div> <strong>What personal information do we collect from the people that visit our blog, website or app?</strong> </div> <div> When registering on our site, as appropriate, you may be asked to enter your name, email address, phone number or other details to help you with your experience. </div> <div> <strong>When do we collect information?</strong> </div> <div> We collect information from you when you register on our site or enter information on our site. </div> <p><br></p> <div> <strong>How do we use your information?</strong> </div> <div> We may use the information we collect from you when you register, sign up volunteer, respond to a survey or marketing communication, surf the website, or use certain other site features in the following ways:<br> </div> <div> <strong>&bull;</strong> To personalize your experience and to allow us to deliver the type of content and events in which you are most interested. </div> <div> <strong>&bull;</strong> To follow up with you after correspondence (live chat, email or phone inquiries) </div> <div> <strong>How do we protect your information?</strong> </div> <div> We only provide articles and information. We never ask for credit card numbers. </div> <div> We use regular Malware Scanning.<br> </div> <div> Your personal information is contained behind secured networks and is only accessible by a limited number of persons who have special access rights to such systems, and are required to keep the information confidential. In addition, all sensitive information you supply is encrypted via Secure Socket Layer (SSL) technology. </div> <div> We implement a variety of security measures when a user enters, submits, or accesses their information to maintain the safety of your personal information. </div> <div> <strong>Do we use 'cookies'?</strong> </div> <div> Yes. Cookies are small files that a site or its service provider transfers to your computer's hard drive through your Web browser (if you allow) that enables the site's or service provider's systems to recognize your browser and capture and remember certain information. For instance, we use cookies to help us remember and progress events that you are interested in. They are also used to help us understand your preferences based on previous or current site activity, which enables us to improve the experience for all volunteers. We also use cookies to help us compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. </div> <div> <br> <strong>We use cookies to:</strong> </div> <div> <strong>&bull;</strong> Understand and save user's preferences for future visits. </div> <div> <br> You can choose to have your computer warn you each time a cookie is being sent, or you can choose to turn off all cookies. You do this through your browser settings. Since browser is a little different, look at your browser's Help Menu to learn the correct way to modify your cookies. </div> <div> <br> <strong>If users disable cookies in their browser:</strong> </div> <div> If you turn cookies off, Some of the features that make your site experience more efficient may not function properly.Some of the features that make your site experience more efficient and may not function properly. </div> <p><br></p> <div> <strong>Third-party disclosure</strong> </div> <div> <strong>Do we disclose the information we collect to Third-Parties?</strong> </div> <div> Part of our mission is to fulfill needs as specified in the requests of those who use our site. We transfer the information needed to outside parties including names, addresses and contact information such as email and phone number. <div> <br> <strong>We engage in this practice because:</strong> </div> <div> We work with other charitable organizations in order to fulfill requests for help from our web site visitors. </div> </div> <p><br></p> <div> <strong>Third-party links</strong> </div> <div> We do not include or offer third-party products or services on our website. </div> <div> <strong>Google</strong> </div> <div> Google's advertising requirements can be summed up by Google's Advertising Principles. They are put in place to provide a positive experience for users. https://support.google.com/adwordspolicy/answer/1316548?hl=en<br> </div> <div> We have not enabled Google AdSense on our site but we may do so in the future. </div> <div> <strong>California Online Privacy Protection Act</strong> </div> <div> CalOPPA is the first state law in the nation to require commercial websites and online services to post a privacy policy. The law's reach stretches well beyond California to require any person or company in the United States (and conceivably the world) that operates websites collecting Personally Identifiable Information from California consumers to post a conspicuous privacy policy on its website stating exactly the information being collected and those individuals or companies with whom it is being shared. - See more at: http://consumercal.org/california-online-privacy-protection-act-caloppa/#sthash.0FdRbT51.dpuf </div> <div> <br> <strong>According to CalOPPA, we agree to the following:</strong> </div> <div> Users can visit our site anonymously. </div> <div> Once this privacy policy is created, we will add a link to it on our home page or as a minimum, on the first significant page after entering our website. </div> <div> Our Privacy Policy link includes the word 'Privacy' and can easily be found on the page specified above. </div> <div> <br> You will be notified of any Privacy Policy changes: </div> <div> <strong>&bull;</strong> On our Privacy Policy Page </div> <div> Can change your personal information: </div> <div> <strong>&bull;</strong> By logging in to your account </div> <div> <br> <strong>How does our site handle Do Not Track signals?</strong> </div> <div> We honor Do Not Track signals and Do Not Track, plant cookies, or use advertising when a Do Not Track (DNT) browser mechanism is in place. </div> <div> <br> <strong>Does our site allow third-party behavioral tracking?</strong> </div> <div> It's also important to note that we do not allow third-party behavioral tracking </div> <div> <strong>COPPA (Children Online Privacy Protection Act)</strong> </div> <div> When it comes to the collection of personal information from children under the age of 13 years old, the Children's Online Privacy Protection Act (COPPA) puts parents in control. The Federal Trade Commission, United States' consumer protection agency, enforces the COPPA Rule, which spells out what operators of websites and online services must do to protect children's privacy and safety online.<br> </div> <div> We do not specifically market to children under the age of 13 years old. </div> <div> <strong>Fair Information Practices</strong> </div> <div> The Fair Information Practices Principles form the backbone of privacy law in the United States and the concepts they include have played a significant role in the development of data protection laws around the globe. Understanding the Fair Information Practice Principles and how they should be implemented is critical to comply with the various privacy laws that protect personal information.<br> </div> <div> <strong>In order to be in line with Fair Information Practices we will take the following responsive action, should a data breach occur:</strong> </div> <div> We will notify you via email within 7 business days </div> <div> <br> We also agree to the Individual Redress Principle which requires that individuals have the right to legally pursue enforceable rights against data collectors and processors who fail to adhere to the law. This principle requires not only that individuals have enforceable rights against data users, but also that individuals have recourse to courts or government agencies to investigate and/or prosecute non-compliance by data processors. </div> <div> <strong>CAN SPAM Act</strong> </div> <div> The CAN-SPAM Act is a law that sets the rules for commercial email, establishes requirements for commercial messages, gives recipients the right to have emails stopped from being sent to them, and spells out tough penalties for violations.<br> </div> <div> <strong>We collect your email address in order to:</strong> </div> <div> <strong>&bull;</strong> Send information, respond to inquiries, and/or other requests or questions </div> <div> <br> <strong>To be in accordance with CANSPAM, we agree to the following:</strong> </div> <div> <strong>&bull;</strong> Not use false or misleading subjects or email addresses. </div> <div> <strong>&bull;</strong> Identify the message as an advertisement in some reasonable way. </div> <div> <strong>&bull;</strong> Include the physical address of our business or site headquarters. </div> <div> <strong>&bull;</strong> Monitor third-party email marketing services for compliance, if one is used. </div> <div> <strong>&bull;</strong> Honor opt-out/unsubscribe requests quickly. </div> <div> <strong>&bull;</strong> Allow users to unsubscribe by using the link at the bottom of each email. </div> <div> <strong> <br> If at any time you would like to unsubscribe from receiving future emails you can: </strong> </div> <div> <strong>&bull;</strong> Follow the instructions at the bottom of each email. </div> <p>and we will promptly remove you from any related correspondence.<br></p> <div> <strong>Contacting Us</strong> </div> <div> If there are any questions regarding this privacy policy, you may contact us using the information below.<br> </div> <div> AllReady </div> <div> <strong>Humanitarian Toolbox</strong> <br /> PO Box 212<br /> Medina, WA 98039<br /> </div> <div> help@htbox.org </div> <div> <br> Last Edited on 2017-11-08 </div>
the_stack
@page @model FlotModel @{ ViewData["Title"] = "Flot"; ViewData["PageName"] = "statistics_flot"; ViewData["Category1"] = "Statistics"; ViewData["Heading"] = "<i class='subheader-icon fal fa-chart-pie'></i> Flot <sup class='badge badge-primary fw-500'>ADDON</sup>"; ViewData["PageDescription"] = "Flot is a pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks and interactive features"; } @section HeadBlock {} <div class="alert alert-primary"> <div class="d-flex flex-start w-100"> <div class="mr-2 hidden-md-down"> <span class="icon-stack icon-stack-lg"> <i class="base base-6 icon-stack-3x opacity-100 color-primary-500"></i> <i class="base base-10 icon-stack-2x opacity-100 color-primary-300 fa-flip-vertical"></i> <i class="ni ni-blog-read icon-stack-1x opacity-100 color-white"></i> </span> </div> <div class="d-flex flex-fill"> <div class="flex-fill"> <span class="h5">Ease of use</span> <p> Flot is a pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks and interactive features. Additional examples are bundled with Flot. Flot is easy to use, just a few lines of code, you can make a simple line chart, it also provides a comprehensive API documentation where you can find examples, usage and methods. The most important part, Flot continues to release new versions, each new version comes with new features. </p> <p class="m-0"> Find more examples and guidelines on Flot's <a href="https://www.flotcharts.org/flot/examples/" target="_blank">official documentation</a> and detailed tutorials on <a href="http://www.jqueryflottutorial.com/how-to-make-jquery-flot-line-chart.html" target="_blank">Flot Tutorials</a> </p> </div> </div> </div> </div> <div class="row"> <div class="col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> Kitchen <span class="fw-300"><i>Sink (example)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> We use a combination of various plots to create a more intricate diagram. More basic examples of plot can be found below </div> <div id="js-checkbox-toggles" class="d-flex mb-3"> <div class="custom-control custom-switch mr-2"> <input type="checkbox" class="custom-control-input" name="gra-0" id="gra-0" checked=""> <label class="custom-control-label" for="gra-0">Target Profit</label> </div> <div class="custom-control custom-switch mr-2"> <input type="checkbox" class="custom-control-input" name="gra-1" id="gra-1" checked=""> <label class="custom-control-label" for="gra-1">Actual Profit</label> </div> <div class="custom-control custom-switch mr-2"> <input type="checkbox" class="custom-control-input" name="gra-2" id="gra-2" checked=""> <label class="custom-control-label" for="gra-2">User Signups</label> </div> </div> <div id="flot-toggles" class="w-100 mt-4" style="height: 300px"></div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-2" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Bar</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Single barchart to display timeline differences. It is currently displaying only one group of data </div> <div id="flot-bar" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-3" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Line</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Flot lines are the most easest to make and can display lots of data very nicely! </div> <div id="flot-line" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-4" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Line (tooltip)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Adding tooltips is easy, you will need to include the plugin <code>jquery.flot.tooltip.js</code> </div> <div id="flot-line-alt" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-5" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Area</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Area chart overlaps one over the other, making it easier to see the proportion of data </div> <div id="flot-area" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-6" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Interval Curve</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Generates random data to populate and redraw recursively, we use the <code>jquery.flot.spline.js</code> plugin to make the lines curvey </div> <div class="btn-group"> <button class="btn btn-secondary btn-sm dropdown-toggle mb-g" type="button" data-toggle="dropdown" aria-expanded="false"> Change interval </button> <div class="dropdown-menu dropdown-lg p-0"> <div class="px-4 py-2 d-flex align-items-center justify-content-center"> <input type="range" class="custom-range js-set-interval" id="js-flot-realtime-curved-speed" min="-1000" max="-100" step="100" value="-1000"> </div> </div> </div> <div id="flot-realtime-curved" style="width:100%; height:300px;"></div> </div> </div> </div> </div> <div class="col-xl-6"> <div id="panel-7" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Multiple Bars</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Here we compare relations of different data groups, the greater the length of bar, bigger the value </div> <div id="flot-bar-fill" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-8" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Curved Lines</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Curved lines by using the plugin <code>jquery.flot.spline.js</code>, adding a nice transition to the eyes </div> <div id="flot-line-curves" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-9" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Curved (tooltip)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> We take the flot chart from previous example (above) and add tooltips </div> <div id="flot-line-curves-alt" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-10" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Area Curved</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> This Area chart has smooth curved lines to make it easy to read </div> <div id="flot-area-fill" style="width:100%; height:300px;"></div> </div> </div> </div> <div id="panel-11" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Interval (fill)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> In this interval example we fill the whitespace. You can also try the interval button to change the speed of the redrawing </div> <div class="btn-group"> <button class="btn btn-secondary btn-sm dropdown-toggle mb-g" type="button" data-toggle="dropdown" aria-expanded="false"> Change interval </button> <div class="dropdown-menu dropdown-lg p-0"> <div class="px-4 py-2 d-flex align-items-center justify-content-center"> <input type="range" class="custom-range js-set-interval" id="js-flot-realtime-fill-speed" min="-1000" max="-100" step="100" value="-1000"> </div> </div> </div> <div id="flot-realtime-fill" style="width:100%; height:300px;"></div> </div> </div> </div> </div> <div class="col-xl-12"> <div id="panel-12" class="panel"> <div class="panel-hdr"> <h2> Flot <span class="fw-300"><i>Pie</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Pie chart is used to see the proprotion of each data groups, making Flot pie chart is pretty simple, in order to make pie chart you have to incldue <code>jquery.flot.pie.js</code> plugin </div> <div class="row"> <div class="col-xl-5"> <div id="js-pie-options" class="w-100" style="height: 250px"></div> </div> <div class="col-xl-6 offset-xl-1"> <div class="h-100 d-flex align-items-center mt-3 mt-xl-0"> <div class="demo"> <button id="example-1" class="btn btn-outline-primary js-pie-example">Default Options</button> <button id="example-2" class="btn btn-outline-primary js-pie-example">Without Legend</button> <button id="example-3" class="btn btn-outline-primary js-pie-example">Label Formatter</button> <button id="example-4" class="btn btn-outline-primary js-pie-example">Label Radius</button> <button id="example-5" class="btn btn-outline-primary js-pie-example">Label Styles #1</button> <button id="example-6" class="btn btn-outline-primary js-pie-example">Label Styles #2</button> <button id="example-7" class="btn btn-outline-primary js-pie-example">Hidden Labels</button> <button id="example-8" class="btn btn-outline-primary js-pie-example">Combined Slice</button> <button id="example-9" class="btn btn-outline-primary js-pie-example">Rectangular Pie</button> <button id="example-10" class="btn btn-outline-primary js-pie-example">Tilted Pie</button> <button id="example-11" class="btn btn-outline-primary js-pie-example">Donut Hole</button> <button id="example-12" class="btn btn-outline-primary js-pie-example">Interactivity</button> </div> </div> </div> </div> </div> </div> </div> <div id="panel-13" class="panel"> <div class="panel-hdr"> <h2> Sales <span class="fw-300"><i>Chart (example)</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div class="panel-tag"> Pie chart is used to see the proprotion of each data groups, making Flot pie chart is pretty simple, in order to make pie chart you have to incldue <code>jquery.flot.pie.js</code> plugin </div> <div id="flot-sales" class="w-100" style="height: 350px"></div> </div> </div> </div> </div> </div> @section ScriptsBlock { <script src="~/js/statistics/flot/flot.bundle.js"></script> <script> /* defined datas */ var dataTargetProfit = [ [1354586000000, 153], [1364587000000, 658], [1374588000000, 198], [1384589000000, 663], [1394590000000, 801], [1404591000000, 1080], [1414592000000, 353], [1424593000000, 749], [1434594000000, 523], [1444595000000, 258], [1454596000000, 688], [1464597000000, 364] ] var dataProfit = [ [1354586000000, 53], [1364587000000, 65], [1374588000000, 98], [1384589000000, 83], [1394590000000, 980], [1404591000000, 808], [1414592000000, 720], [1424593000000, 674], [1434594000000, 23], [1444595000000, 79], [1454596000000, 88], [1464597000000, 36] ] var dataSignups = [ [1354586000000, 647], [1364587000000, 435], [1374588000000, 784], [1384589000000, 346], [1394590000000, 487], [1404591000000, 463], [1414592000000, 479], [1424593000000, 236], [1434594000000, 843], [1444595000000, 657], [1454596000000, 241], [1464597000000, 341] ] var dataSales = [ [1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 1177], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 1676], [1197241200000, 1205], [1197327600000, 1906], [1197414000000, 1710], [1197500400000, 1639], [1197586800000, 1540], [1197673200000, 1435], [1197759600000, 1301], [1197846000000, 1575], [1197932400000, 1481], [1198018800000, 1591], [1198105200000, 1608], [1198191600000, 1459], [1198278000000, 1234], [1198364400000, 1352], [1198450800000, 1686], [1198537200000, 1279], [1198623600000, 1449], [1198710000000, 1468], [1198796400000, 1392], [1198882800000, 1282], [1198969200000, 1208], [1199055600000, 1229], [1199142000000, 1177], [1199228400000, 1374], [1199314800000, 1436], [1199401200000, 1404], [1199487600000, 1253], [1199574000000, 1218], [1199660400000, 1476], [1199746800000, 1462], [1199833200000, 1500], [1199919600000, 1700], [1200006000000, 1750], [1200092400000, 1600], [1200178800000, 1500], [1200265200000, 1900], [1200351600000, 1930], [1200438000000, 1200], [1200524400000, 1980], [1200610800000, 1950], [1200697200000, 1900], [1200783600000, 1000], [1200870000000, 1050], [1200956400000, 1150], [1201042800000, 1100], [1201129200000, 1200], [1201215600000, 1300], [1201302000000, 1700], [1201388400000, 1450], [1201474800000, 1500], [1201561200000, 1546], [1201647600000, 1614], [1201734000000, 1954], [1201820400000, 1700], [1201906800000, 1800], [1201993200000, 1900], [1202079600000, 2000], [1202166000000, 2100], [1202252400000, 2200], [1202338800000, 2300], [1202425200000, 2400], [1202511600000, 2550], [1202598000000, 2600], [1202684400000, 2500], [1202770800000, 2700], [1202857200000, 2750], [1202943600000, 2800], [1203030000000, 3245], [1203116400000, 3345], [1203202800000, 3000], [1203289200000, 3200], [1203375600000, 3300], [1203462000000, 3400], [1203548400000, 3600], [1203634800000, 3700], [1203721200000, 3800], [1203807600000, 4000], [1203894000000, 4500] ]; var dataSetBar1 = [ [0, 3], [2, 8], [4, 5], [6, 13], [8, 5], [10, 7], [12, 4], [14, 6] ]; var dataSetBar2 = [ [0, 3], [2, 8], [4, 5], [6, 13], [8, 5], [10, 7], [12, 8], [14, 10] ]; var dataSetBar3 = [ [1, 5], [3, 7], [5, 10], [7, 7], [9, 9], [11, 5], [13, 4], [15, 6] ]; var dataSet1 = [ [0, 2], [1, 3], [2, 6], [3, 5], [4, 7], [5, 8], [6, 10] ]; var dataSet2 = [ [0, 1], [1, 2], [2, 5], [3, 3], [4, 5], [5, 6], [6, 9] ]; var dataSet3 = [ [0, 10], [1, 7], [2, 8], [3, 9], [4, 6], [5, 5], [6, 7] ]; var dataSet4 = [ [0, 8], [1, 5], [2, 6], [3, 8], [4, 4], [5, 3], [6, 6] ]; var dataSetPie = [{ label: "Asia", data: 4119630000, color: color.primary._500 }, { label: "Latin America", data: 590950000, color: color.info._500 }, { label: "Africa", data: 1012960000, color: color.warning._500 }, { label: "Oceania", data: 95100000, color: color.danger._500 }, { label: "Europe", data: 727080000, color: color.success._500 }, { label: "North America", data: 344120000, color: color.fusion._400 } ]; var data = [], totalPoints = 50; var plotRealtimeCurvedInterval = 1000; var plotRealtimeFillInterval = 1000; /* generate random data */ var getRandomData = function () { if (data.length > 0) data = data.slice(1); while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } data.push(y); } var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } /* generate random data -- end */ /* label formatter */ var labelFormatter = function (label, series) { return "<div class='fs-xs text-center p-1 text-white'>" + label + "<br/>" + Math.round(series.percent) + "%</div>"; } /* label formatter -- end */ /* init() interval range */ $(document).on('change', '.js-set-interval', function () { plotRealtimeFillInterval = Math.abs($('#js-flot-realtime-fill-speed').val()); plotRealtimeCurvedInterval = Math.abs($('#js-flot-realtime-curved-speed').val()); }) $(document).ready(function () { /* flot bar */ var flotBar = $.plot("#flot-bar", [{ data: [ [0, 3], [2, 8], [4, 5], [6, 13], [8, 5], [10, 7], [12, 4], [14, 6] ] }], { series: { bars: { show: true, lineWidth: 0, fillColor: color.fusion._200 } }, grid: { borderWidth: 1, borderColor: '#eee' }, yaxis: { tickColor: '#eee', font: { color: '#999', size: 10 } }, xaxis: { tickColor: '#eee', font: { color: '#999', size: 10 } } }); /* flot bar lines -- end */ /* flot bar lines multiple */ var flotBarFill = $.plot("#flot-bar-fill", [{ data: [ [0, 3], [2, 8], [4, 5], [6, 13], [8, 5], [10, 7], [12, 8], [14, 10] ], bars: { show: true, lineWidth: 0, fillColor: color.success._500 } }, { data: [ [1, 5], [3, 7], [5, 10], [7, 7], [9, 9], [11, 5], [13, 4], [15, 6] ], bars: { show: true, lineWidth: 0, fillColor: color.primary._500 } }], { grid: { borderWidth: 1, borderColor: '#D9D9D9' }, yaxis: { tickColor: '#d9d9d9', font: { color: '#666', size: 10 } }, xaxis: { tickColor: '#d9d9d9', font: { color: '#666', size: 10 } } }); /* flot bar lines multiple -- end */ /* flot simple lines */ var flotLine = $.plot($('#flot-line'), [{ data: dataSet1, label: 'New Customer', color: color.primary._400 }, { data: dataSet2, label: 'Returning Customer', color: color.fusion._400 } ], { series: { lines: { show: true, lineWidth: 1 }, shadowSize: 0 }, points: { show: false, }, legend: { noColumns: 1, position: 'nw' }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot simple lines -- end */ /* flot lines curved */ var flotLineCurves = $.plot($('#flot-line-curves'), [{ data: dataSet1, label: 'New Customer', color: color.primary._400 }, { data: dataSet2, label: 'Returning Customer', color: color.fusion._400 } ], { series: { lines: { show: false }, splines: { show: true, tension: 0.4, lineWidth: 1, //fill: 0.4 }, shadowSize: 0 }, points: { show: false, }, legend: { noColumns: 1, position: 'nw' }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot lines curved -- end */ /* flot lines tooltip */ var flotLineAlt = $.plot($('#flot-line-alt'), [{ data: dataSet3, label: 'New Customer', color: color.danger._500 }, { data: dataSet4, label: 'Returning Customer', color: color.success._500 } ], { series: { lines: { show: true, lineWidth: 1 }, shadowSize: 0 }, points: { show: true, }, legend: { noColumns: 1, position: 'nw' }, tooltip: true, tooltipOpts: { cssClass: 'tooltip-inner', defaultTheme: false, shifts: { x: 10, y: -40 } }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot lines tooltip -- end */ /* flot lines curved tooltip */ var flotLineCurvesAlt = $.plot($('#flot-line-curves-alt'), [{ data: dataSet3, label: 'New Customer', color: color.danger._500 }, { data: dataSet4, label: 'Returning Customer', color: color.success._500 } ], { series: { lines: { show: false }, splines: { show: true, tension: 0.4, lineWidth: 1, //fill: 0.4 }, shadowSize: 0 }, points: { show: true, }, legend: { noColumns: 1, position: 'nw' }, tooltip: true, tooltipOpts: { cssClass: 'tooltip-inner', defaultTheme: false, shifts: { x: 10, y: -40 } }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot lines curved tooltip -- end */ /* flot area */ var flotArea = $.plot($('#flot-area'), [{ data: dataSet1, label: 'New Customer', color: color.primary._500 }, { data: dataSet2, label: 'Returning Customer', color: color.fusion._500 } ], { series: { lines: { show: true, lineWidth: 0, fill: 0.8 }, shadowSize: 0 }, points: { show: false, }, legend: { noColumns: 1, position: 'nw' }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot area -- end */ /* flot area fill */ var flotAreaFill = $.plot($('#flot-area-fill'), [{ data: dataSet1, label: 'New Customer', color: color.primary._500 }, { data: dataSet2, label: 'Returning Customer', color: color.fusion._500 } ], { series: { lines: { show: false }, splines: { show: true, tension: 0.4, lineWidth: 0, fill: 0.8 }, shadowSize: 0 }, points: { show: false, }, legend: { noColumns: 1, position: 'nw' }, grid: { hoverable: true, clickable: true, borderColor: '#ddd', borderWidth: 0, labelMargin: 5, backgroundColor: '#fff' }, yaxis: { min: 0, max: 15, color: '#eee', font: { size: 10, color: '#999' } }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } } }); /* flot area fill -- end */ /* flot realtime curved */ var plotRealtimeCurved = $.plot('#flot-realtime-curved', [getRandomData()], { colors: [color.primary._500], series: { lines: { show: false }, splines: { show: true, tension: 0.4, lineWidth: 1, //fill: 0.9 }, shadowSize: 0 // Drawing is faster without shadows }, grid: { borderColor: '#ddd', borderWidth: 1, labelMargin: 5 }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } }, yaxis: { min: 0, max: 100, color: '#eee', font: { size: 10, color: '#999' } } }); /* flot realtime curved -- end */ /* flot realtime fill */ var plotRealtimeFill = $.plot('#flot-realtime-fill', [getRandomData()], { colors: [color.primary._200], series: { lines: { show: true, lineWidth: 0, fill: 0.9 }, shadowSize: 0 // Drawing is faster without shadows }, grid: { borderColor: '#ddd', borderWidth: 1, labelMargin: 5 }, xaxis: { color: '#eee', font: { size: 10, color: '#999' } }, yaxis: { min: 0, max: 100, color: '#eee', font: { size: 10, color: '#999' } } }); /* flot realtime fill -- end */ /* generate realtime data */ var updateRealtimeCurved = function () { plotRealtimeCurved.setData([getRandomData()]); plotRealtimeCurved.draw(); setTimeout(updateRealtimeCurved, plotRealtimeCurvedInterval); } var updateRealtimeFill = function () { plotRealtimeFill.setData([getRandomData()]); plotRealtimeFill.draw(); setTimeout(updateRealtimeFill, plotRealtimeFillInterval); } /* generate realtime data -- end */ updateRealtimeCurved(); updateRealtimeFill(); /* sales chart */ var plotSales = $.plot($('#flot-sales'), [{ data: dataSales, }], { series: { lines: { show: true, lineWidth: 1, fill: true, fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.15 }] } }, points: { show: true }, shadowSize: 0 }, selection: { mode: "x" }, grid: { hoverable: true, clickable: true, tickColor: '#f2f2f2', borderWidth: 1, borderColor: '#f2f2f2' }, tooltip: true, tooltipOpts: { cssClass: 'tooltip-inner', content: "Your sales for <span class='text-warning fw-500'>%x</span> was <span class='text-success fw-500'>$%y</span>", dateFormat: "%y-%0m-%0d", defaultTheme: false }, colors: [color.primary._500], xaxis: { mode: "time", tickLength: 5 } }); /* sales chart -- end */ /* flot toggle example */ var flot_toggle = function () { var data = [{ label: "Target Profit", data: dataTargetProfit, color: color.danger._500, bars: { show: true, align: "center", barWidth: 30 * 30 * 60 * 1000 * 80, lineWidth: 0, fillColor: { colors: [color.danger._900, color.danger._100] } }, highlightColor: 'rgba(255,255,255,0.3)', shadowSize: 0 }, { label: "Actual Profit", data: dataProfit, color: color.info._500, lines: { show: true, lineWidth: 5 }, shadowSize: 0, points: { show: true } }, { label: "User Signups", data: dataSignups, color: color.success._500, lines: { show: true, lineWidth: 2 }, shadowSize: 0, points: { show: true } }] var options = { grid: { hoverable: true, clickable: true, tickColor: '#f2f2f2', borderWidth: 1, borderColor: '#f2f2f2' }, tooltip: true, tooltipOpts: { cssClass: 'tooltip-inner', defaultTheme: false }, xaxis: { mode: "time" }, yaxes: { tickFormatter: function (val, axis) { return "$" + val; }, max: 1200 } }; var plot2 = null; function plotNow() { var d = []; $("#js-checkbox-toggles").find(':checkbox').each(function () { if ($(this).is(':checked')) { d.push(data[$(this).attr("name").substr(4, 1)]); } }); if (d.length > 0) { if (plot2) { plot2.setData(d); plot2.draw(); } else { plot2 = $.plot($("#flot-toggles"), d, options); } } }; $("#js-checkbox-toggles").find(':checkbox').on('change', function () { plotNow(); }); plotNow() } flot_toggle(); /* flot toggle example -- end*/ /* flot pie chart */ var flot_pie = function () { // target var placeholder = $("#js-pie-options"); /* init first plot */ $.plot(placeholder, dataSetPie, { series: { pie: { show: true } }, legend: { show: true } }); //buttons $(document).on('click', '.js-pie-example', function() { $("#js-pie-options").unbind(); var id = this.id; $(".js-pie-example").removeClass("active"); $("#"+id).addClass("active"); //$("#panel-12 .panel-hdr").addClass("highlight"); switch (true) { case (id == "example-1"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Chart (default)</span>'); $("#panel-12 .panel-tag").text("The default pie chart with no options set"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true } } }); break; case (id == "example-2"): // code block $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Chart (legend)</span>'); $("#panel-12 .panel-tag").text("The default pie chart when the legend is disabled. Since the labels would normally be outside the container, the chart is resized to fit"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true } }, legend: { show: false } }); break; case (id == "example-3"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Custom Label Formatter</span>'); $("#panel-12 .panel-tag").text("Added a semi-transparent background to the labels and a custom labelFormatter function"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 1, formatter: labelFormatter, background: { opacity: 0.8 } } } }, legend: { show: false } }); break; case (id == "example-4"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Label Radius</span>'); $("#panel-12 .panel-tag").html("Slightly more transparent label backgrounds and adjusted the radius values to place them within the pie <code>radius: 3 / 4</code>"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 3 / 4, formatter: labelFormatter, background: { opacity: 0.5 } } } }, legend: { show: false } }); break; case (id == "example-5"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Label Styles #1</span>'); $("#panel-12 .panel-tag").html("Semi-transparent, black-colored label background"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 3 / 4, formatter: labelFormatter, background: { opacity: 0.5, color: "#000" } } } }, legend: { show: false } }); break; case (id == "example-6"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Label Styles #2</span>'); $("#panel-12 .panel-tag").html("Semi-transparent, black-colored label background placed at pie edge"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 3 / 4, label: { show: true, radius: 3 / 4, formatter: labelFormatter, background: { opacity: 0.5, color: "#000" } } } }, legend: { show: false } }); break; case (id == "example-7"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Hidden Labels</span>'); $("#panel-12 .panel-tag").html("Labels can be hidden if the slice is less than a given percentage of the pie (10% in this case)"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 2 / 3, formatter: labelFormatter, threshold: 0.1 } } }, legend: { show: false } }); break; case (id == "example-8"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Combined Slice</span>'); $("#panel-12 .panel-tag").html("Multiple slices less than a given percentage (5% in this case) of the pie can be combined into a single, larger slice"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, combine: { color: "#999", threshold: 0.05 } } }, legend: { show: false } }); break; case (id == "example-9"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Rectangular Pie</span>'); $("#panel-12 .panel-tag").html("The radius can also be set to a specific size (even larger than the container itself)"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 500, label: { show: true, formatter: labelFormatter, threshold: 0.1 } } }, legend: { show: false } }); break; case (id == "example-10"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Tilted Pie</span>'); $("#panel-12 .panel-tag").html("The pie can be tilted at an angle"); $.plot(placeholder, dataSetPie, { series: { pie: { show: true, radius: 1, tilt: 0.5, label: { show: true, radius: 1, formatter: labelFormatter, background: { opacity: 0.8 } }, combine: { color: "#999", threshold: 0.1 } } }, legend: { show: false } }); break; case (id == "example-11"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Donut Hole</span>'); $("#panel-12 .panel-tag").html("A donut hole can be added"); $.plot(placeholder, dataSetPie, { series: { pie: { innerRadius: 0.5, show: true } } }); break; case (id == "example-12"): $("#panel-12 h2").html('Pie <span class="fw-300 font-italic">Interactivity</span>'); $("#panel-12 .panel-tag").html("The pie can be made interactive with hover and click events"); $.plot(placeholder, dataSetPie, { series: { pie: { innerRadius: 0.5, show: true } } }); $.plot(placeholder, dataSetPie, { series: { pie: { show: true } }, grid: { hoverable: true, clickable: true } }); placeholder.bind("plothover", function (event, pos, obj) { if (!obj) { return; } var percent = parseFloat(obj.series.percent).toFixed(2); $("#hover").html("<span style='font-weight:bold; color:" + obj.series.color + "'>" + obj.series.label + " (" + percent + "%)</span>"); }); placeholder.bind("plotclick", function (event, pos, obj) { if (!obj) { return; } percent = parseFloat(obj.series.percent).toFixed(2); alert("" + obj.series.label + ": " + percent + "%"); }); break; } }); } flot_pie(); /* flot pie chart -- end*/ }); </script> }
the_stack
#addin nuget:?package=Cake.Xamarin //&version=2.0.1 //#addin nuget:?package=Cake.Xamarin.Build //&version=3.0.6 #addin nuget:?package=Cake.FileHelpers //&2.0.0 #addin nuget::?package=Cake.Incubator //&version=1.6.0 #addin nuget:?package=Xamarin.Nuget.Validator&version=1.1.1 /* ----------------------------------------------------------------------------------------- choco install -y gitlink ----------------------------------------------------------------------------------------- */ //#tool nuget:?package=gitlink // C# 6 interpolated strings support - experimental switch //var experimental = HasArgument("experimental"); //var exp = Argument<bool>("experimental", true); string TARGET = Argument ("t", Argument ("target", Argument ("Target", "Default"))); string ANDROID_HOME = EnvironmentVariable("ANDROID_HOME") ?? Argument("android_home", ""); string VERBOSITY = Argument ("v", Argument ("verbosity", Argument ("Verbosity", "Diagnostic"))); Verbosity verbosity = Verbosity.Diagnostic; Action<string> InformationFancy = (text) => { Console.BackgroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); return; }; // stuff needed for fixes! DirectoryPath vsLatest = null; FilePath msBuildPathX64 = null; string github_repo_url="https://github.com/xamarin/Xamarin.Auth"; // https://docs.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference#restore // http://cakebuild.net/api/Cake.Common.Tools.NuGet.Restore/NuGetRestoreSettings/ NuGetRestoreSettings nuget_restore_settings = new NuGetRestoreSettings { Verbosity = NuGetVerbosity.Detailed, }; NuGetUpdateSettings nuget_update_settings = new NuGetUpdateSettings { Verbosity = NuGetVerbosity.Detailed, Prerelease = false, }; Task ("dump-environment") .Does ( () => { if(IsRunningOnWindows()) { // Linux: ~/Android/Sdk // Mac: ~/Library/Android/sdk // Windows: %LOCALAPPDATA%\Android\sdk // Get absolute root path. // string[] paths = new string[] // { // EnvironmentVariable ("LOCALAPPDATA") + "/Android/android-sdk", // EnvironmentVariable ("ProgramFiles") + "/Android/android-sdk", // EnvironmentVariable ("ProgramFiles(x86)") + "/Android/android-sdk", // }; // foreach(string path in paths) // { // Information($"mc++ Searching = {path}"); // string root = MakeAbsolute(Directory(path)).FullPath; // // Get directories // DirectoryPathCollection dirs = null; // try // { // dirs = GetSubDirectories(root); // foreach(DirectoryPath dir in dirs) // { // Information($"mc++ FullPath = {dir.FullPath}"); // } // ANDROID_HOME = root; // } // catch(Exception) // { // Information($"mc++ Search failed = {path}"); // } // } } // Print out environment variables to console // var ENV_VARS = EnvironmentVariables(); // Information ($"mc++ Environment Variables:"); // foreach (var ev in ENV_VARS) // { // Information ($" mc++ {ev.Key} = {ev.Value}"); // } // EnvironmentVariables evs = EnvironmentVariables (); // Information ("Environment Variables: {0}", ""); // foreach (EnvironmentVariable ev in evs) // { // Information ($"\t{ev.Key} = {ev.Value}"); // } // var list = AndroidSdkManagerList // ( // new AndroidSdkManagerToolSettings // { // SdkRoot = ANDROID_HOME, // SkipVersionCheck = false // } // ); // list.Dump(); // foreach (var a in list?.AvailablePackages) // { // Console.WriteLine($"{a.Description}\t{a.Version}\t{a.Path}"); // } // foreach (var a in list?.InstalledPackages) // { // Console.WriteLine($"{a.Description}\t{a.Version}\t{a.Path}"); // } // From Cake.Xamarin.Build, dumps out versions of things //LogSystemInfo (); return; } ); Task ("clean") .Does ( () => { DeleteDirectories ( GetDirectories("**/obj"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/Obj"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/bin"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/Bin"), new DeleteDirectorySettings { Recursive = true, Force = true } ); return; } ); Task ("distclean") .IsDependentOn ("clean") .Does ( () => { DeleteDirectories ( GetDirectories("**/obj"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/Obj"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/bin"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/Bin"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/packages"), new DeleteDirectorySettings { Recursive = true, Force = true } ); DeleteDirectories ( GetDirectories("**/Components"), new DeleteDirectorySettings { Recursive = true, Force = true } ); return; } ); Task ("rebuild") .IsDependentOn ("distclean") .IsDependentOn ("build") ; Task ("build") .IsDependentOn ("libs") .IsDependentOn ("samples") ; Task ("package") .IsDependentOn ("nuget") .IsDependentOn ("component") ; Task ("libs") .IsDependentOn ("libs-windows") .IsDependentOn ("libs-macosx") .Does ( () => { } ); //--------------------------------------------------------------- // building with custom preprocessor constants/defines // used by some projects // Azure Mobile Services Client // XAMARIN_AUTH_INTERNAL // to hide public Xamarin.Auth classes (API) // XAMARIN_CUSTOM_TABS_INTERNAL // to hide public CustomTabs classes (API) bool is_using_custom_defines = false; Task ("libs-custom") .Does ( () => { is_using_custom_defines = true; RunTarget("libs"); return; } ); //--------------------------------------------------------------- string[] source_solutions = new string[] { "./source/Xamarin.Auth-Library.sln", "./source/Xamarin.Auth-Library-VS4Mac.sln", //"./source/Xamarin.Auth-Library-VS2015.sln", "./source/Xamarin.Auth-Library-VS4W-2017.sln", }; string[] solutions_for_nuget_tests = new string[] { "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard-MacOSX-Xamarin.Studio.sln", "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard.sln", "./samples/Xamarin.Forms/Evolve16Labs/05-OAuth/ComicBook.sln", "./samples/Xamarin.Forms/Providers/XamarinAuth.XamarinForms.sln", }; string[] sample_solutions_macosx = new string[] { // "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard-MacOSX-Xamarin.Studio.sln", // "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard.sln", // "./samples/Xamarin.Forms/Evolve16Labs/05-OAuth/ComicBook.sln", // "./samples/Xamarin.Forms/Providers/XamarinAuth.XamarinForms.sln", }; string[] sample_solutions_windows = new string[] { // "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard-MacOSX-Xamarin.Studio.sln", // "./samples/Traditional.Standard/Providers/Xamarin.Auth.Samples.TraditionalStandard.sln", // "./samples/Xamarin.Forms/Evolve16Labs/05-OAuth/ComicBook.sln", // "./samples/Xamarin.Forms/Providers/XamarinAuth.XamarinForms.sln", }; string[] sample_solutions = sample_solutions_macosx .Concat(sample_solutions_windows) // comment out this line if in need .ToArray() ; string[] solutions = source_solutions .Concat(sample_solutions) // comment out this line if in need .ToArray() ; string[] build_configurations = new [] { "Debug", "Release", }; //--------------------------------------------------------------------------------------- /* Custom preprocessor defines used by some projects (Azure Mobile Services) when passing preprocessor defines/constants through commandline all required defines must be specified on commandline (even DEBUG for Debug configurations). NOTE - there is deviation in Xamarin.Android behaviour which appends Android default constants (like __ANDROID__) and even some non-standard ones (like __MOBILE__) */ string custom_defines = "XAMARIN_AUTH_INTERNAL%3BXAMARIN_CUSTOM_TABS_INTERNAL%3BAZURE_MOBILE_SERVICES"; //--------------------------------------------------------------------------------------- string define = null; string nuget_3 = System.IO.Path.Combine(".", "tools", "nuget.3.exe"); string nuget_4 = System.IO.Path.Combine(".", "tools", "nuget.4.exe"); string nuget_5 = System.IO.Path.Combine(".", "tools", "nuget.5.exe"); Task ("nuget-install") .Does ( () => { if (! FileExists(nuget_5)) { DownloadFile ( "https://dist.nuget.org/win-x86-commandline/v5.1.0/nuget.exe", File(nuget_5), new Cake.Common.Net.DownloadFileSettings() { } ); } if (! FileExists(nuget_4)) { DownloadFile ( "https://dist.nuget.org/win-x86-commandline/v4.9.4/nuget.exe", File(nuget_4), new Cake.Common.Net.DownloadFileSettings() { } ); } if (! FileExists(nuget_3)) { DownloadFile ( "https://dist.nuget.org/win-x86-commandline/v3.5.0/nuget.exe", File(nuget_3), new Cake.Common.Net.DownloadFileSettings() { } ); } } ); Task ("nuget-restore") .IsDependentOn ("nuget-install") .Does ( () => { InformationFancy("nuget-restore"); Information("libs nuget_restore_settings.ToolPath = {0}", nuget_restore_settings.ToolPath); RunTarget("source-nuget-restore"); RunTarget("samples-nuget-restore"); return; } ); Task ("nuget-update") .IsDependentOn ("nuget-restore") .Does ( () => { FilePathCollection files_package_config = GetFiles("./**/packages.config"); foreach(FilePath package_config_file in files_package_config) { if (IsRunningOnWindows() && package_config_file.ToString().Length < 200) { continue; } else { } Information("Nuget Update = " + package_config_file); NuGetUpdate(package_config_file, nuget_update_settings); } return; } ); Task ("source-nuget-restore") .Does ( () => { foreach (string source_solution in source_solutions) { Information("Nuget Restore = " + source_solution); if (IsRunningOnWindows()) { if (source_solution.Contains("-VS2015.sln")) { nuget_restore_settings.ToolPath = nuget_3; NuGetRestore(source_solution, nuget_restore_settings); } else if (source_solution.Contains("-VS2017.sln")) { nuget_restore_settings.ToolPath = nuget_4; //NuGetRestore(source_solution, nuget_restore_settings); DotNetCoreRestore(source_solution); } else { nuget_restore_settings.ToolPath = nuget_5; //NuGetRestore(source_solution, nuget_restore_settings); DotNetCoreRestore(source_solution); } } else { nuget_restore_settings.ToolPath = nuget_4; NuGetRestore(source_solution, nuget_restore_settings); } } return; } ); Task ("samples-nuget-restore") .Does ( () => { foreach (string sample_solution in sample_solutions) { if (IsRunningOnWindows() && sample_solution.Length > 200) { continue; } else { } NuGetRestore(sample_solution, nuget_restore_settings); } return; } ); string solution_or_project = null; Action<string, MSBuildSettings> BuildLoop = ( sln_prj, // solution or project to be compiled msbuild_settings // msbuild customization settings ) => { if (sln_prj.Contains("Xamarin.Auth-Library.sln")) { /* 2017-09 Failing on Mac because of: * Uinversal Windows Platofrm * WinRT (Windows and Windows Phone) * WindowsPhone Silverlight * .NET Standard Failing on Windows in Visual Studio 2015 because of: * .NET Standard Failing on Windows in Visual Studio 2017 because of: * WinRT (Windows and Windows Phone) * WindowsPhone Silverlight */ return; } foreach (string build_configuration in build_configurations) { InformationFancy("BuildLoop:"); InformationFancy($" Solution/Project = {sln_prj}"); InformationFancy($" Configuration = {build_configuration}"); msbuild_settings.Verbosity = verbosity; msbuild_settings.Configuration = build_configuration; msbuild_settings.WithProperty ( "consoleloggerparameters", "ShowCommandLine" ); InformationFancy($" MsBuildSettings.Properties:"); foreach(KeyValuePair<string, IList<string>> kvp in msbuild_settings.Properties) { string values = string.Join(", ", kvp.Value); InformationFancy($" [{kvp.Key}] = {values}"); } if (sln_prj.Contains(".csproj")) { // NO OP - MSBuildToolVersion is set before calling } else if (sln_prj.Contains("Xamarin.Auth-Library-VS2015.sln") && IsRunningOnWindows() ) { NuGetRestore(sln_prj, nuget_restore_settings); /* Using Visual Studio 2015 tooling Fix for source\Xamarin.Auth.XamarinIOS\Xamarin.Auth.XamarinIOS.csproj" (Build target) (1) -> (CoreCompile target) -> C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets error MSB6004: The specified task executable location "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\Roslyn\csc.exe" is invalid. */ msbuild_settings.ToolVersion = MSBuildToolVersion.VS2015; /* Fix for C:\Program Files (x86)\MSBuild\Microsoft\WindowsPhone\v8.0\Microsoft.WindowsPhone.v8.0.Overrides.targets(15,9) error : Building Windows Phone application using MSBuild 64 bit is not supported. If you are using TFS build definitions, change the MSBuild platform to x86. */ msbuild_settings.PlatformTarget = PlatformTarget.x86; } else if (sln_prj.Contains("Xamarin.Auth-Library-VS4W-2017.sln") && IsRunningOnWindows() ) { /* C:\Program Files\dotnet\sdk\2.1.101\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets(327,5): error : Assets file 'X:\xa-m\source\Core\Xamarin.Auth.NetStandard10.ReferenceAssembly\obj\project.assets.json' not found. Run a NuGet package restore to generate this file. C:\Program Files\dotnet\sdk\2.1.101\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets(167,5): error : Assets file 'X:\xa-m\source\Core\Xamarin.Auth.NetStandard10.ReferenceAssembly\obj\project.assets.json' not found. Run a NuGet package restore to generate this file. */ NuGetRestore(sln_prj, nuget_restore_settings); NuGetRestore ( "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/Xamarin.Auth.NetStandard10.ReferenceAssembly.csproj", nuget_restore_settings ); NuGetRestore ( "./source/Core/Xamarin.Auth.NetStandard16/Xamarin.Auth.NetStandard16.csproj", nuget_restore_settings ); DotNetCoreRestore ( "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/Xamarin.Auth.NetStandard10.ReferenceAssembly.csproj" ); DotNetCoreRestore ( "./source/Core/Xamarin.Auth.NetStandard16/Xamarin.Auth.NetStandard16.csproj" ); DotNetCoreBuild ( "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/Xamarin.Auth.NetStandard10.ReferenceAssembly.csproj" ); DotNetCoreBuild ( "./source/Core/Xamarin.Auth.NetStandard16/Xamarin.Auth.NetStandard16.csproj" ); /* C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets error MSB6004: The specified task executable location "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\Roslyn\csc.exe" is invalid. [X:\x.a-m\source\Xamarin.Auth.XamarinIOS\Xamarin.Auth.XamarinIOS.csproj] */ msbuild_settings.ToolVersion = MSBuildToolVersion.VS2017; msbuild_settings.ToolPath = msBuildPathX64; msbuild_settings.WithProperty ( "RestoreIgnoreFailedSources", "true" ); } else if(sln_prj.Contains("Xamarin.Auth-Library-VS4Mac.sln") && ! IsRunningOnWindows() ) { // MacOSX only // return; } else if(sln_prj.Contains("Xamarin.Auth-Library.sln") && ! IsRunningOnWindows() ) { // cannot build solution with Windows platforms on Mac return; } else { return; } MSBuild(sln_prj,msbuild_settings); } return; }; Task ("libs-macosx-filesystem") .Does ( () => { CreateDirectory ("./output/"); CreateDirectory ("./output/pcl/"); CreateDirectory ("./output/android/"); CreateDirectory ("./output/ios/"); CreateDirectory ("./output/netstandard1.0/"); CreateDirectory ("./output/netstandard1.6/"); return; } ); Task ("libs-macosx") .IsDependentOn ("libs-macosx-solutions") .IsDependentOn ("libs-macosx-projects") .Does ( () => { RunTarget("copy-artifacts"); return; } ); Task ("libs-macosx-solutions") .IsDependentOn ("nuget-restore") .IsDependentOn ("libs-macosx-filesystem") .Does ( () => { if ( ! IsRunningOnWindows() ) { foreach(string sln in source_solutions) { InformationFancy($"Solution = {sln}"); BuildLoop ( sln, new MSBuildSettings { // Default Settings for Solutions Verbosity = verbosity, } ); } } return; } ); Task ("libs-macosx-projects") .IsDependentOn ("nuget-restore") .IsDependentOn ("libs-macosx-filesystem") .Does ( () => { if ( ! IsRunningOnWindows() ) { //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.Common.LinkSource/Xamarin.Auth.Common.LinkSource.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.Portable/Xamarin.Auth.Portable.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Core/Xamarin.Auth.Portable/**/Release/Xamarin.Auth.dll", "./output/pcl/" ); CopyFiles ( "./source/Core/Xamarin.Auth.Portable/**/Release/Xamarin.Auth.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.XamarinAndroid/Xamarin.Auth.XamarinAndroid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinAndroid/**/Release/Xamarin.Auth.dll", "./output/android/" ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinAndroid/**/Release/Xamarin.Auth.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.XamarinIOS/Xamarin.Auth.XamarinIOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinIOS/**/Release/Xamarin.Auth.dll", "./output/iOS/" ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinIOS/**/Release/Xamarin.Auth.pdb", "./output/iOS/" ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.Portable/Xamarin.Auth.Extensions.Portable.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.Portable/**/Release/Xamarin.Auth.Extensions.dll", "./output/pcl/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.Portable/**/Release/Xamarin.Auth.Extensions.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/Xamarin.Auth.Extensions.XamarinAndroid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/**/Release/Xamarin.Auth.Extensions.dll", "./output/android/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/**/Release/Xamarin.Auth.Extensions.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/Xamarin.Auth.Extensions.XamarinIOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/**/Release/Xamarin.Auth.Extensions.dll", "./output/ios/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/**/Release/Xamarin.Auth.Extensions.pdb", "./output/ios/" ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms/Xamarin.Auth.Forms.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/pcl/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms.Droid/Xamarin.Auth.Forms.Droid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.Droid/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/android/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.Droid/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms.iOS/Xamarin.Auth.Forms.iOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.iOS/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/ios/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.iOS/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/ios/" ); //------------------------------------------------------------------------------------- } // if ( ! IsRunningOnWindows() ) return; } ); Task ("libs-windows") //.IsDependentOn ("libs-windows-projects") .IsDependentOn ("libs-windows-solutions") .Does ( () => { RunTarget("copy-artifacts"); return; } ); // https://cakebuild.net/dsl/vswhere/ // needed to detect VS and Build Tools installations! Task ("libs-windows-tooling") .Does ( () => { //https://cakebuild.net/dsl/vswhere/ if (IsRunningOnWindows ()) { DirectoryPathCollection vswhere_all = null; vswhere_all = VSWhereAll ( new VSWhereAllSettings { Requires = "'Microsoft.Component.MSBuild" } ); foreach(DirectoryPath dp in vswhere_all) { InformationFancy(dp.Dump()); } DirectoryPathCollection vswhere_legacy = null; vswhere_legacy = VSWhereLegacy ( new VSWhereLegacySettings() { } ); foreach(DirectoryPath dp in vswhere_legacy) { InformationFancy(dp.Dump()); } DirectoryPath vswhere_latest = VSWhereLatest(); msBuildPathX64 = (vsLatest==null) ? null : vswhere_latest.CombineWithFilePath("./MSBuild/15.0/Bin/amd64/MSBuild.exe") ; InformationFancy("msBuildPathX64 = " + msBuildPathX64); // FIX csc path is invalid msBuildPathX64 = "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/MSBuild/15.0/Bin/MSBuild.exe"; InformationFancy("msBuildPathX64 FIXED = " + msBuildPathX64); } return; } ); Task ("libs-windows-filesystem") .IsDependentOn ("nuget-restore") .Does ( () => { CreateDirectory ("./output/"); CreateDirectory ("./output/pcl/"); CreateDirectory ("./output/android/"); CreateDirectory ("./output/ios/"); CreateDirectory ("./output/wp80/"); CreateDirectory ("./output/wp81/"); CreateDirectory ("./output/wpa81/"); CreateDirectory ("./output/wpa81/Xamarin.Auth/"); CreateDirectory ("./output/win81/"); CreateDirectory ("./output/win81/Xamarin.Auth/"); CreateDirectory ("./output/uap10.0/"); CreateDirectory ("./output/uap10.0/Xamarin.Auth/"); CreateDirectory ("./output/netstandard1.0/"); CreateDirectory ("./output/netstandard1.6/"); } ); Task ("libs-windows-solutions") .IsDependentOn ("nuget-restore") .IsDependentOn ("libs-windows-filesystem") .IsDependentOn ("libs-windows-tooling") .Does ( () => { if (IsRunningOnWindows ()) { foreach(string sln_prj in source_solutions) { if (sln_prj.Contains("Xamarin.Auth-Library.sln")) { // Xamarin.Auth-Library.sln contains all projects // cannot be built xplatform continue; } Information ($"BuildLoop {sln_prj}"); BuildLoop ( sln_prj, new MSBuildSettings { } ); } // GitLinkAction("./source/Xamarin.Auth-Library.sln"); // GitLinkAction("./source/Xamarin.Auth-Library-VS4Mac.sln"); return; } } ); Task ("libs-windows-projects") .IsDependentOn ("nuget-restore") .IsDependentOn ("libs-windows-filesystem") .IsDependentOn ("libs-windows-tooling") .Does ( () => { if (IsRunningOnWindows ()) { //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.Common.LinkSource/Xamarin.Auth.Common.LinkSource.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.Portable/Xamarin.Auth.Portable.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.XamarinAndroid/Xamarin.Auth.XamarinAndroid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { /* C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets error : Could not find android.jar for API Level 23. This means the Android SDK platform for API Level 23 is not installed. Either install it in the Android SDK Manager (Tools > Open Android SDK Manager...), or change your Xamarin.Android project to target an API version that is installed. (C:\Program Files (x86)\Android\android-sdk\platforms\android-23\android.jar missing.) */ ToolPath = msBuildPathX64, ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- InformationFancy("msBuildPathX64 = " + msBuildPathX64); solution_or_project = "./source/Core/Xamarin.Auth.XamarinIOS/Xamarin.Auth.XamarinIOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolPath = msBuildPathX64, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.WindowsPhone8/Xamarin.Auth.WindowsPhone8.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2015, PlatformTarget = PlatformTarget.x86, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.WindowsPhone81/Xamarin.Auth.WindowsPhone81.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- /* Dependencies omitted!! . ├── Release │   ├── Xamarin.Auth │   │   ├── WebAuthenticatorPage.xaml │   │   ├── WebAuthenticatorPage.xbf │   │   └── Xamarin.Auth.xr.xml │   ├── Xamarin.Auth.dll │   ├── Xamarin.Auth.pdb │   └── Xamarin.Auth.pri */ solution_or_project = "./source/Core/Xamarin.Auth.WinRTWindows81/Xamarin.Auth.WinRTWindows81.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/Xamarin.Auth.WinRTWindowsPhone81.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/Xamarin.Auth.UniversalWindowsPlatform.csproj"; /* Dependencies omitted!! . ├── Release │   ├── Xamarin.Auth │   │   ├── WebAuthenticatorPage.xaml │   │   └── Xamarin.Auth.xr.xml │   ├── Xamarin.Auth.dll │   ├── Xamarin.Auth.pdb │   └── Xamarin.Auth.pri */ if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { //ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); BuildLoop ( solution_or_project, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2017, }.WithProperty("DefineConstants", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/Xamarin.Auth.NetStandard10.ReferenceAssembly.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Core/Xamarin.Auth.NetStandard16/Xamarin.Auth.NetStandard16.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.Portable/Xamarin.Auth.Extensions.Portable.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/Xamarin.Auth.Extensions.XamarinAndroid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { /* C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets error : Could not find android.jar for API Level 23. This means the Android SDK platform for API Level 23 is not installed. Either install it in the Android SDK Manager (Tools > Open Android SDK Manager...), or change your Xamarin.Android project to target an API version that is installed. (C:\Program Files (x86)\Android\android-sdk\platforms\android-23\android.jar missing.) */ ToolPath = msBuildPathX64, ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/Xamarin.Auth.Extensions.XamarinIOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolPath = msBuildPathX64, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms/Xamarin.Auth.Forms.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms.Droid/Xamarin.Auth.Forms.Droid.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { /* C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets error : Could not find android.jar for API Level 23. This means the Android SDK platform for API Level 23 is not installed. Either install it in the Android SDK Manager (Tools > Open Android SDK Manager...), or change your Xamarin.Android project to target an API version that is installed. (C:\Program Files (x86)\Android\android-sdk\platforms\android-23\android.jar missing.) */ //ToolPath = msBuildPathX64, //ToolVersion = MSBuildToolVersion.VS2015, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- solution_or_project = "./source/XamarinForms/Xamarin.Auth.Forms.iOS/Xamarin.Auth.Forms.iOS.csproj"; if (is_using_custom_defines == true) { define = custom_defines; } BuildLoop ( solution_or_project, new MSBuildSettings { ToolPath = msBuildPathX64, }.WithProperty("XamarinAuthCustomPreprocessorConstantsDefines", define) ); //------------------------------------------------------------------------------------- } return; } ); Task ("copy-artifacts") .Does ( () => { //------------------------------------------------------------------------------------- CopyFiles ( @".\source\Core\Xamarin.Auth.Portable\**\Release\Xamarin.Auth.dll", @".\output\pcl\" ); CopyFiles ( "./source/Core/Xamarin.Auth.Portable/**/Release/Xamarin.Auth.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.XamarinAndroid/**/Release/Xamarin.Auth.dll", "./output/android/" ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinAndroid/**/Release/Xamarin.Auth.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.XamarinIOS/**/Release/Xamarin.Auth.dll", "./output/ios/" ); CopyFiles ( "./source/Core/Xamarin.Auth.XamarinIOS/**/Release/Xamarin.Auth.pdb", "./output/ios/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.WindowsPhone8/**/Release/Xamarin.Auth.dll", "./output/wp80/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WindowsPhone8/**/Release/Xamarin.Auth.pdb", "./output/wp80/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.WindowsPhone81/**/Release/Xamarin.Auth.dll", "./output/wp81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WindowsPhone81/**/Release/Xamarin.Auth.pdb", "./output/wp81/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/Xamarin.Auth.dll", "./output/win81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/Xamarin.Auth.pdb", "./output/win81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/Xamarin.Auth.pri", "./output/win81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/Xamarin.Auth.xr.xml", "./output/win81/Xamarin.Auth/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/WebAuthenticatorPage.xaml", "./output/win81/Xamarin.Auth/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindows81/**/Release/WebAuthenticatorPage.xbf", "./output/win81/Xamarin.Auth/" ); //------------------------------------------------------------------------------------- /* Dependencies omitted!! . ├── Release │   ├── Xamarin.Auth │   │   ├── WebAuthenticatorPage.xaml │   │   ├── WebAuthenticatorPage.xbf │   │   └── Xamarin.Auth.xr.xml │   ├── Xamarin.Auth.dll │   ├── Xamarin.Auth.pdb │   └── Xamarin.Auth.pri */ CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/Xamarin.Auth.dll", "./output/wpa81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/Xamarin.Auth.pdb", "./output/wpa81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/Xamarin.Auth.pri", "./output/wpa81/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/Xamarin.Auth.xr.xml", "./output/wpa81/Xamarin.Auth/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/WebAuthenticatorPage.xaml", "./output/wpa81/Xamarin.Auth/" ); CopyFiles ( "./source/Core/Xamarin.Auth.WinRTWindowsPhone81/**/Release/WebAuthenticatorPage.xbf", "./output/wpa81/Xamarin.Auth/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/Xamarin.Auth.dll", "./output/uap10.0/" ); CopyFiles ( "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/Xamarin.Auth.pdb", "./output/uap10.0/" ); CopyFiles ( "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/Xamarin.Auth.pri", "./output/uap10.0/" ); CopyFiles ( /* mc++ 2017-10-17 output changed?? Visual Studio does not generate Xamarin.Auth subfolder, but nuget needs it */ "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/Xamarin.Auth.xr.xml", "./output/uap10.0/Xamarin.Auth/" ); CopyFiles ( "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/WebAuthenticatorPage.xbf", "./output/uap10.0/Xamarin.Auth/" ); /* .net Native - Linking stuff - not needed CopyFiles ( "./source/Core/Xamarin.Auth.UniversalWindowsPlatform/bin/Release/Xamarin.Auth.rd.xml", "./output/uap10.0/Properties/" ); */ //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0/Xamarin.Auth.dll", "./output/netstandard1.0/" ); CopyFiles ( "./source/Core/Xamarin.Auth.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0/Xamarin.Auth.pdb", "./output/netstandard1.0/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Core/Xamarin.Auth.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.dll", "./output/netstandard1.6/" ); CopyFiles ( "./source/Core/Xamarin.Auth.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.pdb", "./output/netstandard1.6/" ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.Portable/**/Release/Xamarin.Auth.Extensions.dll", "./output/pcl/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.Portable/**/Release/Xamarin.Auth.Extensions.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/**/Release/Xamarin.Auth.Extensions.dll", "./output/android/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinAndroid/**/Release/Xamarin.Auth.Extensions.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/**/Release/Xamarin.Auth.Extensions.dll", "./output/ios/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.XamarinIOS/**/Release/Xamarin.Auth.Extensions.pdb", "./output/ios/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0/Xamarin.Auth.Extensions.dll", "./output/netstandard1.0/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0/Xamarin.Auth.Extensions.pdb", "./output/netstandard1.0/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.Extensions.dll", "./output/netstandard1.6/" ); CopyFiles ( "./source/Extensions/Xamarin.Auth.Extensions.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.Extensions.pdb", "./output/netstandard1.6/" ); //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/pcl/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/pcl/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/pcl/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.Droid/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/android/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.Droid/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/android/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.iOS/**/Release/Xamarin.Auth.XamarinForms.dll", "./output/ios/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.iOS/**/Release/Xamarin.Auth.XamarinForms.pdb", "./output/ios/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0/Xamarin.Auth.XamarinForms.dll", "./output/netstandard1.0/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.NetStandard10.ReferenceAssembly/**/Release/netstandard1.0//Xamarin.Auth.XamarinForms.pdb", "./output/netstandard1.0/" ); //------------------------------------------------------------------------------------- CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.XamarinForms.dll", "./output/netstandard1.6/" ); CopyFiles ( "./source/XamarinForms/Xamarin.Auth.Forms.NetStandard16/**/Release/netstandard1.6/Xamarin.Auth.XamarinForms.pdb", "./output/netstandard1.6/" ); //------------------------------------------------------------------------------------- return; } ); Task ("samples") .Does ( () => { if ( IsRunningOnWindows() ) { RunTarget ("samples-windows"); } RunTarget ("samples-macosx"); } ); Task ("samples-macosx") .IsDependentOn ("samples-nuget-restore") .IsDependentOn ("libs") .Does ( () => { foreach (string sample_solution in sample_solutions_macosx) { foreach (string configuration in build_configurations) { if ( IsRunningOnWindows() ) { MSBuild ( sample_solution, c => { c.SetConfiguration(configuration); } ); } else { MSBuild ( sample_solution, c => { c.SetConfiguration(configuration); } ); } } } return; } ); Task ("samples-windows") .IsDependentOn ("samples-nuget-restore") .IsDependentOn ("libs") .Does ( () => { foreach (string sample_solution in sample_solutions_windows) { foreach (string configuration in build_configurations) { if ( IsRunningOnWindows() ) { } else { MSBuild ( sample_solution, c => { c.SetConfiguration(configuration); } ); } } } return; } ); Task ("nuget") .IsDependentOn ("libs") .Does ( () => { string platform = null; string msg = "Missing Windows dll artifacts" + System.Environment.NewLine + "Please, build on Windows first!" + System.Environment.NewLine ; platform = "win81"; if ( ! FileExists($"./output/{platform}/Xamarin.Auth.dll") ) { throw new System.ArgumentNullException(msg + $"platform = {platform}"); } platform = "wp80"; if ( ! FileExists($"./output/{platform}/Xamarin.Auth.dll") ) { throw new System.ArgumentNullException(msg + $"platform = {platform}"); } platform = "wp81"; if ( ! FileExists($"./output/{platform}/Xamarin.Auth.dll") ) { throw new System.ArgumentNullException(msg + $"platform = {platform}"); } platform = "wpa81"; if ( ! FileExists($"./output/{platform}/Xamarin.Auth.dll") ) { throw new System.ArgumentNullException(msg + $"platform = {platform}"); } platform = "uap10.0"; if ( ! FileExists($"./output/{platform}/Xamarin.Auth.dll") ) { throw new System.ArgumentNullException(msg + $"platform = {platform}"); } NuGetPack ( "./nuget/Xamarin.Auth.nuspec", new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./output/", Symbols = true, ToolPath = nuget_4, RequireLicenseAcceptance = true } ); NuGetPack ( "./nuget/Xamarin.Auth.XamarinForms.nuspec", new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./output/", Symbols = true, ToolPath = nuget_4, RequireLicenseAcceptance = true } ); NuGetPack ( "./nuget/Xamarin.Auth.Extensions.nuspec", new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./output/", Symbols = true, ToolPath = nuget_4, RequireLicenseAcceptance = true } ); } ); Task("nuget-validation") .IsDependentOn("nuget") .Does(()=> { //setup validation options var options = new Xamarin.Nuget.Validator.NugetValidatorOptions() { Copyright = "© Microsoft Corporation. All rights reserved.", Author = "Microsoft", Owner = "Microsoft", NeedsProjectUrl = true, NeedsLicenseUrl = true, ValidateRequireLicenseAcceptance = true, ValidPackageNamespace = new [] { "Xamarin", "Mono", "SkiaSharp", "HarfBuzzSharp", "mdoc" }, }; var nupkgFiles = GetFiles ("./output/*.nupkg"); Information ("Found ({0}) Nuget's to validate", nupkgFiles.Count ()); foreach (var nupkgFile in nupkgFiles) { Information ("Verifiying Metadata of {0}", nupkgFile.GetFilename ()); var result = Xamarin.Nuget.Validator.NugetValidator.Validate(MakeAbsolute(nupkgFile).FullPath, options); if (!result.Success) { Information ("Metadata validation failed for: {0} \n\n", nupkgFile.GetFilename ()); Information (string.Join("\n ", result.ErrorMessages)); throw new Exception ($"Invalid Metadata for: {nupkgFile.GetFilename ()}"); } else { Information ("Metadata validation passed for: {0}", nupkgFile.GetFilename ()); } } }); Task ("externals") .Does ( () => { return; } ); Task ("component") .IsDependentOn ("nuget") .IsDependentOn ("samples") .Does ( () => { var COMPONENT_VERSION = "1.3.1.1"; var yamls = GetFiles ("./**/component.yaml"); foreach (var yaml in yamls) { Information("yaml = " + yaml); var contents = FileReadText (yaml).Replace ("$version$", COMPONENT_VERSION); var fixedFile = yaml.GetDirectory ().CombineWithFilePath ("component.yaml"); FileWriteText (fixedFile, contents); // PackageComponent // ( // fixedFile.GetDirectory (), // new XamarinComponentSettings () // ); } if (!DirectoryExists ("./output")) { CreateDirectory ("./output"); } CopyFiles ("./component/**/*.xam", "./output"); } ); FilePath GetToolPath (FilePath toolPath) { var appRoot = Context.Environment.ApplicationRoot; var appRootExe = appRoot.CombineWithFilePath (toolPath); if (FileExists (appRootExe)) { return appRootExe; } throw new FileNotFoundException ("Unable to find tool: " + appRootExe); } //================================================================================================= // Put those 2 CI targets at the end of the file after all targets // If those targets are before 1st RunTarget() call following error occusrs on // * MacOSX under Mono // * Windows // // Task 'ci-osx' is dependent on task 'libs' which do not exist. // // Xamarin CI - Jenkins job targets Task ("ci-osx") .IsDependentOn ("nuget") //.IsDependentOn ("samples") ; Task ("ci-windows") .IsDependentOn ("libs") //.IsDependentOn ("nuget") //.IsDependentOn ("samples") ; //================================================================================================= Task("Default") .Does ( () => { Information($"Arguments: "); Information($"\t\t TARGET: " + TARGET); Information($"\t\t VERBOSITY: " + VERBOSITY); Information($"Usage: " + Environment.NewLine); Information($"-v | --verbosity | --Verbosity "); Information($"-t | --target | --Target "); Information($" Target task to be executed:"); Information($" libs - compile source (libs only"); Information($" libs-custom"); Information($" clean"); Information($" distclean"); Information($" rebuild"); Information($" build"); Information($" package"); Information($" nuget-restore"); Information($" nuget-update"); Information($" source-nuget-restore - "); Information($" samples-nuget-restore -"); Information($" libs-macosx-filesystem -"); Information($" libs-macosx - "); Information($" libs-macosx-solutions"); Information($" libs-macosx-projects"); Information($" libs-windows"); Information($" libs-windows-tooling"); Information($" libs-windows-filesystem"); Information($" libs-windows-solutions"); Information($" libs-windows-projects"); Information($" samples"); Information($" samples-macosx"); Information($" samples-windows"); Information($" nuget"); Information($" externals"); Information($" component"); //verbosity = (VERBOSITY == null) : return; } ); Task ("ci") .Does ( () => { RunTarget("nuget"); return; } ); RunTarget("dump-environment"); //RunTarget("distclean"); //RunTarget ("android-sdk-install"); RunTarget (TARGET);
the_stack
@using cohort @{ Layout = "~/Views/Shared/_WithoutNavNarrow.cshtml"; } @section Head { @if (Cohort.Site.Stripe.Enabled && Cohort.Site.Stripe.CaptureCardOnSignUp) { <link href="/Content/cc.css" rel="stylesheet" media="screen"> } } <form class="form-horizontal" action='@Url.Action("SignUp", "Cohort")' method="post"> <fieldset> <legend>Your Info</legend> @Html.Partial("_ValidationSummary", ViewData.ModelState) <div class="control-group"> <label class="control-label" for="email">Email</label> <div class="controls"> <input id="email" name="email" placeholder="" class="input-xlarge required" type="email"> <p class="help-block">We will send login instructions to this address.</p> </div> </div> <div class="control-group"> <label class="control-label" for="password">Password</label> <div class="controls"> <input type="password" id="password" name="password" placeholder="" class="input-xlarge required"> <p class="help-block">Password should be at least 4 characters</p> </div> </div> <div class="control-group"> <label class="control-label" for="confirm_password">Password (again)</label> <div class="controls"> <input type="password" id="confirm_password" name="confirm_password" placeholder="" class="input-xlarge required"> <p class="help-block">Please confirm password</p> </div> </div> @if (!Cohort.Site.Stripe.Enabled || !Cohort.Site.Stripe.CaptureCardOnSignUp) { <div class="control-group"> <div class="controls"> <button class="btn btn-success">Go!</button> </div> </div> } </fieldset> @if (Cohort.Site.Stripe.Enabled && Cohort.Site.Stripe.CaptureCardOnSignUp) { <fieldset> <legend>Payment Details <a href="//stripe.com" style="margin-left:7px"><img src="/Content/images/outline@2x.png" alt="Powered by Stripe" width="100" height="27"/></a> </legend> <div class="alert alert-info"> We won't charge your credit card unless you use your account in any given month. </div> <div class="control-group"> <label class="control-label" for="card-name">Your Name</label> <div class="controls"> <input id="card-name" placeholder="" class="input-xlarge" type="text"> <p class="help-block">As it appears on your credit card.</p> </div> </div> <div id="payment-errors"> </div> <div class="control-group"> <div class="controls"> <div class="cc default visa"></div> <div class="cc default mastercard"></div> <div class="cc default amex"></div> <div class="cc default discover"></div> </div> </div> <div class="control-group"> <label class="control-label" for="card-number">Card Number</label> <div class="controls"> <input id="card-number" placeholder="" class="input-xlarge" type="text"> <p class="help-block">Up to 16 digits on the front of your credit card.</p> </div> </div> <div class="control-group"> <label class="control-label">Expiration</label> <div class="controls"> <select id="card-expiry-month" class="stripe-sensitive required" required="required"> <option></option> </select> <span style="font-weight:bold;"> / </span> <select id="card-expiry-year" class="stripe-sensitive required" required="required"> <option></option> </select> </div> </div> <div class="control-group"> <label class="control-label" for="card-cvc">Verification Code</label> <div class="controls"> <input id="card-cvc" placeholder="" class="input-mini" type="text" size="2"> <p class="help-block">3 or 4 digits on the back of most cards.</p> <p class="help-block">On the front of AMEX cards.</p> </div> </div> <div class="control-group"> <label class="control-label"></label> <div class="controls"> <button id="submit-button" class="btn btn-success">Go!</button> </div> </div> </fieldset> } <input id="referer_url" name="referer_url" type="hidden" value="" /> <input id="landing_page" name="landing_page" type="hidden" value="" /> </form> @section Scripts { <script type="text/javascript"> $(function(){ var referer = $.cookie("cohort_referer_url"); $("input[id=referer_url]").val(referer); var landing = $.cookie("cohort_landing_page"); $("input[id=landing_page]").val(landing); }); </script> @if (Cohort.Site.Stripe.Enabled && Cohort.Site.Stripe.CaptureCardOnSignUp) { <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script> <script type="text/javascript" src="//js.stripe.com/v1/"></script> <script> if (Stripe === undefined) { alert("Couldn't load Stripe.com payment processing script. Perhaps your firewall is blocking it, or it might be unavailable right now."); } Stripe.setPublishableKey('@Cohort.Site.Stripe.PublishableKey'); </script> <script> jQuery.extend(jQuery.validator.messages, { required: 'This field is required.', email: 'Please enter a valid email address.', minlength: jQuery.validator.format('Please enter at least {0} characters.'), }); @*http://javascript.gakaa.com/credit-card-type-by-number.aspx*@ $("#card-number").keyup(function () { var cc = $(this).val(); if (cc.length >= 1) { var which; if ((/^(34|37)/).test(cc)) { which = '.amex'; } else if ((/^(51|52|53|54|55)/).test(cc)) { which = '.mastercard'; } else if ((/^(4)/).test(cc)) { which = '.visa'; } else if ((/^(6011)/).test(cc)) { which = '.discover'; } else if ((/^(300|301|302|303|304|305|36|38)/).test(cc)) { which = '.diners'; // NOT USED } else if ((/^(3)/).test(cc) && cc.length >= 2) { which = '.jcb'; // NOT USED } else if ((/^(2131|1800)/).test(cc)) { which = '.jcb'; // NOT USED } $('.cc').removeClass('default'); $('.cc').removeClass('selected'); $('.cc').addClass('deselected'); if (which) { $(which).removeClass('deselected'); $(which).addClass('selected'); @* if (which == '.cc_amex') { $('#cc_explain_amex').addClass('hilite_amex'); $('#cvc_card').addClass('cvc_amex'); } else { $('#cc_explain_amex').removeClass('hilite_amex'); $('#cvc_card').removeClass('cvc_amex'); }*@ } } else { $('.cc').removeClass('deselected'); $('.cc').removeClass('selected'); $('.cc').addClass('default'); @* $('#cc_explain_amex').removeClass('hilite_amex'); $('#cvc_card').removeClass('cvc_amex');*@ } }); function initExpiryFields() { $('#card-expiry-month, #card-expiry-year').css("width", ""); var select = $("#card-expiry-month"); var now = new Date(); var month = now.getMonth() + 1; for (var i = 1; i <= 12; i++) { var pad = (i <= 9) ? "0" + i : i; select.append($("<option value='" + pad + "' " + (month === i ? "selected" : "") + ">" + pad + "</option>")); } var year = now.getFullYear(); select = $("#card-expiry-year"); select.empty(); for (i = 0; i < 8; i++) { select.append($("<option value='" + (i + year) + "' " + (i === 0 ? "selected" : "") + ">" + (i + year) + "</option>")); } } function stripeResponseHandler(status, response) { if (response.error) { // show the errors on the form $(".payment-errors").text(response.error.message); $(".submit-button").removeAttr("disabled"); } else { var form$ = $("#payment-form"); // token contains id, last4, and card type var token = response['id']; // insert the token into the form so it gets submitted to the server form$.append("<input type='hidden' name='stripeToken' value='" + token + "'/>"); // and submit form$.get(0).submit(); } } $(function () { initExpiryFields(); $('#submit-button').click(function () { $('#payment-form').triggerHandler('submit'); }); $("#payment-form").submit(function (event) { // disable the submit button to prevent repeated clicks //$('#submit-button').attr("disabled", "disabled"); $('#submit-button').removeAttr("disabled"); Stripe.createToken({ name: $('#card-name').val(), number: $('#card-number').val(), cvc: $('#card-cvc').val(), exp_month: $('#card-expiry-month').val(), exp_year: $('#card-expiry-year').val() }, stripeResponseHandler); // prevent the form from submitting with the default action return false; }); $.validator.addMethod("cardNumber", Stripe.validateCardNumber, 'This does not appear to be a valid card number. Please try again and remember that this must match the digits on the front of your card exactly.'); $.validator.addMethod("cardCVC", Stripe.validateCVC, 'This does not appear to be a valid security code. We need this code to ensure that you have a valid credit card. If the diagram here does not help, please contact your credit card company for help finding the code.'); $.validator.addMethod("cardExpiry", function () { return Stripe.validateExpiry($("#card-expiry-month").val(), $("#card-expiry-year").val()); }, 'This does not appear to be a valid expiration date. The expiration must be a month/year in the future.'); $("#payment-form").validate({ //submitHandler: stripeOrGenerateSubmit, rules: { "email": { minlength: 5, required: true }, "card-cvc": { cardCVC: true, required: true }, "card-number": { cardNumber: true, required: true }, "card-expiry-year": "cardExpiry" // we don't validate month separately }, errorPlacement: function (error, element) { //var sibling1 = element.parent().next(); //sibling1.addClass('backArrow'); //var sibling2 = sibling1.next(); //error.appendTo(sibling2); error.appendTo("#payment-errors"); }, success: function (element) { //var prev = element.parent().prev(); //prev.removeClass('backArrow'); } }); }); </script> } }
the_stack
@model HomePageModel @{ var additionalClasses = ""; if (Model.HideDetails) { additionalClasses = "initially-hidden"; } } <div class="container-fluid tagline"> @if (!string.IsNullOrEmpty(Model.CustomDescription)) { <div style="white-space:pre-wrap">@Model.CustomDescription</div> } else { @:SAML2 stub: be whoever you want to be } </div> @if (Request.Url.Host == "stubidp.kentor.se") { <div class="container"> <div class="col-md-12"> <div class="panel panel-warning"> <div class="panel-heading"> Service moved to <a href="https://stubidp.sustainsys.com">https://stubidp.sustainsys.com</a> </div> <div class="panel-body"> This service has moved to <a href="https://stubidp.sustainsys.com">https://stubidp.sustainsys.com</a>. The stubidp.kentor.se host name will be removed, please update your configuration. All custom tenant information is the same accross the domain names. </div> </div> </div> </div> } @if (Request.Url.Host == "stubidp.sustainsys.com" && Request.Url.Scheme == "http") { <div class="container"> <div class="col-md-12"> <div class="panel panel-info"> <div class="panel-heading"> Consider using <a href="https://stubidp.sustainsys.com">https://stubidp.sustainsys.com</a> instead </div> <div class="panel-body"> You are currently accessing this service unencrypted. Consider changing to use the https version instead. </div> </div> </div> </div> } <div class="container"> <div class="col-lg-8 card"> <h2>Send SAML2 Response</h2> <div class="contents"> <p> This form will send a SAML2 Response to a service provider. If the In Response To ID field is empty, the Response is considered unsolicited (IDP initiated). </p> <p> The pre-filled values in the user selection box are just an example. If you want to build your own user list you can @Html.ActionLink("create your own IDP tenant", "Index", "Manage", new { idpId = Guid.NewGuid() }, null). </p> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = additionalClasses })) { @Html.HiddenFor(m => m.CustomDescription) @*Preserve value on post-redisplay*@ <div id="user-dropdown-placeholder" class="form-group row" style="display:none"> <label for="userList" class="col-form-label col-sm-4">Use pre-filled values</label> <div class="col-md-8"> <select id="userList"></select> </div> <div class="col-md-8" id="userDescription">&nbsp;</div> </div> if (Model.AssertionModel.AuthnRequestXml != null) { <div class="hide-details form-group row"> <label class="col-form-label col-md-4">@Html.DisplayNameFor(m => m.AssertionModel.AuthnRequestXml)</label> <div class="col-md-8"> <pre class="xml">@Model.AssertionModel.AuthnRequestXml</pre> </div> </div> } <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.InResponseTo, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.InResponseTo, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.InResponseTo) </div> </div> <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.AssertionConsumerServiceUrl, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.AssertionConsumerServiceUrl, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.AssertionConsumerServiceUrl) </div> </div> <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.Audience, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.Audience, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.Audience) </div> </div> <div class="hide-details form-group row"> <label class="col-form-label col-md-4">Send response via</label> <div class="radio-group col-md-8"> <label for="binding_post"> <input type="radio" name="AssertionModel.ResponseBinding" id="binding_post" checked="@(Model.AssertionModel.ResponseBinding == Sustainsys.Saml2.WebSso.Saml2BindingType.HttpPost)" value="HttpPost" /> Http POST Binding </label> <label for="binding_artifact"> <input type="radio" name="AssertionModel.ResponseBinding" id="binding_artifact" checked="@(Model.AssertionModel.ResponseBinding == Sustainsys.Saml2.WebSso.Saml2BindingType.Artifact)" value="Artifact" /> Artifact Binding over Http Redirect </label> </div> </div> <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.RelayState, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.RelayState, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.RelayState) </div> </div> <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.NameId, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.NameId, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.NameId) </div> </div> <div class="hide-details form-group row"> @Html.LabelFor(m => m.AssertionModel.SessionIndex, new { @class = "col-form-label col-md-4" }) <div class="col-md-8"> @Html.TextBoxFor(m => m.AssertionModel.SessionIndex, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.AssertionModel.SessionIndex) </div> </div> <div class="hide-details panel panel-default"> <div class="panel-heading">Attribute Statements</div> <div class="panel-body"> <div id="attributes-placeholder" class="row" style="display:none"> <label class="col-md-5 hidden-sm hidden-xs">Type</label> <label class="col-md-5 hidden-sm hidden-xs">Value</label> </div> <button class="btn glyphicon glyphicon-plus" id="add-attribute"></button> </div> </div> <p></p> <button class="btn btn-primary" id="submit">Log in</button> <button class="show-details btn btn-secondary">Show Details</button> } </div> </div> @Html.Partial("_About") </div> <script id="attributeRowTemplate" type="text/html"> @* Mustache.js template for each attribute row *@ @*Array model binding using Index property, see http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/*@ <div class="attribute-row form-group"> <input type="hidden" name="AssertionModel.AttributeStatements.Index" value="{{rowIndex}}" /> <div class="col-md-5"> <label class="hidden-md hidden-lg col-form-label">Type</label> <input class="form-control" type="text" data-val="true" data-val-required="The Type field is required." name="AssertionModel.AttributeStatements[{{rowIndex}}].Type" value="{{type}}" /> </div> <div class="col-md-5"> <label class="hidden-md hidden-lg col-form-label">Value</label> <input class="pull-right form-control" type="text" data-val="true" data-val-required="The Value field is required." name="AssertionModel.AttributeStatements[{{rowIndex}}].Value" value="{{value}}" /> </div> <div class="col-md-1 col-xs-1"> <button class="btn remove-attribute glyphicon glyphicon-trash"></button> </div> <div class="col-xs-11 col-md-12"> <span class="col-md-5 field-validation-valid" data-valmsg-for="AssertionModel.AttributeStatements[{{rowIndex}}].Type" data-valmsg-replace="true"></span> <span class="col-md-5 field-validation-valid" data-valmsg-for="AssertionModel.AttributeStatements[{{rowIndex}}].Value" data-valmsg-replace="true"></span> </div> </div> </script> @* Mustache.js template for a user item display in the select2 list *@ <script id="userListTemplate" type="text/html"> <div> {{DisplayName}} <br /> <em> {{Description}} </em> </div> </script>
the_stack
// This C# script can be executed using the csi // tool found in Tools\net46\roslyn\tools. // // It produces an IL file (on stdout) containing tests // for all possible integral ldind/conv combinations. using System; using System.Collections.Generic; using System.IO; class ILType { public static readonly ILType I1 = new ILType(byteSize: 1, unsigned: false, min: 0xFFFF_FFFF_FFFF_FF80, max: 0x7F); public static readonly ILType U1 = new ILType(byteSize: 1, unsigned: true, min: 0, max: 0xFF); public static readonly ILType I2 = new ILType(byteSize: 2, unsigned: false, min: 0xFFFF_FFFF_FFFF_8000, max: 0x7FFF); public static readonly ILType U2 = new ILType(byteSize: 2, unsigned: true, min: 0, max: 0xFFFF); public static readonly ILType I4 = new ILType(byteSize: 4, unsigned: false, min: 0xFFFF_FFFF_8000_0000, max: 0x7FFF_FFFF); public static readonly ILType U4 = new ILType(byteSize: 4, unsigned: true, min: 0, max: 0xFFFF_FFFF); public static readonly ILType I8 = new ILType(byteSize: 8, unsigned: false, min: 0x8000_0000_0000_0000, max: 0x7FFF_FFFF_FFFF_FFFF); public static readonly ILType U8 = new ILType(byteSize: 8, unsigned: true, min: 0, max: 0xFFFF_FFFF_FFFF_FFFF); public static readonly IEnumerable<ILType> Types = new[] { I1, U1, I2, U2, I4, U4, I8, U8 }; public readonly int ByteSize; public readonly bool IsUnsigned; public readonly ulong Min; public readonly ulong Max; ILType(int byteSize, bool unsigned, ulong min, ulong max) { ByteSize = byteSize; IsUnsigned = unsigned; Min = min; Max = max; } public int BitSize => ByteSize * 8; public bool IsSigned => !IsUnsigned; public bool IsSmall => ByteSize < 4; public bool IsSmallUnsigned => IsSmall && IsUnsigned; public bool IsSmallSigned => IsSmall && IsSigned; public string Name => $"{(IsUnsigned ? "u" : "")}int{BitSize}"; public string ShortName => $"{(IsUnsigned ? "u" : "i")}{ByteSize}"; public ILType ActualType => ByteSize <= 4 ? I4 : I8; public ILType UnsignedType { get { switch (ByteSize) { case 1: return U1; case 2: return U2; case 4: return U4; case 8: return U8; default: throw new Exception(); } } } public ILType SignedType { get { switch (ByteSize) { case 1: return I1; case 2: return I2; case 4: return I4; case 8: return I8; default: throw new Exception(); } } } public ulong AllOnes => UnsignedType.Max; public string ILConst(ulong value) => $"ldc.i{ActualType.ByteSize} {Hex(value)}"; public string Hex(ulong value) { string hex = value.ToString("X16"); if (hex.Length > ByteSize * 2) { hex = hex.Substring(hex.Length - ByteSize * 2); } return "0x" + hex; } } class ILConv { public static IEnumerable<ILConv> Conversions { get { foreach (ILType type in ILType.Types) { yield return new ILConv(type, false, false); yield return new ILConv(type, true, false); yield return new ILConv(type, true, true); } } } public readonly ILType Type; public readonly bool Ovf; public readonly bool Un; ILConv(ILType type, bool overflow, bool unsigned) { Type = type; Ovf = overflow; Un = unsigned; } public string IL => $"conv.{(Ovf ? "ovf." : "")}{Type.ShortName}{(Ovf & Un ? ".un" : "")}"; static ulong SignExtend(ulong value, ILType valueType) { if ((value & valueType.Min) != 0) value |= ~valueType.AllOnes; return value; } static ulong ZeroExtend(ulong value, ILType valueType) { return value & valueType.AllOnes; } static ulong Widen(ulong value, ILType valueType) { return valueType.IsSigned ? SignExtend(value, valueType) : ZeroExtend(value, valueType); } public ulong? Eval(ulong value, ILType valueType) { valueType = valueType.ActualType; if (Ovf) { if (Un) { valueType = valueType.UnsignedType; } value = Widen(value, valueType); if (valueType.IsSigned) { if ((long)value < (long)Type.Min) return null; } if (Type.IsUnsigned) { if (value > Type.Max) return null; } else { if (valueType.IsSigned) { if ((long)value > (long)Type.Max) return null; } else { if (value > Type.Max) return null; } } } if (Type.ByteSize <= 4) { value &= Type.AllOnes; if (Type.IsSmallSigned) { value = SignExtend(value, Type); } } else { value &= valueType.AllOnes; if (valueType == ILType.I4 && Type == ILType.I8) { if ((value & valueType.Min) != 0) { value |= ~valueType.AllOnes; } } } return value; } } class ILLdInd { public readonly ILType Type; public ILLdInd(ILType type) { Type = type; } public ulong Eval(ulong bits) { bits &= Type.AllOnes; if (Type.IsSmallSigned && ((bits & Type.Min) != 0)) { bits |= ~Type.AllOnes; } return bits; } public string IL => $"ldind.{Type.ShortName}"; } class ILStInd { public readonly ILType Type; public ILStInd(ILType type) { Type = type; } public string IL => $"stind.{Type.ShortName}"; } class Test { public readonly ILLdInd Load; public readonly ILConv Conv; public readonly ILStInd Store; public string Name => $"{Load.IL}_{Conv.IL}".Replace('.', '_'); public Test(ILLdInd load, ILConv conv) { Load = load; Conv = conv; Store = new ILStInd(conv.Type.ActualType); } public void WriteConvMethod(TextWriter writer) { writer.WriteLine(); writer.WriteLine($" .method private hidebysig static void Test_{Name}({Load.Type.Name}& src, {Store.Type.Name}& dst) cil managed noinlining"); writer.WriteLine($" {{"); writer.WriteLine($" .maxstack 4"); writer.WriteLine($" ldarg.1"); writer.WriteLine($" ldarg.0"); writer.WriteLine($" {Load.IL}"); writer.WriteLine($" {Conv.IL}"); writer.WriteLine($" {Store.IL}"); writer.WriteLine($" ret"); writer.WriteLine($" }}"); } public void WriteCheckMethod(TextWriter writer) { writer.WriteLine(); writer.WriteLine($" .method private hidebysig static int32 Check_{Name}({Load.Type.ActualType.Name} input, {Store.Type.Name} expected, class [System.Private.CoreLib]System.String desc) cil managed noinlining"); writer.WriteLine($" {{"); writer.WriteLine($" .maxstack 4"); writer.WriteLine($" .locals init({Load.Type.Name} src, {Store.Type.Name} dst)"); writer.WriteLine($" ldarg.2"); writer.WriteLine($" call void Program::print(class [System.Private.CoreLib]System.String)"); writer.WriteLine($" ldarg.0"); writer.WriteLine($" stloc 0"); writer.WriteLine($" ldloca 0"); writer.WriteLine($" ldloca 1"); writer.WriteLine($" call void Program::Test_{Name}({Load.Type.Name}&, {Store.Type.Name}&)"); writer.WriteLine($" ldloc.1"); writer.WriteLine($" ldarg.1"); writer.WriteLine($" ceq"); writer.WriteLine($" ret"); writer.WriteLine($" }}"); } public void WriteCheckOverflowMethod(TextWriter writer) { writer.WriteLine(); writer.WriteLine($" .method private hidebysig static int32 CheckOvf_{Name}({Load.Type.ActualType.Name} input, class [System.Private.CoreLib]System.String desc) cil managed noinlining"); writer.WriteLine($" {{"); writer.WriteLine($" .maxstack 4"); writer.WriteLine($" .locals init({Load.Type.Name} src, {Store.Type.Name} dst, int32 ovf)"); writer.WriteLine($" ldarg.1"); writer.WriteLine($" call void Program::print(class [System.Private.CoreLib]System.String)"); writer.WriteLine($" ldarg.0"); writer.WriteLine($" stloc 0"); writer.WriteLine($" .try {{"); writer.WriteLine($" ldloca 0"); writer.WriteLine($" ldloca 1"); writer.WriteLine($" call void Program::Test_{Name}({Load.Type.Name}&, {Store.Type.Name}&)"); writer.WriteLine($" leave END"); writer.WriteLine($" }} catch [System.Private.CoreLib]System.OverflowException {{"); writer.WriteLine($" ldc.i4 1"); writer.WriteLine($" stloc 2"); writer.WriteLine($" leave END"); writer.WriteLine($" }}"); writer.WriteLine($" END: ldloc.2"); writer.WriteLine($" ret"); writer.WriteLine($" }}"); } public ulong? Eval(ulong value) => Conv.Eval(Load.Eval(value), Load.Type); } class TestInput { public readonly ulong Input; public readonly ulong? Expected; public TestInput(Test test, ulong input) { Input = input; Expected = test.Eval(input); } } const string FileBeginIL = @"// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. .assembly extern System.Private.CoreLib { auto } .assembly test { } .class auto Program extends [System.Private.CoreLib]System.Object { .method private static void print(class [System.Private.CoreLib]System.String) cil managed { .maxstack 1 ldarg 0 call void [System.Private.CoreLib]Internal.Console::WriteLine(class [System.Private.CoreLib]System.String) ret }"; const string MainMethodBeginIL = @" .method private hidebysig static int32 Main() cil managed { .entrypoint .maxstack 8"; const string MainMethodEndIL = @" ldc.i4 100 ret FAIL: ldstr ""FAILED"" call void Program::print(class [System.Private.CoreLib]System.String) ldc.i4 1 ret }"; IEnumerable<Test> GenerateTests() { var tests = new List<Test>(); foreach (ILType loadType in ILType.Types) { foreach (ILConv conv in ILConv.Conversions) { tests.Add(new Test(new ILLdInd(loadType), conv)); } } return tests; } IEnumerable<TestInput> GenerateTestInputs(Test test) { var inputs = new List<TestInput>(); inputs.Add(new TestInput(test, test.Load.Type.Max)); if (test.Load.Type.IsSigned) { inputs.Add(new TestInput(test, test.Load.Type.Min)); inputs.Add(new TestInput(test, test.Load.Type.AllOnes)); } if (test.Conv.Type.ByteSize < test.Load.Type.ByteSize) { inputs.Add(new TestInput(test, test.Conv.Type.Max)); if (test.Conv.Type.IsSigned) { inputs.Add(new TestInput(test, test.Conv.Type.Min)); inputs.Add(new TestInput(test, test.Conv.Type.AllOnes)); } } return inputs; } void WriteMainMethod(TextWriter write, IEnumerable<Test> tests) { writer.WriteLine(MainMethodBeginIL); foreach (Test t in tests) { foreach (TestInput i in GenerateTestInputs(t)) { writer.WriteLine(); writer.WriteLine($" {t.Load.Type.ActualType.ILConst(i.Input)}"); if (i.Expected == null) { writer.WriteLine($" ldstr \"Checking {t.Name}({t.Load.Type.Hex(i.Input)}) == OverflowException\""); writer.WriteLine($" call int32 Program::CheckOvf_{t.Name}({t.Load.Type.ActualType.Name}, class [System.Private.CoreLib]System.String)"); } else { writer.WriteLine($" {t.Store.Type.ILConst(i.Expected.Value)}"); writer.WriteLine($" ldstr \"Checking {t.Name}({t.Load.Type.Hex(i.Input)}) == {t.Store.Type.Hex(i.Expected.Value)}\""); writer.WriteLine($" call int32 Program::Check_{t.Name}({t.Load.Type.ActualType.Name}, {t.Store.Type.Name}, class [System.Private.CoreLib]System.String)"); } writer.WriteLine($" brfalse FAIL"); } } writer.WriteLine(MainMethodEndIL); } void WriteTestMethods(TextWriter writer, IEnumerable<Test> tests) { foreach (Test t in tests) { t.WriteConvMethod(writer); t.WriteCheckMethod(writer); if (t.Conv.Ovf) { t.WriteCheckOverflowMethod(writer); } } } var tests = GenerateTests(); var writer = Console.Out; writer.WriteLine(FileBeginIL); WriteMainMethod(writer, tests); WriteTestMethods(writer, tests); writer.WriteLine("}");
the_stack
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>PhaAccounts</title> @*Easyui需要引入的文件*@ <script type="text/javascript" src="~/Content/jquery-easyui-1.4.5/jquery.min.js"></script> <script type="text/javascript" src="~/Content/jquery-easyui-1.4.5/jquery.easyui.min.js"></script> <link href="~/Content/jquery-easyui-1.4.5/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/jquery-easyui-1.4.5/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery.validate.min.js"></script> <script type="text/javascript" src="~/Content/Site.js"></script> <script type="text/javascript"> $(function () { //初始化datagrid InitGrid(); InitControl(); InitDialog(); InitOriSelectDialog(); InitOriDialoggrid(); InitPhaSelectDialog(); InitPhaDialoggrid(); $('#btnReload').click(function () { $("#grid").datagrid("reload"); }); //ajax提交修改表单 $('#ok').click(function () { $('#errdiv').removeClass('dis'); $('#form').submit(); }); $('#cancel').click(function () { $('#dd').dialog('close'); }); $('#add').click(function () { $('#errdiv').attr('class', 'dis'); $('#form')[0].reset(); $('#key').val(0); $('#editpha').removeAttr("disabled"); $('#editori').removeAttr("disabled"); $('#dd').dialog('open'); }); $('#editori').click(function () { $('#oriselect').dialog('open'); }); $('#editpha').click(function () { $('#phaselect').dialog('open'); }); $('#del').click(function () { getAjax("../PHA_Accounts/Del", { phaCode: $('#del_pha').val(), orginID: $('#del_ori').val() }, function (data) { if ($('#del_ori').val() == null || $('#del_pha').val() == "") return false; if (data) { $.messager.alert('提示', '操作成功!'); $('#dd').dialog('close'); $("#grid").datagrid("reload"); return true; } else { $.messager.alert('提示', '操作失败!'); return false; } }); }); }); //实现对DataGird控件的绑定操作 function InitGrid() { $('#grid').datagrid({ url: '../PHA_Accounts/LoadList', singleSelect: true, fit: true, nowrap: true,//单行显示 autoRowHeight: false, striped: false, //斑马纹 collapsible: true, //可折叠 pagination: true, pageSize: 20, fitColumns: false, //自适应列宽 rownumbers: true, sortName: 'PhaCode', //根据某个字段给easyUI排序 sortOrder: 'asc', remoteSort: true, loadMsg: '加载中,请等待', queryParams: ({ pinyin: $('#itemid').val() }), //异步查询的参数 columns: [[ { title: '药品编号', field: 'PhaCode', hidden: true }, { title: '药品名称', field: 'PhaName', width: 120, sortable: true }, { title: '规格', field: 'Spec', width: 80, sortable: true }, { title: '单位', field: 'Unit', width: 60, sortable: true, align: 'center' }, { title: '拼音代码', field: 'PinyinCode', width: 70, sortable: true, align: 'center' }, { title: '产地', field: 'OrginName', width: 100, sortable: true, align: 'center' }, { title: '库存', field: 'Stock', width: 80, sortable: true, align: 'center' }, { title: '进货价格', field: 'InWarehousePrice', width: 80, sortable: true, align: 'center' }, { title: '批发价格', field: 'WholesalePrice', width: 80, sortable: true, align: 'center' }, { title: '零售价格', field: 'RetailPrice', width: 90, sortable: true, align: 'center' }, { title: '进货金额', field: 'InWarehouseSum', width: 80, sortable: true, align: 'center' }, { title: '批发金额', field: 'WholesaleSum', width: 90, sortable: true, align: 'center' }, { title: '零售金额', field: 'RetailSum', width: 90, sortable: true, align: 'center' }, { title: '供货单位', field: 'CompanyName', width: 160, sortable: true }, ]], toolbar: '#tb', onDblClickRow: function (rowIndex, rowData) { $('#editpha').attr('disabled', 'disabled'); $('#editori').attr('disabled', 'disabled'); //$('#errdiv').attr('class', 'dis'); getAjax("../PHA_Accounts/LoadForm", { phaCode: rowData['PhaCode'], orginID: rowData['OrginID'] }, function (data) { var data = eval("(" + data + ")"); SetWebControls(data); $('#key').val(1); }); $('#dd').window('open'); }, onClickRow: function (index, row) { $('#del_pha').val(row['PhaCode']); $('#del_ori').val(row['OrginID']); } }) var p = $('#grid').datagrid('getPager'); $(p).pagination({ pageSize: 20, pageList: [10, 12, 20, 40, 60, 100, 200], beforePageText: '第', afterPageText: '页 共 {pages} 页', displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录', }); }; function InitDialog() { $('#dd').dialog({ title: '修改信息', width: 740, height: 220, top: ($(window).height() - 220) * 0.5, //居中 left: ($(window).width() - 740) * 0.5, closed: true, cache: false, modal: true, buttons: '#dlg-buttons' }); } //产地选择器 function InitOriDialoggrid() { $('#origrid').datagrid({ url: '../PHA_Orgin/LoadList', height: 410, nowrap: true,//单行显示 autoRowHeight: false, striped: false, //斑马纹 collapsible: true, //可折叠 singleSelect: true, pagination: true, sortName: 'OrginID', //根据某个字段给easyUI排序 sortOrder: 'asc', pageSize: 20, fitColumns: true, //自适应列宽 rownumbers: true, toolbar: '#origrid_tb', queryParams: ({ query: $('#origrid_dir').val() }), columns: [[ { title: '编号', field: 'OrginID', hidden: true }, { title: '产地', field: 'OrginName' }, { title: '拼音代码', field: 'PinyinCode' }, { title: '生产厂家', field: 'Manufacturer' }, ]], onDblClickRow: function (rowIndex, rowData) { $('#OrginName').val(rowData['OrginName']); $('#OrginID').val(rowData['OrginID']); $('#oriselect').dialog('close'); } }); var p = $('#origrid').datagrid('getPager'); $(p).pagination({ pageSize: 20, pageList: [10, 12, 20, 40, 60, 100, 200], beforePageText: '第', afterPageText: '页 共 {pages} 页', displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录', }); } function InitOriSelectDialog() { $('#oriselect').dialog({ title: '选择产地', width: 400, height: 450, top: ($(window).height() - 450) * 0.5, //居中 left: ($(window).width() - 400) * 0.5, closed: true, cache: false, modal: true, }); } //药品选择器 function InitPhaDialoggrid() { $('#phagrid').datagrid({ url: '../DrugManagement/LoadList', height: 410, nowrap: true,//单行显示 autoRowHeight: false, singleSelect: true, striped: false, //斑马纹 collapsible: true, //可折叠 pagination: true, pageSize: 20, fitColumns: true, //自适应列宽 rownumbers: true, sortName: 'PhaCode', //根据某个字段给easyUI排序 sortOrder: 'asc', remoteSort: true, loadMsg: '加载中,请等待', queryParams: ({ query: $('#phagrid_dir').val() }), //异步查询的参数 columns: [[ { title: '药品编号', field: 'PhaCode', hidden: true }, { title: '药品名称', field: 'PhaName', width: 120, sortable: true }, { title: '药品规格', field: 'Spec', width: 80, sortable: true }, { title: '药品单位', field: 'Unit', width: 60, sortable: true, align: 'center' }, { title: '拼音码', field: 'PinyinCode', width: 90 } ]], toolbar: '#phagrid_tb', onDblClickRow: function (rowIndex, rowData) { $('#PhaCode').val(rowData['PhaCode']); $('#PhaName').val(rowData['PhaName']); $('#Spec').val(rowData['Spec']); $('#Unit').val(rowData['Unit']); $('#PinyinCode').val(rowData['PinyinCode']); $('#phaselect').dialog('close'); } }) var p = $('#phagrid').datagrid('getPager'); $(p).pagination({ pageSize: 20, pageList: [10, 12, 20, 40, 60, 100, 200], beforePageText: '第', afterPageText: '页 共 {pages} 页', displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录', }); }; function InitPhaSelectDialog() { $('#phaselect').dialog({ title: '选择药品', width: 500, height: 450, top: ($(window).height() - 450) * 0.5, //居中 left: ($(window).width() - 500) * 0.5, closed: true, cache: false, modal: true, }); } //绑定供货单位下拉框 function InitControl() { var dataJson = ""; getAjax("/PHA_Accounts/LoadSelectComPany", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#CompanyID").append($("<option></option>").val(datajson[i].CompanyID).html(datajson[i].CompanyName)); }); }) } </script> <script> //表单验证和提交 $(function () { $('#form').validate({ rules: { PhaCode: { required: true }, OrginName: { required: true }, Stock: { required: true }, CompanyID: { required: true }, InWarehousePrice: { required: true }, RetailPrice: { required: true }, WholesalePrice: { required: true } }, messages: { PhaCode: "药品序号不能为空!", OrginName: "药品产地不能为空!", Stock: "库存不能为空!", CompanyID: "进货单位不能为空!", InWarehousePrice: "入库价格不能为空!", RetailPrice: "零售价格不能为空!", WholesalePrice: "批发价格不能为空!" }, errorLabelContainer: '#errdiv>ul', wrapper: 'li', submitHandler: function (form) { var postData = GetWebControls("#form"); getAjax("/PHA_Accounts/AcceptClick?key=" + $('#key').val(), postData, function (data) { if (data) { //此处可以优化,提示消息可更美观。 $.messager.alert('提示', '操作成功!'); $('#dd').dialog('close'); $("#grid").datagrid("reload"); return true; } else if (data == -1) { $.messager.alert('提示', '已存在该记录或单号重复,请重新填写!'); return false; } else { $.messager.alert('提示', '操作失败!'); return false; } }); }, invalidHandler: function (form, validator) { //不通过回调 return false; } }); }); </script> <style> .dis { display: none; } fieldset { border-color: #E0ECFF; } .tb-line { margin-bottom: 5px; } .tb-col-200 { width: 200px; } .tb-col-160 { width: 160px; } .tb-col-140 { width: 140px; } .tb-col-120 { width: 120px; } .tb-col-80 { width: 80px; } .tb-col-40 { width: 40px; } </style> </head> <body style="margin:2px;padding:0"> <div> <div style="position:fixed;width:100%;height:100%"> <table id="grid"></table> </div> <input id="del_pha" type="hidden" name="del_pha" value="" /> <input id="del_ori" type="hidden" name="del_ori" value="" /> <div id="tb" style="padding:3px"> <a id="add" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a> <a id="del" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-remove'">删除</a> <a id="btnReload" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-reload'">刷新</a> <span>拼音码:</span> <input id="itemid" style="border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" plain="true" onclick="InitGrid()">查找</a> </div> </div> <div id="dd" class="easyui-dialog" style="position:relative"> <form id="form" name="form" method="post"> <input id="key" type="hidden" value="" /> <div style="margin:10px"> <div class="tb-line"> <span>药品编码:</span><input type="text" id="PhaCode" class="tb-col-120" name="PhaCode" value="" disabled="disabled" /> <input type="button" id="editpha" value="改" /> <span>药品名:</span><input type="text" id="PhaName" class="tb-col-160" name="PhaName" value="" disabled="disabled" /> <span>规格:</span><input type="text" id="Spec" name="Spec" class="tb-col-80" value="" disabled="disabled" /> <span>单位:</span><input type="text" id="Unit" name="Unit" class="tb-col-40" value="" disabled="disabled" /> </div> <div class="tb-line"> <span>拼音:</span><input type="text" id="PinyinCode" name="PinyinCode" class="tb-col-80" value="" disabled="disabled" /> <span>产地:</span><input type="text" id="OrginName" name="OrginName" class="tb-col-120" value="" disabled="disabled" /> <input type="hidden" id="OrginID" /> <input type="button" id="editori" value="改" /> <span>库存:</span><input type="text" id="Stock" name="Stock" class="tb-col-40" value="" /> <span>供货单位:</span><select id="CompanyID" name="CompanyID" class="tb-col-200"></select> </div> <div class="tb-line"> <span>进货价格:</span><input type="text" id="InWarehousePrice" name="InWarehousePrice" class="tb-col-120" value="" /> <span>批发价格:</span><input type="text" id="WholesalePrice" name="WholesalePrice" class="tb-col-120" value="" /> <span>零售价格:</span><input type="text" id="RetailPrice" name="RetailPrice" class="tb-col-120" value="" /> </div> <div class="tb-line"> <span>进货金额:</span><input type="text" id="InWarehouseSum" name="InWarehouseSum" class="tb-col-120" value="" disabled="disabled" /> <span>批发金额:</span><input type="text" id="WholesaleSum" name="WholesaleSum" class="tb-col-120" value="" disabled="disabled" /> <span>零售金额:</span><input type="text" id="RetailSum" name="RetailSum" class="tb-col-120" value="" disabled="disabled" /> </div> </div> <div class="errdiv" id="errdiv"> <ul></ul> </div> <div id="dlg-buttons"> <a id="ok" href="#" class="easyui-linkbutton" iconcls="icon-ok">确定</a> <a id="cancel" href="#" class="easyui-linkbutton" iconcls="icon-cancel">取消</a> </div> </form> </div> <div id="oriselect" class="easyui-dialog" style="position:relative"> <table id="origrid"></table> <div id="origrid_tb" style="padding:3px"> <span>拼音码:</span> <input id="origrid_dir" style="border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" plain="true" onclick="InitOriDialoggrid()">查找</a> </div> </div> <div id="phaselect" class="easyui-dialog" style="position:relative"> <table id="phagrid"></table> <div id="phagrid_tb" style="padding:3px"> <span>拼音码:</span> <input id="phagrid_dir" style="border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" plain="true" onclick="InitPhaDialoggrid()">查找</a> </div> </div> </body> </html>
the_stack
using System.Text.RegularExpressions; private void WriteImportOfVersionInfoToMsBuildFile() { WriteToMsBuildXml("./src/directory.build.props", root => { root.AddFirst( new XElement("Import", new XAttribute("Project", "$(MSBuildThisFileDirectory)versioninfo.props"), new XAttribute("Condition", "exists('$(MSBuildThisFileDirectory)versioninfo.props')"))); }); } private void WriteToMsBuildXml(FilePath file, Action<XElement> add) { XElement root; if (!FileExists(file)) { Information("File not found, creating new"); root = new XElement(ns + "Project"); } else { Information("Using existing file"); root = XElement.Load(file.FullPath); } add(root); root.Save(file.FullPath, SaveOptions.None); } private FilePath GetVersionInfoFile() { return File("./src/versioninfo.props"); } private void WriteVersionInformationToMsBuildFile(GitVersion version, FilePath changelogFile) { var log = ChangeLog.Parse(changelogFile.FullPath); var releaseNotes = log?.GetVersion(version.MajorMinorPatch)?.Body; // Ignore if version is prerelease if (string.IsNullOrEmpty(releaseNotes)) { if (string.IsNullOrEmpty(version.PreReleaseTag)) { throw new Exception($"Release notes for version {version.MajorMinorPatch} is missing"); } Warning($"Missing release notes for version {version.MajorMinorPatch} but ignoring it because this is a prelease version"); } var file = GetVersionInfoFile(); WriteToMsBuildXml(file, root => { Information($"Writing version information [{version.NuGetVersionV2}] to {file}"); root.Descendants(ns+"PropertyGroup").Remove(); var pg = new XElement(ns + "PropertyGroup"); pg.Add(new XElement(ns + "Version", version.AssemblySemFileVer)); pg.Add(new XElement(ns + "FileVersion", version.AssemblySemFileVer)); pg.Add(new XElement(ns + "AssemblyVersion", version.AssemblySemVer)); pg.Add(new XElement(ns + "InformationalVersion", version.InformationalVersion)); pg.Add(new XElement(ns + "PackageReleaseNotes", releaseNotes)); root.Add(pg); }); } private class ChangeLog { // patterns private static Regex semver = new Regex(@"## ?\[?v?([\w\d.-]+\.[\w\d.-]+[a-zA-Z0-9])?"); private static Regex date = new Regex(@".*[ ](\d\d?\d?\d[-/.]\d\d?[-/.]\d\d?\d?\d?).*"); private static string EOL = Environment.NewLine; public string Title {get;set;} public string Description {get;set;} public List<VersionInfo> Versions {get;} = new List<VersionInfo>(); public VersionInfo GetVersion(string version) { return Versions.FirstOrDefault(ver => version.Equals(ver.Version)); } public override string ToString() { var str = $"Title: {Title}\nDescription: {Description}\nVersions:\n"; foreach (var ver in Versions) { str += ver.ToString() + "\n"; } return str; } public static ChangeLog Parse(string filename) { var input = System.IO.File.ReadAllLines(filename); return Parse(input); } public static ChangeLog Parse(IEnumerable<string> lines) { var log = new ChangeLog(); VersionInfo current = null; string activeSubhead = null; foreach (var line in lines) { log.HandleLine(line, ref current, ref activeSubhead); } // push last version into log log.AddVersion(current); // clean up description log.Description = Clean(log.Description); if (log.Description == string.Empty) { log.Description = null; } return log; } private void HandleLine(string line, ref VersionInfo current, ref string activeSubhead) { // skip line if it's a link label if (Regex.IsMatch(line, @"^\[[^[\]]*\] *?:")) { return; } // set title if it's there if (Title == null && Regex.IsMatch(line, "^# ?[^#]")) { Title = line.Substring(1).Trim(); return; } // new version found! if (Regex.IsMatch(line, "^## ?[^#]")) { if (current?.Title != null) { AddVersion(current); } current = new VersionInfo(); activeSubhead = null; var match = semver.Match(line); if (match.Success) { current.Version = match.Groups[1].Value; } current.Title = line.Substring(2).Trim(); match = date.Match(current.Title); if (current.Title != null && match.Success) { current.Date = match.Groups[1].Value; } return; } // deal with body or description content if (current != null) { current.HandleLine(line, ref activeSubhead); } else { Description = (Description ?? string.Empty) + line + EOL; } } private void AddVersion(VersionInfo current) { if (current != null) { current.Body = Clean(current.Body); Versions.Add(current); } } private static string Clean(string str) { if (str == null) { return string.Empty; } str = str.Trim(); str = Regex.Replace(str, "^[" + EOL + "]*", string.Empty); str = Regex.Replace(str, "[" + EOL + "]*$", string.Empty); return str; } } private class VersionInfo { // patterns private static Regex subhead = new Regex("^###"); private static Regex listitem = new Regex("^[*-]"); public string Version {get;set;} public string Title {get;set;} public string Date {get;set;} public string Body {get;set;} = string.Empty; public Dictionary<string, List<string>> Parsed {get;} = new Dictionary<string, List<string>> { { "_", new List<string>() } }; public override string ToString() { var str = $" Version: {Version}\n Title: {Title}\n Date: {Date}\n Body: {Body}\n"; foreach (var key in Parsed.Keys) { str += $" {key}:\n"; foreach (var line in Parsed[key]) { str += $" {line}\n"; } } return str; } public void HandleLine(string line, ref string activeSubhead) { Body += line + "\n"; // handle case where current line is a 'subhead': // - 'handleize' subhead. // - add subhead to 'parsed' data if not already present. var match = subhead.Match(line); if (match.Success) { var key = line.Replace("###", string.Empty).Trim(); if (!Parsed.ContainsKey(key)) { Parsed[key] = new List<string>(); activeSubhead = key; } } // handle case where current line is a 'list item': match = listitem.Match(line); if (match.Success) { line = RemoveMarkdown(line); // add line to 'catch all' array Parsed["_"].Add(line); // add line to 'active subhead' if applicable (eg. 'Added', 'Changed', etc.) if (activeSubhead != null) { Parsed[activeSubhead].Add(line); } } } } private static string RemoveMarkdown(string str, string listUnicodeChar = null, bool stripListLeaders = true, bool gfm = true, bool useImgAltText = true) { var output = str ?? string.Empty; // Remove horizontal rules (stripListLeaders conflict with this rule, which is why it has been moved to the top) output = Regex.Replace(output, @"(?m)^(-\s*?|\*\s*?|_\s*?){3,}\s*$", string.Empty); if (stripListLeaders) { var replacement = "$1"; if (listUnicodeChar != null && listUnicodeChar != string.Empty) { replacement = $"{listUnicodeChar} $1"; } output = Regex.Replace(output, @"(?m)^([\s\t]*)([\*\-\+]|\d+\.)\s+", replacement); } if (gfm) { // Header output = Regex.Replace(output, @"\n={2,}", "\n"); // Fenced codeblocks output = Regex.Replace(output, @"~{3}.*\n", string.Empty); // Strikethrough output = Regex.Replace(output, "~~", string.Empty); // Fenced codeblocks output = Regex.Replace(output, @"`{3}.*\n", string.Empty); } // Remove HTML tags output = Regex.Replace(output, @"<[^>]*>", string.Empty); // Remove setext-style headers output = Regex.Replace(output, @"^[=\-]{2,}\s*$", string.Empty); // Remove footnotes? output = Regex.Replace(output, @"\[\^.+?\](\: .*?$)?", string.Empty); output = Regex.Replace(output, @"\s{0,2}\[.*?\]: .*?$", string.Empty); // Remove images output = Regex.Replace(output, @"\!\[(.*?)\][\[\(].*?[\]\)]", useImgAltText ? "$1" : string.Empty); // Remove inline links output = Regex.Replace(output, @"\[(.*?)\][\[\(].*?[\]\)]", "$1"); // Remove blockquotes output = Regex.Replace(output, @"^\s{0,3}>\s?", string.Empty); // Remove reference-style links? output = Regex.Replace(output, @"^\s{1,2}\[(.*?)\]: (\S+)( "".*?"")?\s*$", string.Empty); // Remove atx-style headers output = Regex.Replace(output, @"(?m)^(\n)?\s{0,}#{1,6}\s+| {0,}(\n)?\s{0,}#{0,} {0,}(\n)?\s{0,}$", "$1$2$3"); // Remove emphasis (repeat the line to remove double emphasis) output = Regex.Replace(output, @"([\*_]{1,3})(\S.*?\S{0,1})\1", "$2"); output = Regex.Replace(output, @"([\*_]{1,3})(\S.*?\S{0,1})\1", "$2"); // Remove code blocks output = Regex.Replace(output, @"(?m)(`{3,})(.*?)\1", "$2"); // Remove inline code output = Regex.Replace(output, @"`(.+?)`", "$1"); // Replace two or more newlines with exactly two? Not entirely sure this belongs here... output = Regex.Replace(output, @"\n{2,}", "\n\n"); return output; }
the_stack
@{ ViewBag.MainMenu = "Campaign"; ViewBag.LeftMenu = "PictureVote"; ViewBag.Title = "投票"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script language="javascript"> var _mode = "create";//modify var _validator; var _pictureVote; $(document).ready(function () { setOnlyMember(); _validator = $("#formExtra").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { //"txtMaxPublishTimes": { // required: true, // number: true, // digits: true, // range: [1, 100] //}, "txtMaxVoteTimes": { required: true, number: true, digits: true, range: [1, 100] }, "txtApprovedPoint": { required: true, number: true, digits: true, range: [1, 1000] }, "txtShareTimelineVote": { required: true, number: true, digits: true, range: [1, 100] }, "txtShareAppMessageVote": { required: true, number: true, digits: true, range: [1, 100] } }, messages: { //"txtMaxPublishTimes": { // required: "请输入允许发布条数;", // number: "允许发布条数请输入有效整数字;", // digits: "允许发布条数请输入有效整数字;", // range: "允许发布条数请介于 0 到 100 之间;" //}, "txtMaxVoteTimes": { required: "请输入每人可投票数;", number: "每人可投票数请输入有效整数字;", digits: "每人可投票数请输入有效整数字;", range: "每人可投票数请介于 0 到 100 之间;" }, "txtApprovedPoint": { required: "请输入参与活动奖励积分;", number: "参与活动奖励积分请输入有效整数字;", digits: "参与活动奖励积分请输入有效整数字;", range: "参与活动奖励积分请介于 0 到 1000 之间;" }, "txtShareTimelineVote": { required: "请输入分享朋友圈奖励票数;", number: "分享朋友圈奖励票数请输入有效整数字;", digits: "分享朋友圈奖励票数请输入有效整数字;", range: "分享朋友圈奖励票数请介于 0 到 100 之间;" }, "txtShareAppMessageVote": { required: "请输入分享好友奖励票数;", number: "分享好友奖励票数请输入有效整数字;", digits: "分享好友奖励票数请输入有效整数字;", range: "分享好友奖励票数请介于 0 到 100 之间;" } } }); loadData(); }); function loadData() { var id = getQueryString("id"); if (id == undefined || id == "") { return; } _mode = "modify"; $("#btnRemove").show(); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Campaign/GetPictureVoteBundle?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var campaign = data.Data.Campaign; _pictureVote = data.Data.PictureVote; setCampaign(campaign); $("#selectPublishType").find("option[value='" + _pictureVote.PublishType + "']").attr("selected", true); //$("#txtMaxPublishTimes").val(_pictureVote.MaxPublishTimes); $("#txtMaxVoteTimes").val(_pictureVote.MaxVoteTimes); $("#txtApprovedPoint").val(_pictureVote.ApprovedPoint); $("#txtShareTimelineVote").val(_pictureVote.ShareTimelineVote); $("#txtShareAppMessageVote").val(_pictureVote.ShareAppMessageVote); $("#selectVoteType").find("option[value='" + _pictureVote.VoteType + "']").attr("selected", true); $("#selectAllowedNoAttentionVote").find("option[value='" + _pictureVote.AllowedNoAttentionVote + "']").attr("selected", true); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function save() { if (_campaignBaseInfoValidator.form() == false || _validator.form() == false) { return; } var campaign = getCampaign(); if (_pictureVote == undefined || _pictureVote == null) { _pictureVote = new Object(); } _pictureVote.PublishType = $("#selectPublishType").val(); //_pictureVote.MaxPublishTimes = $("#txtMaxPublishTimes").val(); _pictureVote.MaxVoteTimes = $("#txtMaxVoteTimes").val(); _pictureVote.ApprovedPoint = $("#txtApprovedPoint").val(); _pictureVote.ShareTimelineVote = $("#txtShareTimelineVote").val(); _pictureVote.ShareAppMessageVote = $("#txtShareAppMessageVote").val(); _pictureVote.VoteType = $("#selectVoteType").val(); _pictureVote.AllowedNoAttentionVote = $("#selectAllowedNoAttentionVote").val(); var bundle = new Object(); bundle.Campaign = campaign; bundle.PictureVote = _pictureVote; var url = "/Api/Campaign/CreatePictureVote"; if (_mode == "modify") { campaign.Id = $("#txtId").val(); url = "/Api/Campaign/UpdatePictureVote"; } var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: url, type: "POST", dataType: "json", data: JSON.stringify(bundle), success: function (data, status, jqXHR) { if (data.Success) { var url = "PictureVote_Preparatory"; if (campaign.Status != undefined && campaign.Status != null) { switch (campaign.Status) { case 0: url = "PictureVote_Preparatory"; break; case 1: url = "PictureVote_Ongoing"; break; case 2: url = "PictureVote_End"; break; } } window.location.href = "/Campaign/" + url; } else { layer.close(loadLayerIndex); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function cancel() { window.location.href = "/Campaign/PictureVote_Preparatory"; } function removeData() { var id = $("#txtId").val(); if (id == undefined || id == "") { return; } var msg = "是否确认删除该活动?" var confirmLayerIndex = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 shade: [0.4, '#393D49'], title: false, closeBtn: false, shift: _layerShift }, function () { layer.close(confirmLayerIndex); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Campaign/RemovePictureVote?id=" + id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { if (data.Success) { window.location.href = "/Campaign/PictureVote_Preparatory"; } else { layer.close(loadLayerIndex); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); }); } </script> <div style="margin-top: 25px; margin-left: 10px;" class="font_black_24"> 发起活动 </div> <div class="divDotLine" style="margin-top: 15px;"></div> <div style="margin-top: 25px;"> @Helpers.CampaignBaseEdit() </div> <div style="margin-top: 0px;"> <form id="formExtra"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="200" height="36">发布方式:</td> <td> <select id="selectPublishType" name="selectPublishType" class="input_16" style="width: 130px;"> <option value="0">用户上传</option> </select> </td> </tr> @*<tr> <td height="36">每人允许发布条数:</td> <td> <input id="txtMaxPublishTimes" name="txtMaxPublishTimes" type="text" class="input_16" style="width: 130px;" value="1" disabled /></td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 每个参与者最多可以发布多少条被投票项目。 </div> </td> </tr>*@ <tr> <td width="140" height="36">每人可投票数:</td> <td> <input id="txtMaxVoteTimes" name="txtMaxVoteTimes" type="text" class="input_16" style="width: 130px;" value="1" /></td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 每个投票者手中的票数。 </div> </td> </tr> <tr> <td width="200" height="36">投票方式:</td> <td> <select id="selectVoteType" name="selectVoteType" class="input_16" style="width: 250px;"> <option value="0">不允许重复给同一个人投票</option> <option value="1">每天可重复给同一个人投票</option> </select> @Helpers.VipIcon() </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 如果选择“每天可重复给同一个人投票”,则“每人可投票数”会在每天重置。 </div> </td> </tr> <tr> <td width="200" height="36">允许未关注者投票:</td> <td> <select id="selectAllowedNoAttentionVote" name="selectAllowedNoAttentionVote" class="input_16" style="width: 250px;"> <option value="true" selected>是</option> <option value="false">否</option> </select> @Helpers.VipIcon() </td> </tr> <tr> <td></td> <td> <div class="font_gray_13" style="width: 96%; margin-bottom: 10px;"> 是否必须先关注公众号才可以投票。 </div> </td> </tr> <tr> <td width="140" height="36">参与活动奖励积分:</td> <td> <input id="txtApprovedPoint" name="txtApprovedPoint" type="text" class="input_16" style="width: 130px;" value="1" /> </td> </tr> <tr> <td width="140" height="36">分享朋友圈奖励票数:</td> <td> <input id="txtShareTimelineVote" name="txtShareTimelineVote" type="text" class="input_16" style="width: 130px;" value="1" /></td> </tr> <tr> <td width="140" height="36">分享好友奖励票数:</td> <td> <input id="txtShareAppMessageVote" name="txtShareAppMessageVote" type="text" class="input_16" style="width: 130px;" value="1" /></td> </tr> </table> </form> </div> <div style="margin-top: 25px;"> <div style="float: right;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" style="display: none" onclick="removeData()" /> </div> <div style="float: left"> <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保 存" onclick="save()" /> <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" /> </div> <div style="clear: both"></div> </div> @Helpers.FileUpload()
the_stack
@page @model SpecOps.Pages.Admin.TerminalModel @{ ViewData["Title"] = "Terminal"; } @section head { <!-- jQuery Terminal --> <link rel="stylesheet" href="@Url.Content("~/css/jquery.terminal.min.css")"> <!-- PrismJS (configured for dark background and powershell commands) --> <link rel="stylesheet prefetch" href="@Url.Content("~/css/prism.css")"> <style> /* Log table styles taken from https://windowsterminalthemes.dev/ theme Obsidian */ :root { --log-foreground: #bbbbbb; /*white*/ --log-background: #283033; /*background*/ } .so-data { color: #bbbbbb; } /*white*/ .so-error { color: #ff5370; } /*red*/ .so-warning { color: #fecd22; } /*yellow*/ .so-info { color: #ffffff; } /*brightWhite*/ .so-progress { color: #00bb00; } /*green*/ .so-verbose { color: #3a9bdb; } /*blue*/ .so-debug { color: #55ffff; } /*brightCyan*/ .so-system { color: #00bbbb; } /*cyan*/ .so-unknown { color: #ffcb6b; } /*yellow*/ /* ----------------------------------------------------------------------------- */ .logRecord div:nth-of-type(1) { display:inline-block; width:190px; white-space:nowrap; } .logRecord div:nth-of-type(2) { display:inline-block; width:85px; } .logRecord div:nth-of-type(3) { display:inline-block; width:auto; } </style> } @section pageHeader { <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Terminal</h1> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> } <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-10"> <!-- Horizontal Form --> <div class="card card-secondary collapsed-card"> <div class="card-header"> <h3 class="card-title">Tips</h3> <div class="card-tools"> <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-plus"></i> </button> </div> <!-- /.card-tools --> </div> <!-- /.card-header --> <div class="card-body"> <ul> <li>Multiline input is accepted (use <span class="font-weight-bold">Shift-Enter</span> to go to next line)</li> <li><span class="font-weight-bold">Ctrl-C</span> should cancel long running code</li> <li>You may have to pipe some command output to Write-Host/Information/etc. Example: <span class="font-weight-bold">dir | Write-Host</span></li> </ul> </div> <!-- /.card-body --> </div> </div> </div> <div class="row"> <!-- left column --> <div class="col-md-10"> <!-- Horizontal Form --> <div class="card card-secondary"> <div class="card-header"> <h3 class="card-title">Runspace Config</h3> </div> <!-- /.card-header --> <form id="dummyForm"> <div class="card-body runspaceConfig"> <div class="form-group row"> <label for="ExecutionPolicy" class="col-md-2 col-form-label">Execution Policy</label> <div class="col-md-6"> <select id="ExecutionPolicy" name="ExecutionPolicy" class="custom-select"> <option value="" selected></option> <option value="AllSigned">AllSigned</option> <option value="Bypass">Bypass</option> <option value="Default">Default</option> <option value="RemoteSigned">RemoteSigned</option> <option value="Restricted">Restricted</option> <option value="Undefined">Undefined</option> <option value="Unrestricted">Unrestricted</option> </select> </div> </div> <div class="form-group row"> <label for="Modules" class="col-md-2 col-form-label">Modules</label> <div class="col-md-6"> <input id="Modules" name="Modules" type="text" class="form-control" placeholder="comma separated" /> </div> </div> <div class="form-group row"> <label for="Min" class="col-md-2 col-form-label">Min</label> <div class="col-md-1"> <input id="Min" name="Min" type="number" class="form-control" /> </div> <div class="col-md-2"></div> <label for="Max" class="col-md-2 col-form-label">Max</label> <div class="col-md-1"> <input id="Max" name="Max" type="number" class="form-control" /> </div> </div> </div> </form> </div> </div> </div> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- Horizontal Form --> <div class="card card-secondary"> <div class="card-body"> <div id="terminal"> </div> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> </div> </div> @section scripts { <!-- SignalR --> <script src="@Url.Content("~/lib/signalr/dist/browser/signalr.min.js")"></script> <!-- jQuery Terminal --> <script src="@Url.Content("~/lib/jquery-terminal/jquery.terminal.min.js")"></script> <!-- PrismJS (configured for dark background and powershell commands) --> <script src="@Url.Content("~/lib/prism/prism.js")"></script> <!-- jQuery Terminal monkey patch for PrismJS --> <script src="@Url.Content("~/lib/jquery-terminal/jquery.terminal.prism.js")"></script> <script> (function () { // Mapping of output log record type to css class for coloring comes from appsettings var dataTypes = @Html.Raw(Model.OutputLevels); var connection; var $terminal; $(document).ready(function () { // dynamically get the hubUrl by including the site's appname if exists, as site could be running from root or as an app. // setup the hub connection connection = new signalR.HubConnectionBuilder().withUrl("@HttpContext.Request.PathBase.Value" + "/streamPowerShellRaw").build(); // log the output records to the table as they come in connection.on("OutputReceived", logRecord => { if (logRecord.type == 'System' && logRecord.data == "Loading script...") { $terminal.pause(); } $terminal.echo(`<div class="logRecord ${ dataTypes.find((o) => { return o["Name"] === logRecord.type }).CssClass ?? "" }"> <div>${logRecord.timeStamp}</div> <div>${logRecord.type}</div> <div>${logRecord.data}</div> </div>` , {raw: true, wrap:false}); if (logRecord.type == 'System' && logRecord.data == "Script execution ended.") { $terminal.resume(); } }); // enable terminal input once connected connection.start().then(function () { // Setup the terminal $terminal = $('#terminal').terminal(function(command, term) { if (command !== '') { if (command == 'cls') { $terminal.clear(); } else { let runspaceOptions = $("div.runspaceConfig input, div.runspaceConfig select").filter(function() {return this.value;}).length; let runspace = undefined; if (runspaceOptions > 0) { runspace = { ExecutionPolicy: $('#ExecutionPolicy option:selected').text(), Min: parseInt($('#Min').val()) || undefined, Max: parseInt($('#Max').val()) || undefined, Modules: $('#Modules').val().split(',').filter(entry => entry.trim() != '') } }; connection .invoke("StreamPowerShellRaw", command, runspace) .catch(function (err) { $terminal.echo(`An error occured: ${err}`).resume(); }); } } }, { keydown: function(e, term) { if (e.which === 67 && e.ctrlKey) { // CTRL+C $.getJSON(`?handler=CancelScript&connectionId=${connection.connection.connectionId}`); $terminal.echo("Canceled...").resume(); return false; } }, greetings: 'PowerShell Terminal\n', height: 500, pauseEvents: false, prompt: 'PS > ' }); $.terminal.syntax('powershell'); }).catch(err => $terminal.echo(`An error occured: ${err}`)); }); })(); </script> }
the_stack
@using System.IO; <link rel="stylesheet" href="wwwroot/lib/bootstrap/css/bootstrap.min.css" /> <link rel="stylesheet" href="wwwroot/css/site.css" /> @{ async void RenderReferences() { var logoBinary = File.ReadAllBytes(@Url.Content("wwwroot/images/CRR/CRR_logo.png")); var logoURI = @"data:image/png;base64," + Convert.ToBase64String(logoBinary); var logoHtml = String.Format("<img src='{0}' class=\"row crr-logo\">", logoURI); @Html.Raw(logoHtml) <br /> <h5 style="color: #363895;">List of Resources Referenced in this Report</h5> <table class="resource-table"> <tr style="background-color: #363895;"> <td style="color: white;"> <div>Resource Name</div> </td> <td style="color: white;"> <div>URL</div> </td> </tr> <tr> <td class="resource-name"> <div> A Complete Guide to the Common Vulnerability Scoring System Version 2.0 </div> </td> <td class="url"> <a target="_blank" href="http://www.first.org/cvss/v2/guide">http://www.first.org/cvss/v2/guide</a> </td> </tr> <tr> <td class="resource-name"> <div> "Introducing OCTAVE Allegro: Improving the Information Security Risk Assessment Process" </div> </td> <td class="url"> <a target="_blank" href="https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=8419">https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=8419</a> </td> </tr> <tr> <td class="resource-name"> <div>CERT Resilience Management Model (CERT©-RMM)</div> </td> <td class="url"> <a target="_blank" href="https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=508084">https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=508084</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-16 Revision 1 (DRAFT) "A Role-Based Model for Federal Information Technology/Cybersecurity Training (3rd Draft)" </div> </td> <td class="url"> <a target="_blank" href="https://csrc.nist.gov/publications/detail/sp/800-16/rev-1/archive/2014-03-14">https://csrc.nist.gov/publications/detail/sp/800-16/rev-1/archive/2014-03-14</a> </td> </tr> <tr> <td class="resource-name"> <div> FIPS Publication 199 "Standards for Security Categorization and Federal Information and Information Systems" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/fips/fips199/FIPSPUB-199-final.pdf">http://csrc.nist.gov/publications/fips/fips199/FIPSPUB-199-final.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> FIPS Publication 200 "Minimum Security Requirements for Federal Information and Information Systems" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/fips/fips200/FIPS-200-final-march.pdf">http://csrc.nist.gov/publications/fips/fips200/FIPS-200-final-march.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Framework for Improving Critical Infrastructure Cybersecurity </div> </td> <td class="url"> <a target="_blank" href="http://www.nist.gov/cyberframework/">http://www.nist.gov/cyberframework/</a> </td> </tr> <tr> <td class="resource-name"> <div> Handbook for Computer Security Incident Response Teams (CSIRTs) </div> </td> <td class="url"> <a target="_blank" href="https://resources.sei.cmu.edu/asset_files/Handbook/2003_002_001_14102.pdf">https://resources.sei.cmu.edu/asset_files/Handbook/2003_002_001_14102.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div>Managing for Enterprise Security</div> </td> <td class="url"> <a target="_blank" href="http://resources.sei.cmu.edu/library/asset-view.cfm?assetID=7019">http://resources.sei.cmu.edu/library/asset-view.cfm?assetID=7019</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-18 Revision 1 "Guide for Developing Security Plans for Federal Information Systems" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-18-Rev1/sp800-18-Rev1-final.pdf">http://csrc.nist.gov/publications/nistpubs/800-18-Rev1/sp800-18-Rev1-final.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-30 "Guide for Conducting Risk Assessments" </div> </td> <td class="url"> <a target="_blank" href="http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-30r1.pdf"> http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-30r1.pdf </a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-34 "Contingency Planning for Federal Information Systems" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-34-rev1/sp800-34-rev1_errata-Nov11-2010.pdf"> http://csrc.nist.gov/publications/nistpubs/800-34-rev1/sp800-34-rev1_errata-Nov11-2010.pdf </a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-37 "Risk Management Framework for Information Systems and Organizations: A System Life Cycle Approach for Security and Privacy" </div> </td> <td class="url"> <a target="_blank" href="https://csrc.nist.gov/publications/detail/sp/800-37/rev-2/final">https://csrc.nist.gov/publications/detail/sp/800-37/rev-2/final</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-39 "Managing Information Security Risk: Organization, Mission, and Information System View" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-39/SP800-39-final.pdf">http://csrc.nist.gov/publications/nistpubs/800-39/SP800-39-final.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-40 Version 3.0 "Guide to Enterprise Patch Management Technologies" </div> </td> <td class="url"> <a target="_blank" href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-40r3.pdf">http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-40r3.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-53 Revision 4 "Security and Privacy Controls for Federal Information Systems and Organizations" </div> </td> <td class="url"> <a target="_blank" href="http://dx.doi.org/10.6028/NIST.SP.800-53r4">http://dx.doi.org/10.6028/NIST.SP.800-53r4</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publications 800-61 "Computer Security Incident Handling guide" </div> </td> <td class="url"> <a target="_blank" href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-61r2.pdf">http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-61r2.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-70 "National Checklist Program for IT Products: Guidelines for Checklist Users and Developers" </td> <td class="url"> <a target="_blank" href="https://csrc.nist.gov/publications/detail/sp/800-70/rev-4/final">https://csrc.nist.gov/publications/detail/sp/800-70/rev-4/final</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-84 "Guide to Test, Training, and Exercise Programs for IT Plans and Capabilities" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-84/SP800-84.pdf">http://csrc.nist.gov/publications/nistpubs/800-84/SP800-84.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-128 "Guide for Security-Focused Configuration Management of Information Systems" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-128/sp800-128.pdf">http://csrc.nist.gov/publications/nistpubs/800-128/sp800-128.pdf</a> </td> </tr> <tr> <td class="resource-name"> <div> Special Publication 800-137 "Information Security Continuous Monitoring (ICSM) for Federal Information Systems and Organizations" </div> </td> <td class="url"> <a target="_blank" href="http://csrc.nist.gov/publications/nistpubs/800-137/SP800-137-Final.pdf"> http://csrc.nist.gov/publications/nistpubs/800-137/SP800-137-Final.pdf </a> </td> </tr> </table> } } <div class="container-fluid"> @{ RenderReferences(); } </div> <style> table.resource-table td { border: 1px solid black !important; padding: 0 0.5rem; font-size: 9pt; } td.resource-name { min-width: 50%; max-width: 50%; width: 50%; padding: 0; } td.url { text-decoration: underline; color: #363895; word-break: break-word; padding: 0; } td.url:visited { color: #363895; } </style>
the_stack
 @using Resgrid.Model @model Resgrid.Web.Areas.User.Models.Shifts.NewShiftView @{ ViewBag.Title = "Resgrid | New Shift"; Layout = "~/Areas/User/Views/Shared/_UserLayout.cshtml"; } <link rel="stylesheet" href="~/lib/bootstrapvalidator/css/bootstrapValidator.css" /> <style> .ui-datepicker { width: 100% !important; } .nav > li.active { border-left: 0px solid #2185c2; color: #FFFFFF !important; } </style> <div class="row wrapper border-bottom white-bg page-heading"> <div class="col-sm-4"> <h2>New Shift</h2> <ol class="breadcrumb"> <li> <a asp-controller="Home" asp-action="Dashboard" asp-route-area="User">Home</a> </li> <li> <a asp-controller="Shifts" asp-action="Index" asp-route-area="User">Shifts</a> </li> <li class="active"> <strong>New Shift</strong> </li> </ol> </div> </div> <div class="row"> <div class="col-xs-12"> <div class="wrapper wrapper-content"> <div class="ibox float-e-margins"> <div class="ibox-content"> <form class="form-horizontal" role="form" asp-controller="Shifts" asp-action="NewShift" asp-route-area="User" method="post" id="new_shift"> <div id="rootwizard"> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <ul> <li><a href="#tab1" data-toggle="tab">Start ></a></li> <li><a href="#tab2" data-toggle="tab">Schedule ></a></li> <li><a href="#tab3" data-toggle="tab">Slots ></a></li> <li><a href="#tab4" data-toggle="tab">Personnel ></a></li> <li><a href="#tab5" data-toggle="tab">Finish</a></li> </ul> </div> </div> </div> <div class="tab-content"> <div class="tab-pane" id="tab1"> <div class="row"> <div class="col-xs-12"> <p>Welcome to the new Shift wizard. This wizard will guide you through creating a new shift for your department. Below specify your shifts name, code and optional shift color. To continue click the "Next" button in the lower right hand corner.</p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Name of the Shift" asp-for="Shift.Name" name="Shift_Name"> <span class="help-block m-b-none">For example ("A Shift", "B Shift", "C Shift")</span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Code</label> <div class="col-sm-4"> <input type="text" class="form-control" asp-for="Shift.Code" name="Shift_Code"> <span class="help-block m-b-none">Example ("A", "B", "C")</span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Assignment Type</label> <div class="col-sm-10"> <select asp-for="AssignmentType" asp-items="ViewBag.ShiftAssignmentTypes" style="padding-left: 0; width: 40%;" class="form-control"></select> <span class="help-inline">For assigned you specify the personnel for the shift, for signup the personnel will assign themselves</span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Color</label> <div class="col-sm-10"> <input type="text" class="form-control" asp-for="Shift.Color" id="colorPicker"> <span class="help-block m-b-none">Note the text on the Calendar is black, take that into account when picking a shift color as the color will be used as the background</span> </div> </div> </div> <div class="tab-pane" id="tab2"> <div class="row"> <div class="col-xs-12"> <p>Below is where you specify which days the shift will on duty and the start time of shift for the first day. If your shift is contiguous the start time will be for the first shift day (i.e. Day 1 of a 48hour block). </p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Start Time</label> <div class="col-sm-3"> <input type="text" class="form-control" asp-for="Shift.StartTime" name="Shift_StartTime" onkeydown="javascript:return false;"> <span class="help-block m-b-none">When does the shift start for the first day (or only day)</span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">End Time</label> <div class="col-sm-3"> <input type="text" class="form-control" asp-for="Shift.EndTime" name="Shift_EndTime" onkeydown="javascript:return false;"> <span class="help-block m-b-none">When does the shift end for the last day (or only day)</span> </div> </div> <div class="form-group"> <div class="col-sm-12"> <div id="manualScheduleCalendar"></div> @Html.HiddenFor(m => m.Dates) </div> </div> </div> <div class="tab-pane" id="tab3"> <div class="row"> <div class="col-xs-12"> <p>Here you can configure the required roles for each group in your department for the shift. Click the "Add group to shift" button to add a group to the shift, your shift can have many groups both station and orginizational. After you select the group (witht he left hand drop down) you can click the "Add role to Group" button to add the required roles for the group. </p> </div> </div> <table id="groups" class="table table-striped table-bordered"> <thead> <tr> <th style="font-size: 14px;">Shift Group</th> <th style="font-size: 14px;">Shift Roles</th> <th style="font-size: 16px;"><a id="addGroupButton" class="btn btn-success btn-xs" onclick="resgrid.shifts.newshift.addGroup();" data-original-title="Add Group to Shift"><i class="icon-plus"></i> Add Group to Shift</a></th> </tr> </thead> <tbody></tbody> </table> </div> <div class="tab-pane" id="tab4"> <div class="row"> <div class="col-xs-12"> <p>Now select the personnel that are working in this shift for your department. These personnel will dynamically fill the group role slot based upon what group they are in if shift group roles were supplied.</p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Non-Group Personnel</label> <div class="col-sm-10"> <select id="shiftPersonnel" name="shiftPersonnel"></select> <span class="help-block m-b-none">Personnel assigned to the shift but not directly assigned to a station or organizational group (i.e. floaters or stand-bys)</span> </div> </div> @foreach (var group in Model.Groups) { <div class="form-group"> <label class="col-sm-2 control-label">@group.Name</label> <div class="col-sm-10"> <select id="groupPersonnel_@group.DepartmentGroupId" name="groupPersonnel_@group.DepartmentGroupId" class="groupPersonnelSelect"></select> </div> </div> } </div> <div class="tab-pane" id="tab5"> <div class="row"> <div class="col-xs-12 padding"> <p>Click the finish button below to create your new shift. If you need to add more days, or change any details you can always edit the shift latter from the Shifts list page.</p> </div> </div> <span class="alert alert-error"> @Html.ValidationSummary(false) @Html.AntiForgeryToken() </span> </div> <ul class="pager wizard" style="display:block;"> <li class="previous first" style="display:none;"><a href="#">First</a></li> <li class="previous"><a href="#">Previous</a></li> <li class="next"><a href="#">Next</a></li> <li class="next finish" style="display:none;"><a href="javascript:;">Finish</a></li> </ul> </div> </div> </form> </div> </div> </div> </div> </div> @section Scripts { <script src="~/lib/twitter-bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script> <script src="~/lib/bootstrapvalidator/js/bootstrapValidator.min.js"></script> <script src="~/lib/jquery-ui.multidatespicker/jquery-ui.multidatespicker.js"></script> <script> $(document).ready(function () { $('.sl2').select2(); $("#colorPicker").kendoColorPicker({ value: "#ffffff", buttons: false }); //var $validator = $("#new_shift").validate({ // rules: { // Shift_Name: { // required: true, // minlength: 3 // }, // "Shift.Code": { // required: true, // minlength: 1 // } // } //}); var $validator = $("#new_shift").bootstrapValidator({ excluded: [':disabled', ':hidden', ':not(:visible)'], fields: { Shift_Name: { validators: { notEmpty: { message: 'Shift Name is required' } } }, Shift_Code: { validators: { notEmpty: { message: 'Shift Code is required' } } }, Shift_StartTime: { validators: { notEmpty: { message: 'Shift start time is required.' } } } } }); $('#rootwizard').bootstrapWizard({ onTabShow: function (tab, navigation, index) { var $total = navigation.find('li').length; var $current = index + 1; //var $percent = ($current / $total) * 100; //$('#rootwizard').find('.bar').css({ width: $percent + '%' }); // If it's the last tab then hide the last button and show the finish instead if ($current >= $total) { $('#rootwizard').find('.pager .next').hide(); $('#rootwizard').find('.pager .finish').show(); $('#rootwizard').find('.pager .finish').removeClass('disabled'); } else { $('#rootwizard').find('.pager .next').show(); $('#rootwizard').find('.pager .finish').hide(); } }, onTabClick: function (tab, navigation, index) { return false; }, onNext: function (tab, navigation, index) { var $validate = $("#new_shift").data('bootstrapValidator').validate(); var $valid = $validate.isValid(); if (!$valid) { return false; } } }); $('#AssignmentType').on("change", function (e) { if (e.val === '1') { $('#rootwizard').bootstrapWizard('disable', 3); //$('#rootwizard').bootstrapWizard('enable', 2); } else { $('#rootwizard').bootstrapWizard('enable', 3); //$('#rootwizard').bootstrapWizard('disable', 2); } }); var today = new Date(); var y = today.getFullYear(); $('#manualScheduleCalendar').multiDatesPicker({ //addDates: ['10/14/' + y, '02/19/' + y, '01/14/' + y, '11/16/' + y], numberOfMonths: [3, 4] //, //defaultDate: '1/1/' + y }); $('#rootwizard .finish').click(function () { var dates = $('#manualScheduleCalendar').multiDatesPicker('getDates'); $('#Dates').val(dates); $("form")[0].submit(); }); $('#manualScheduleCalendar').children().first().css('width', '100%'); //$('#rootwizard').bootstrapWizard('disable', 2); //$('#manualScheduleCalendar').children().first().removeClass('width'); }); function addGroupRoleField(name) { var newField = $(name); $('#new_shift').bootstrapValidator('addField', newField); } </script> <script src="~/js/app/internal/shifts/resgrid.shifts.newshift.js"></script> }
the_stack
 <!-- MAIN CONTENT --> <div id="content"> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-map-marker fa-fw "></i> Google Map <span> > Custom Skins </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> <ul id="sparks" class=""> <li class="sparks-info"> <h5> My Income <span class="txt-color-blue">$47,171</span></h5> <div class="sparkline txt-color-blue hidden-mobile hidden-md hidden-sm"> 1300, 1877, 2500, 2577, 2000, 2100, 3000, 2700, 3631, 2471, 2700, 3631, 2471 </div> </li> <li class="sparks-info"> <h5> Site Traffic <span class="txt-color-purple"><i class="fa fa-arrow-circle-up" data-rel="bootstrap-tooltip" title="Increased"></i>&nbsp;45%</span></h5> <div class="sparkline txt-color-purple hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> <li class="sparks-info"> <h5> Site Orders <span class="txt-color-greenDark"><i class="fa fa-shopping-cart"></i>&nbsp;2447</span></h5> <div class="sparkline txt-color-greenDark hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> </ul> </div> </div> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-white" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Data Attribute Driven</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas" class="google_maps" data-gmap-lat="23.895883" data-gmap-lng="-80.650635" data-gmap-zoom="5" data-gmap-src="xml/gmap/pins.xml"> &nbsp; </div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-white" id="wid-id-1" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Greyscale</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas1" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-blueDark" id="wid-id-3" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Night Vision</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas3" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-yellow" id="wid-id-5" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Papiro Style </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas5" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-teal" id="wid-id-7" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Retro </h2> </header> <div> <div class="jarviswidget-editbox"> </div> <div class="widget-body no-padding"> <div id="map_canvas7" class="google_maps"></div> </div> </div> </div> <!-- end widget --> </article> <!-- WIDGET END --> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-greenDark" id="wid-id-2" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Cartoon Color</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas2" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-orange" id="wid-id-4" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Night Light</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas4" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-pink" id="wid-id-6" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>One Color</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="map_canvas6" class="google_maps"></div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-darken" id="wid-id-8" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <header> <span class="widget-icon"> <i class="fa fa-map-marker"></i> </span> <h2>Black & White </h2> </header> <div> <div class="jarviswidget-editbox"> </div> <div class="widget-body no-padding"> <div id="map_canvas8" class="google_maps"></div> </div> </div> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> </section> <!-- end widget grid --> </div> <!-- END MAIN CONTENT --> @section pagespecific { <script type="text/javascript"> // DO NOT REMOVE : GLOBAL FUNCTIONS! $(document).ready(function () { var pagefunction = function () { /*jslint smarttabs:true */ var colorful_style = [{ "featureType": "landscape", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "on" }, { "color": "#b1bc39" }] }, { "featureType": "landscape.man_made", "stylers": [{ "visibility": "on" }, { "color": "#ebad02" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#416d9f" }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "off" }, { "color": "#ffffff" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "color": "#ebad02" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#8ca83c" }] }]; // Grey Scale var greyscale_style = [{ "featureType": "road.highway", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "poi.medical", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.medical", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "color": "#cccccc" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#cecece" }] }, { "featureType": "road.local", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#808080" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#808080" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#fdfdfd" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "color": "#d2d2d2" }] }]; // Black & White var monochrome_style = [{ "featureType": "road.highway", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#cecece" }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "visibility": "off" }] }]; // Retro var metro_style = [{ "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "on" }, { "color": "#eee8ce" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#b8cec9" }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "off" }, { "color": "#ffffff" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#000000" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "color": "#d3cdab" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#ced09d" }] }, { "featureType": "poi", "elementType": "labels", "stylers": [{ "visibility": "off" }] }]; // Night var nightvision_style = [{ "featureType": "landscape", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "on" }, { "hue": "#0008ff" }, { "lightness": -75 }, { "saturation": 10 }] }, { "elementType": "geometry.stroke", "stylers": [{ "color": "#1f1d45" }] }, { "featureType": "landscape.natural", "stylers": [{ "color": "#1f1d45" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#01001f" }] }, { "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#e7e8ec" }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#151348" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#f7fdd9" }] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#01001f" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#316694" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "color": "#1a153d" }] }]; // Night Light var nightvision_highlight_style = [{ "elementType": "geometry", "stylers": [{ "visibility": "on" }, { "hue": "#232a57" }] }, { "featureType": "road.highway", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "elementType": "geometry.fill", "stylers": [{ "hue": "#0033ff" }, { "saturation": 13 }, { "lightness": -77 }] }, { "featureType": "landscape", "elementType": "geometry.stroke", "stylers": [{ "color": "#4657ab" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#0d0a1f" }] }, { "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#d2cfe3" }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#0d0a1f" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#ffffff" }] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#0d0a1f" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#ff9910" }] }, { "featureType": "road.local", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#4657ab" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "color": "#232a57" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#232a57" }] }, { "featureType": "poi", "elementType": "labels", "stylers": [{ "visibility": "off" }] }]; // Papiro var old_paper_style = [{ "elementType": "geometry", "stylers": [{ "visibility": "on" }, { "color": "#f2e48c" }] }, { "featureType": "road.highway", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#d3d3d3" }, { "visibility": "on" }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#f2e48c" }] }, { "featureType": "landscape", "elementType": "geometry.stroke", "stylers": [{ "visibility": "on" }, { "color": "#592c00" }] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#a77637" }] }, { "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#592c00" }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#f2e48c" }] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [{ "visibility": "on" }, { "color": "#592c00" }] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#f2e48c" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#a5630f" }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#592c00" }] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "labels", "stylers": [{ "visibility": "off" }] }]; // One color - Change the hue value for your desired color var mono_color_style = [{ "stylers": [{ "hue": "#ff00aa" }, { "saturation": 1 }, { "lightness": 1 }] }]; /* * Google Maps Initialize */ $this = $("#map_canvas"); $zoom_level = ($this.data("gmap-zoom") || 5); $data_lat = ($this.data("gmap-lat") || 29.895883); $data_lng = ($this.data("gmap-lng") || -80.650635); $xml_src = ($this.data("gmap-src") || "xml/gmap/pins.xml"); var greyStyleMap = new google.maps.StyledMapType(greyscale_style, { name: "Greyscale" }), monoChromeStyleMap = new google.maps.StyledMapType(monochrome_style, { name: "Mono Chrome" }), metroStyleMap = new google.maps.StyledMapType(metro_style, { name: "Metro" }), nightvisionStyleMap = new google.maps.StyledMapType(nightvision_style, { name: "Nightvision" }), nvisionhstyleMap = new google.maps.StyledMapType(nightvision_highlight_style, { name: "Nightvision Light" }), oPaperStyleMap = new google.maps.StyledMapType(old_paper_style, { name: "Old Paper" }), colorfulStyleMap = new google.maps.StyledMapType(colorful_style, { name: "Colorful" }), monoColorStyleMap = new google.maps.StyledMapType(mono_color_style, { name: "One Color" }); function demoLoadAttribute() { var centerLatLng = new google.maps.LatLng($data_lat, $data_lng), mapOptions = { zoom: $zoom_level, center: centerLatLng, //disableDefaultUI: true, //mapTypeId : google.maps.MapTypeId.ROADMAP mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'colorful_style', 'greyscale_style', 'monochrome_style', 'metro_style', 'nightvision_style', 'nightvision_highlight_style', 'old_paper_style', 'mono_color_style' ] } }, bounds = new google.maps.LatLngBounds(), infowindow = new google.maps.InfoWindow(), map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); map.mapTypes.set('colorful_style', colorfulStyleMap); map.mapTypes.set('greyscale_style', greyStyleMap); map.mapTypes.set('monochrome_style', monoChromeStyleMap); map.mapTypes.set('metro_style', metroStyleMap); map.mapTypes.set('nightvision_style', nightvisionStyleMap); map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap); map.mapTypes.set('old_paper_style', oPaperStyleMap); map.mapTypes.set('mono_color_style', monoColorStyleMap); //map.setMapTypeId(google.maps.MapTypeId.TERRAIN); map.setMapTypeId('metro_style'); } // end demoLoadAttribute // grey function generate_map_1() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas1'), mapOptions); // Setup skin for the map map.mapTypes.set('greyscale_style', greyStyleMap); map.setMapTypeId('greyscale_style'); } // colorful function generate_map_2() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions); // Setup skin for the map map.mapTypes.set('colorful_style', colorfulStyleMap); map.setMapTypeId('colorful_style'); } // colorful function generate_map_3() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas3'), mapOptions); // Setup skin for the map map.mapTypes.set('nightvision_style', nvisionhstyleMap); map.setMapTypeId('nightvision_style'); } // Night Light function generate_map_4() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas4'), mapOptions); // Setup skin for the map map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap); map.setMapTypeId('nightvision_highlight_style'); } // Paper Style function generate_map_5() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas5'), mapOptions); // Setup skin for the map map.mapTypes.set('old_paper_style', oPaperStyleMap); map.setMapTypeId('old_paper_style'); } // One Color Style function generate_map_6() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas6'), mapOptions); // Setup skin for the map map.mapTypes.set('mono_color_style', monoColorStyleMap); map.setMapTypeId('mono_color_style'); } // Monochrome Style function generate_map_8() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas8'), mapOptions); // Setup skin for the map map.mapTypes.set('monochrome_style', monoChromeStyleMap); map.setMapTypeId('monochrome_style'); } // Metro Style function generate_map_7() { var mapOptions = { center: new google.maps.LatLng(41.38155, 2.13752), zoom: 12, }; map = new google.maps.Map(document.getElementById('map_canvas7'), mapOptions); // Setup skin for the map map.mapTypes.set('metro_style', metroStyleMap); map.setMapTypeId('metro_style'); } demoLoadAttribute(); generate_map_1(); generate_map_2(); generate_map_3(); generate_map_4(); generate_map_5(); generate_map_6(); generate_map_7(); generate_map_8(); }; $(window).unbind('gMapsLoaded'); $(window).bind('gMapsLoaded', pagefunction); window.loadGoogleMaps(); }) </script> }
the_stack
@model Sheng.WeixinConstruction.Management.Shell.Models.MemberQRCodeDetailViewModel @{ ViewBag.MainMenu = "Campaign"; ViewBag.LeftMenu = "MemberQRCode"; ViewBag.Title = "粉丝海报"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script type="text/javascript" src="/Scripts/laydate/laydate.js"></script> <script type="text/javascript" src="/Scripts/echarts.min.js"></script> <script> var _id = getQueryString("id"); $(document).ready(function () { if (_online == false) return; loadDataAnalyse(); }); function changePage(url) { window.location.href = url + "?id=" + _id; } function removeData() { if (_id == undefined || _id == "") { return; } var msg = "是否确认删除该活动?" var confirmLayerIndex = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 shade: [0.4, '#393D49'], title: false, closeBtn: false, shift: _layerShift }, function () { layer.close(confirmLayerIndex); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Campaign/RemoveMemberQRCode?id=" + _id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { window.location.href = "/Campaign/MemberQRCode_Ongoing"; } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); }); } function endCampaign() { if (_id == undefined || _id == "") { return; } var msg = "是否确认结束该活动?" var confirmLayerIndex = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 shade: [0.4, '#393D49'], title: false, closeBtn: false, shift: _layerShift }, function () { layer.close(confirmLayerIndex); var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); $.ajax({ url: "/Api/Campaign/EndCampaign?id=" + _id, type: "POST", dataType: "json", success: function (data, status, jqXHR) { if (data.Success) { if (data.Data == 0) { window.location.reload(); } else { layer.close(loadLayerIndex); switch (data.Data) { case 1: layerAlert("此活动已经是结束过的活动。"); case 2: layerAlert("此活动还没有开始。"); default: layerAlert("开始失败"); } } } else { layer.close(loadLayerIndex); layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); }); } function loadDataAnalyse() { @if (Model.CampaignBundle.Campaign.StartTime.HasValue == false) { <text> layerAlert("活动尚未开始。"); return; </text> } if ($("#txtStartDate").val() == "") { $("#txtStartDate").val('@Model.CampaignBundle.Campaign.StartTime.Value.AddDays(-1).ToString("yyyy-MM-dd")'); } if ($("#txtEndDate").val() == "") { @if (Model.CampaignBundle.Campaign.EndTime.HasValue) { @:$("#txtEndDate").val('@Model.CampaignBundle.Campaign.EndTime.Value.ToString("yyyy-MM-dd")'); } else { @:$("#txtEndDate").val((new Date()).format("yyyy-MM-dd")); } } var loadLayerIndex = layer.load(0, { shade: [0.2, '#fff'] }); var args = new Object(); args.CampaignId = _id; args.StartDate = $("#txtStartDate").val(); args.EndDate = $("#txtEndDate").val(); $.ajax({ url: "/Api/Campaign/GetMemberQRCodeDataAnalyse", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(JSON.stringify(data)); layer.close(loadLayerIndex); if (data.Success) { showDayChart(data.Data); showLandingChart(data.Data); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); alert("Error: " + xmlHttpRequest.status); } }); } function showDayChart(data) { var categoryArray = new Array(); $.each(data.DayCreate, function (idx, obj) { categoryArray[idx] = obj.Date; }); var dayCreateArray = new Array(); $.each(data.DayCreate, function (idx, obj) { dayCreateArray[idx] = obj.TotalCount; }); var dayLandingArray = new Array(); $.each(data.DayLanding, function (idx, obj) { dayLandingArray[idx] = obj.TotalCount; }); var dayLandingPersonArray = new Array(); $.each(data.DayLandingPerson, function (idx, obj) { dayLandingPersonArray[idx] = obj.TotalCount; }); // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('dayChart')); // 指定图表的配置项和数据 option = { title: { text: '日生成量与落地量', subtext: '指定时间段内每日生成二维码的数量与落地到指定页面的数量' }, tooltip: { trigger: 'axis' }, legend: { data: ['生成量', '落地次数', '落地人数'] }, toolbox: { show: true, feature: { dataZoom: {}, dataView: { readOnly: false }, magicType: { type: ['line', 'bar'] }, restore: {}, saveAsImage: {} } }, xAxis: [ { type: 'category', boundaryGap: false, data: categoryArray } ], yAxis: [ { type: 'value', axisLabel: { formatter: '{value}' } } ], series: [ { name: '生成量', type: 'line', data: dayCreateArray }, { name: '落地次数', type: 'line', data: dayLandingArray }, { name: '落地人数', type: 'line', data: dayLandingPersonArray } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); } function showLandingChart(data) { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('landingChart')); // 指定图表的配置项和数据 option = { title: { text: '落地总量', subtext: '落地总次数及总人数' }, tooltip: { trigger: 'axis', axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: 'shadow' // 默认为直线,可选为:'line' | 'shadow' } }, legend: { data: ['落地总次数', '落地总人数'] }, xAxis: [ { type: 'value' } ], yAxis: [ { type: 'category', axisTick: { show: false }, data: [''] } ], series: [ { name: '落地总次数', type: 'bar', itemStyle: { normal: { label: { show: true } } }, data: [data.LandingCount] }, { name: '落地总人数', type: 'bar', itemStyle: { normal: { label: { show: true } } }, data: [data.LandingPersonCount] } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); } </script> <div style="margin-top: 25px; margin-left: 10px;" class="font_black_24"> @Model.CampaignBundle.Campaign.Name </div> <div style="margin-top: 30px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="td_ContentTab_active" style="width: 150px;">摘要</td> <td class="td_ContentTab" style="width: 150px;"> <a href="javascript:void(0)" class="a_black_16" onclick="changePage('/Campaign/MemberQRCodeItemList')">生成记录</a> </td> <td align="right"> &nbsp; </td> </tr> <tr> <td colspan="4" bgcolor="#EEEEEE" height="2"></td> </tr> </table> </div> <div style="margin-left: 20px; margin-right: 20px; margin-top: 10px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td valign="top"> <table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top: 20px;"> <tr> <td width="50%" height="36" valign="top">创建时间:@Model.CampaignBundle.Campaign.CreateTime</td> <td width="50%" valign="top">&nbsp;</td> </tr> <tr> <td width="50%" height="36" valign="top">开始时间:@Model.CampaignBundle.Campaign.StartTime</td> <td width="50%" valign="top"> @if (Model.CampaignBundle.Campaign.Status == Sheng.WeixinConstruction.Infrastructure.EnumCampaignStatus.End) { @:结束时间:@Model.CampaignBundle.Campaign.EndTime } </td> </tr> <tr> <td height="36" valign="top">创建者:@Model.CampaignBundle.Campaign.CreateUserName</td> <td valign="top"> 仅关注者可参与: @if (Model.CampaignBundle.Campaign.OnlyMember) { @:是 } else { @:否 } </td> </tr> <tr> <td colspan="2" valign="top">备注:@Model.CampaignBundle.Campaign.Remark</td> </tr> </table> </td> <td width="280" align="right" valign="top"> <img src="@Model.CampaignBundle.Campaign.ImageUrl" sty style="max-width:240px;"> </td> </tr> </table> </div> <div class="divDotLine" style="margin-top: 20px; margin-left: 20px; margin-right: 20px;"></div> <div style="margin-top:10px;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <div style="padding:0px;"> <table width="100%" border="0" cellspacing="0" cellpadding="8"> <tr> <td width="60">开始:</td> <td width="150"> <input id="txtStartDate" class="input_16" onclick="laydate({format: 'YYYY-MM-DD'})"> </td> <td width="60">结束:</td> <td width="150"> <input id="txtEndDate" class="input_16" onclick="laydate({format: 'YYYY-MM-DD'})"> </td> <td> <span style=" margin-top:20px;"> <input name="btnSearch" type="button" class="btn_blue" id="btnSearch" value="查询" onclick="loadDataAnalyse()" /> </span> </td> <td width="100" align="right"> &nbsp; </td> </tr> </table> </div> </td> </tr> </table> </div> <div id="dayChart" style="width: 100%; height: 400px; margin-top:20px;"></div> <div class="divDotLine" style="margin-top: 20px; margin-left: 20px; margin-right: 20px;"></div> <div id="landingChart" style="width: 100%; height: 300px; margin-top:20px;"></div> <div class="divDotLine" style="margin-top: 20px; margin-left: 20px; margin-right: 20px;"></div> <div style="margin-top: 25px;"> <div style="float: right;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" onclick="removeData()" /> </div> <div style="float: left"> @if (Model.CampaignBundle.Campaign.Status == Sheng.WeixinConstruction.Infrastructure.EnumCampaignStatus.Ongoing) { <input name="btnModify" type="button" class="btn_blue" id="btnModify" value="编 辑" onclick="changePage('/Campaign/MemberQRCodeEidt')" /> <input name="btnEnd" type="button" class="btn_red" id="btnEnd" value="结 束" onclick="endCampaign()" /> } </div> <div style="clear: both"></div> </div>
the_stack
@page "{rpCategoryId?}/{rpScriptId?}" @model SpecOps.Pages.User.ScriptsModel @{ ViewData["Title"] = "Script Runner"; } @section head { <!-- DataTables --> <link rel="stylesheet" href="@Url.Content("~/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css")"> <link rel="stylesheet" href="@Url.Content("~/plugins/datatables-responsive/css/responsive.bootstrap4.min.css")"> <link rel="stylesheet" href="@Url.Content("~/plugins/datatables-buttons/css/buttons.bootstrap4.min.css")"> <style> /* Log table styles taken from https://windowsterminalthemes.dev/ theme Obsidian */ :root { --log-foreground: #bbbbbb; /*white*/ --log-background: #283033; /*background*/ } .so-data { color: #bbbbbb; } /*white*/ .so-error { color: #ff5370; } /*red*/ .so-warning { color: #fecd22; } /*yellow*/ .so-info { color: #ffffff; } /*brightWhite*/ .so-progress { color: #00bb00; } /*green*/ .so-verbose { color: #3a9bdb; } /*blue*/ .so-debug { color: #55ffff; } /*brightCyan*/ .so-system { color: #00bbbb; } /*cyan*/ .so-unknown { color: #ffcb6b; } /*yellow*/ /* ----------------------------------------------------------------------------- */ .error { border-color: var(--danger);} label.error { color: var(--danger); } /* Remove the browser's dropdown on input with range datalist because we're using bootstrap's */ [list]::-webkit-calendar-picker-indicator { display: none; } .logTable { display: block; line-height: initial; font-family: var(--font-family-monospace); font-size: .9rem; color: var(--log-foreground); background-color: var(--log-background); min-height: 30rem; padding: .6rem; table-layout: fixed; } .logTable th { text-align: left; padding: .75rem .75rem .75rem .25rem; font-weight: bold; } .logTable col:nth-of-type(1), .logTable td:nth-of-type(1) { width: 190px; white-space: nowrap; } .logTable col:nth-of-type(2) { width: 85px; } .logTable col:nth-of-type(3) { width: 100vw; } .logTable td { border: 0; padding: .1rem .25rem; } </style> } @section pageHeader { <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Script Runner</h1> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> } <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-10"> <!-- Horizontal Form --> <div class="card card-secondary"> <div class="card-header"> <h3 class="card-title">Script Config</h3> </div> <!-- /.card-header --> <form id="dummyForm"> <div class="card-body scriptConfig"> <div class="form-group row"> <label for="CategoryId" class="col-md-2 col-form-label">Category</label> <div class="col-md-6"> <select id="CategoryId" name="CategoryId" class="custom-select" asp-items="Model.Categories" required> <option value="">Select Category</option> </select> </div> </div> <div class="form-group row"> <label for="ScriptId" class="col-md-2 col-form-label">Script</label> <div class="col-md-6"> <select id="ScriptId" name="ScriptId" class="custom-select" required> <option value="">Select Script</option> </select> </div> </div> <div class="form-group row"> <label for="scriptSummary" class="col-md-2 col-form-label">Summary</label> <div class="col-md-10"> <textarea id="scriptSummary" name="scriptSummary" class="card-text form-control-plaintext" readonly style="resize:none;"></textarea> </div> </div> <div class="card border-light"> <div class="card-header font-weight-bold">Parameters</div> <div class="card-body"> <div class="card-text parameters"></div> </div> </div> </div> <!-- /.card-body --> <div class="card-footer"> <button id="runScript" type="button" class="btn btn-primary"> <i class="fas fa-code"></i> Run </button> <button id="cancelScript" type="button" class="btn btn-danger"> <i class="fas fa-stop-circle"></i> Cancel </button> </div> <!-- /.card-footer --> </form> </div> <!-- /.card --> </div> <!-- left column --> <div class="col-md-12"> <!-- Horizontal Form --> <div class="card card-secondary"> <div class="card-body"> <table id="log" class="logTable table table-dark table-borderless"> <colgroup> <col> <col> <col> </colgroup> <thead><tr><th>TimeStamp</th><th>Type</th><th>Data</th></tr></thead> <tbody></tbody> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> </div> </div> @section scripts { <!-- SignalR --> <script src="@Url.Content("~/lib/signalr/dist/browser/signalr.min.js")"></script> <!-- DataTables & Plugins --> <script src="@Url.Content("~/plugins/datatables/jquery.dataTables.min.js")"></script> <script src="@Url.Content("~/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js")"></script> <script src="@Url.Content("~/plugins/datatables-buttons/js/dataTables.buttons.min.js")"></script> <script src="@Url.Content("~/plugins/datatables-buttons/js/buttons.bootstrap4.min.js")"></script> <script src="@Url.Content("~/plugins/jszip/jszip.min.js")"></script> <script src="@Url.Content("~/plugins/pdfmake/pdfmake.min.js")"></script> <script src="@Url.Content("~/plugins/pdfmake/vfs_fonts.js")"></script> <script src="@Url.Content("~/plugins/datatables-buttons/js/buttons.html5.min.js")"></script> <script src="@Url.Content("~/plugins/datatables-buttons/js/buttons.print.min.js")"></script> <!-- jquery-validation --> <script src="@Url.Content("~/plugins/jquery-validation/jquery.validate.min.js")"></script> <script src="@Url.Content("~/plugins/jquery-validation/additional-methods.min.js")"></script> <script> (function () { // simple helper to check for null/undefined/empty function hasValue(x) { return !!x; } // Grab route parameters (if exists) because we'll auto-select them var routeCategoryId = "@HttpContext.Request.RouteValues["rpCategoryId"]" ?? ""; var routeScriptId = "@HttpContext.Request.RouteValues["rpScriptId"]" ?? ""; // Mapping of output log record type to css class for coloring comes from appsettings var dataTypes = @Html.Raw(Model.OutputLevels); var connection; $(document).ready(function () { // if the user presses Enter in a form control, don't submit the form (postback) but rather click the Run button $('form').keydown(function (event) { if (event.keyCode == 13) { event.preventDefault(); $('#runScript').click(); return false; } }); $.fn.dataTable.ext.buttons.clear = { text: 'Clear', action: function (e, dt, node, config) { dt.clear().draw(); } }; // setup the output log tabale $('#log').DataTable({ "buttons": [ { extend: 'copy', className: 'btn-sm' }, { extend: 'csv', className: 'btn-sm' }, { extend: 'excel', className: 'btn-sm' }, { extend: 'pdf', className: 'btn-sm' }, { extend: 'print', className: 'btn-sm' }, { extend: 'clear', className: 'btn-sm' } ], "paging": false, "language": { "emptyTable": "No output yet... Try running the script." }, "lengthChange": false, "searching": true, "ordering": true, "info": false, "autoWidth": false, "responsive": false, }).buttons().container().appendTo('#log_wrapper .col-md-6:eq(0)'); //Disable run button until connection is established; dont show spinner toggleRunScript(true, false); // dynamically get the hubUrl by including the site's appname if exists, as site could be running from root or as an app. // setup the hub connection connection = new signalR.HubConnectionBuilder().withUrl("@HttpContext.Request.PathBase.Value" + "/streamPowerShell").build(); // log the output records to the table as they come in connection.on("OutputReceived", logRecord => { $('#log').DataTable().row.add([ logRecord.timeStamp, logRecord.type, logRecord.data ]).draw(false).nodes().to$().addClass( dataTypes.find((o) => { return o["Name"] === logRecord.type }).CssClass ?? "" ); if (logRecord.type == 'System' && logRecord.data == "Script execution ended.") { // script finished, so enable run button and hide spinner toggleRunScript(false, false); } }); // enable the Run button once connected connection.start().then(function () { // enable run button; dont show spinner toggleRunScript(false, false); }).catch(err => $('#log').DataTable().row.add(["", "Error", `An error occured: ${err}`]).draw(false)); // if categoryId route parm exists, auto-select it in the dropdown and clear the temp variable if (hasValue(routeCategoryId)) { $("#CategoryId").val(routeCategoryId).trigger('change'); routeCategoryId = ""; } // setup validation $('#dummyForm').validate(); // this displays the range value in the output element as the slider is moved $('#dummyForm').on('input change', 'input[type="range"]', function () { this.nextElementSibling.value = this.value; }); }); /// disable (boolean) Disable button /// spin (boolean) Invoke spinner function toggleRunScript(disable, spin) { var $runScript = $('#runScript'); $runScript.prop('disabled', disable); var $cancelScript = $('#cancelScript'); var $icon = $runScript.children(":first"); if (spin) { $icon.addClass("spinner-border spinner-border-sm").removeClass("fas fa-code"); $cancelScript.prop('disabled', false); } else { $icon.removeClass("spinner-border spinner-border-sm").addClass("fas fa-code"); $cancelScript.prop('disabled', true); } } $('#cancelScript').on("click", function () { $.getJSON(`?handler=CancelScript&connectionId=${connection.connection.connectionId}`); }); // Run the script $('#runScript').on("click", function () { // if fields are valid, invoke the hub and run the script if ($('#dummyForm').valid()) { // disable run button and show spinner toggleRunScript(true, true); let parameters = {}; $('div.parameters input, div.parameters select').each(function (i) { parameters[this.id] = this.value; }); connection .invoke("StreamPowerShell", $('#ScriptId').val(), parameters) .catch(function (err) { $('#log').DataTable().row.add(["", "Error", `An error occured: ${err}`]).draw(false); // enable run button and hide spinner toggleRunScript(false, false); }); event.preventDefault(); } else { // scroll to the first error $('html, body').animate({ scrollTop: ($('.error:visible').offset().top - 60) }, 500); } }); // shared function to clear the script-specific fields function clearScriptFields() { $('#scriptSummary').val(""); $('div.parameters').empty(); } // when category changes, clear fields and get list of scripts $("#CategoryId").on("change", function () { let categoryId = $(this).val(); $ScriptId = $("#ScriptId"); $ScriptId.empty().append("<option value=''>Select Script</option>"); clearScriptFields(); if (hasValue(categoryId)) { $.getJSON(`?handler=Scripts&categoryId=${categoryId}`, (data) => { $.each(data, function (i, item) { $ScriptId.append(`<option value="${item.id}">${item.name}</option>`); }); }).done(function () { // if scriptId route parm exists, auto-select it in the dropdown and clear the temp variable if (hasValue(routeScriptId)) { $ScriptId.val(routeScriptId).trigger('change'); routeScriptId = ""; } }); } }); // when script changes, clear fields and get script-specific fields $("#ScriptId").on("change", function () { let scriptId = $(this).val(); clearScriptFields(); if (hasValue(scriptId)) { $.getJSON(`?handler=Script&scriptId=${scriptId}`, (data) => { // load the script fields $('#scriptSummary').val(data.summary); $.each(data.inputParms, function (i, parm) { switch (parm.type) { case "select": let options=""; for (var key in parm.options) { options = options + `<option value="${key}">${parm.options[key]}</option>`; } $('div.parameters').append(`<div class="form-group row"> <label for="${parm.name}" class="col-md-2 col-form-label">${parm.name}</label> <div class="col-md-4"> <select class="custom-select" id="${parm.name}" name="${parm.name}" ${parm.required ? " required" : ""}> ${options} </select> </div> ${parm.description ? "<textarea class='col-md-6 form-control-plaintext pl-2' readonly style='resize:none;'>" + parm.description + "</textarea>" : ""} </div>`); break; default: $('div.parameters').append(`<div class="form-group row"> <label for="${parm.name}" class="col-md-2 col-form-label">${parm.name}</label> <div class="col-md-4"> <input type="${parm.type}" class="form-control" id="${parm.name}" name="${parm.name}" ${parm.value ? " value='" + parm.value + "'" : ""} ${parm.list ? " custom-select" : ""} ${parm.placeholder ? " placeholder='" + parm.placeholder + "'" : ""} ${parm.required ? " required" : ""} ${parm.list ? " list='" + parm.name + "List'" : ""} ${parm.min ? " min='" + parm.min + "'" : ""} ${parm.max ? " max='" + parm.max + "'" : ""} ${parm.step ? " step='" + parm.step + "'" : ""} ${parm.pattern ? " pattern='" + parm.pattern + "'" : ""}> ${parm.list ? "<datalist id='" + parm.name + "List'>" + "<option value='" + parm.list.join("'></option><option value='") + "'></option>" + "</datalist>" : ""} ${parm.type == "range" ? "<output for='" + parm.name + "'></output>" : ""} </div> ${parm.description ? "<textarea class='col-md-6 form-control-plaintext pl-2' readonly style='resize:none;'>" + parm.description + "</textarea>" : ""} </div>`); } }); }); } // clear the log if the selected script changes $('#log').DataTable().clear().draw(); }); })(); </script> }
the_stack
@using jQuery.Validation.Unobtrusive.Native.Demos.Models @model CustomValidationModel @section metatags{ <meta name="Description" content="A demo of custom validation."> } @section scripts { @Scripts.Render("~/bundles/jquery-validation") <script> // Add our custom rule / method jQuery.validator.addMethod("notequalto", function (value, element, params) { return this.optional(element) || value !== $(params.other).val(); }, "These shouldn't equal"); $("form").validate({ submitHandler: function (form) { alert("This is a valid form!"); } }); </script> } <h3>@ViewBag.Title</h3> <p>It is also possible to extend jQuery Validation with custom attributes. There's a good <code>notequalto</code> example of how this is done using jquery.validate.unobtrusive.js on <a href="http://stackoverflow.com/a/5742494" target="_blank">Stack Overflow</a>. For this demo I'm planning to demonstrate how the same validation would be implemented using jQuery Validation Unobtrusive Native.</p> <p>Credit and thanks to <a href="http://stackoverflow.com/users/29407/darin-dimitrov" target="_blank">Darin Dimitrov</a> for his original example and thanks to the Stack Overflow folks for <a href="http://blog.stackoverflow.com/2009/06/attribution-required/" target="_blank">letting me share this</a>.</p> <ul class="nav nav-tabs" data-tabs="tabs"> <li class="active"><a data-toggle="tab" href="#demo">Demo</a></li> <li><a data-toggle="tab" href="#customattribute">Custom Attribute</a></li> <li><a data-toggle="tab" href="#model">Model</a></li> <li><a data-toggle="tab" href="#view">View</a></li> <li><a data-toggle="tab" href="#html">HTML</a></li> <li><a data-toggle="tab" href="#javascript">JavaScript</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="demo"> @using (Html.BeginForm()) { <div class="row"> @Html.LabelFor(x => x.Property, "Put something here:") @Html.TextBoxFor(x => x.Property, true) </div> <div class="row"> @Html.LabelFor(x => x.DifferentProperty, "Put something different here:") @Html.TextBoxFor(x => x.DifferentProperty, true) </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-info">Reset</button> </div> } </div> <div class="tab-pane" id="customattribute"> <p>This is the <code>NotEqualToAttribute</code> class. As you can see this implements the <code>IClientValidatable</code> interface which amounts to just the <code>GetClientValidationRules</code> method. And it is this method, and this method alone, that is relevant for jQuery Validation Unobtrusive Native just as it is for jquery.validate.unobtrusive.js.</p> <p>To go to a granualar level you can map each property of the <code>ModelClientValidationRule</code> to jQuery Validation as follows:</p> <ul> <li><code>ValidationType</code> is the jQuery Validation method or rule name. The value that this is set to will lead to the naming of data attributes like (in this example) <code>data-rule-notequalto</code> and <code>data-msg-notequalto</code>. And it's the equivalent <code>notequalto</code> method that we'll need to add to jQuery Validation to get our client side implementation working.</li> <li><code>ErrorMessage</code> is used to create the content of the (again, in this example) <code>data-msg-notequalto</code> attribute. This is the custom error message for this validation.</li> <li>The <code>ValidationParameters</code> Dictionary ends up being passed through to the <code>params</code> parameter in our client side implementation as a JavaScript Object Literal (through the magic of JSON). You can see how this is used in the JavaScript.</li> </ul> <pre class="prettyprint cs"> using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Web.Mvc; namespace jQuery.Validation.Unobtrusive.Native.Demos.CustomAttributes { public class NotEqualToAttribute : ValidationAttribute, IClientValidatable { public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "notequalto" }; rule.ValidationParameters["other"] = "#" + OtherProperty; // CSS Selector (won't work if applied to nested properties on a viewmodel) yield return rule; } public string OtherProperty { get; private set; } public NotEqualToAttribute(string otherProperty) { OtherProperty = otherProperty; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var property = validationContext.ObjectType.GetProperty(OtherProperty); if (property == null) { return new ValidationResult( string.Format( CultureInfo.CurrentCulture, "{0} is unknown property", OtherProperty ), new [] { validationContext.MemberName } ); } var otherValue = property.GetValue(validationContext.ObjectInstance, null); if (value == otherValue) { return new ValidationResult( FormatErrorMessage(validationContext.DisplayName), new [] { validationContext.MemberName }); } return ValidationResult.Success; } } } </pre> </div> <div class="tab-pane" id="model"> <p>Here's the model, note that the custom <code>NotEqualTo</code> attribute decorates the <code>DifferentProperty</code> property on the model:</p> <pre class="prettyprint cs"> using System.ComponentModel.DataAnnotations; namespace jQuery.Validation.Unobtrusive.Native.Demos.Models { public class CustomValidationModel { [Required] public string Property { get; set; } [Required, NotEqualTo("Property", ErrorMessage = "These fields cannot match")] public string DifferentProperty { get; set; } } } </pre> </div> <div class="tab-pane" id="view"> <p>Here's the view (which uses the model):</p> <pre class="prettyprint cs"> @@model jQuery.Validation.Unobtrusive.Native.Demos.Models.CustomValidationModel @@using (Html.BeginForm()) { &lt;div class="row"&gt; @@Html.LabelFor(x =&gt; x.Property, "Put something here:") @@Html.TextBoxFor(x =&gt; x.Property, true) &lt;/div&gt; &lt;div class="row"&gt; @@Html.LabelFor(x =&gt; x.DifferentProperty, "Put something different here:") @@Html.TextBoxFor(x =&gt; x.DifferentProperty, true) &lt;/div&gt; &lt;div class="row"&gt; &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt; &lt;button type="reset" class="btn btn-info"&gt;Reset&lt;/button&gt; &lt;/div&gt; } </pre> </div> <div class="tab-pane" id="html"> <p>Here's the HTML that the view generates. If you look closely at the <code>data-rule-notequalto</code> attribute you can see the JSON hiding in plain sight in the form of many a <code>&amp;quot;</code> standing in for a <code>&quot;</code>. Here's the more human readable version: <code>{&quot;other&quot;:&quot;#Property&quot;}</code>. And you can see that this single object represents the serialization of the <code>ValidationParameters</code> Dictionary on the attribute; an object with a single property.</p> <pre class="prettyprint html"> &lt;form action="/Demo/CustomValidation" method="post"&gt; &lt;div class="row"&gt; &lt;label for="Property"&gt;Put something here:&lt;/label&gt; &lt;input data-msg-required="The Property field is required." data-rule-required="true" id="Property" name="Property" type="text" value="" /&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;label for="DifferentProperty"&gt;Put something different here:&lt;/label&gt; &lt;input data-msg-notequalto="These fields cannot match" data-msg-required="The DifferentProperty field is required." data-rule-notequalto="{&amp;quot;other&amp;quot;:&amp;quot;#Property&amp;quot;}" data-rule-required="true" id="DifferentProperty" name="DifferentProperty" type="text" value="" /&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt; &lt;button type="reset" class="btn btn-info"&gt;Reset&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </pre> </div> <div class="tab-pane" id="javascript"> <p>Here's the JavaScript that adds our custom rule / method and initialises the validation.</p> <p>The name of the custom rule / method is the same as the <code>ValidationType</code> specified on the attribute, ie <code>"notequalto"</code>. The <code>"These shouldn't equal"</code> string is the default error message that will be displayed if an <code>ErrorMessage</code> wasn't specified when the attribute was being applied. And if you look at the <code>params</code> parameter you can see this is the client side equivalent of our <code>ValidationParameters</code> Dictionary on the attribute. As you can see, we use the <code>params.other</code> property to look up our comparison element. </p> <pre class="prettyprint js"> // Add our custom rule / method jQuery.validator.addMethod("notequalto", function (value, element, params) { return this.optional(element) || value !== $(params.other).val(); }, "These shouldn't equal"); $("form").validate({ submitHandler: function (form) { alert("This is a valid form!"); } }); </pre> </div> </div>
the_stack
@model News @{ Layout = Constants.AdminLayoutName; var mainName = "News"; Title = mainName + " Create"; SubTitle = "Create a new " + mainName.ToLower(); if (Model.Id > 0) { Title = mainName + " Update"; SubTitle = "Update an existing " + mainName.ToLower(); } } <style> .tabBorderDesign { border-left: 1px solid #ddd; border-right: 1px solid #ddd; border-bottom: 1px solid #ddd; } </style> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> @SubTitle <div class="pull-right"> @if (Model.Id > 0) { <a asp-controller="@ControllerName" asp-action="CreateEdit" asp-route-id="" class="btn btn-outline btn-success btn-xs">New @mainName</a> } <a asp-controller="@ControllerName" asp-action="Manage" class="btn btn-outline btn-primary btn-xs">Manage @mainName</a> </div> </div> <div class="panel-body"> <form id="createEditForm" class="form-horizontal" asp-controller="@ControllerName" asp-action="CreateEdit" method="post"> <input type="hidden" asp-for="Id" /> <input type="hidden" asp-for="Status" /> <div class="col-md-12"> <div class="col-md-8"> @{ var tabBorderDesign = ""; } @if (GlobalContext.WebSite.IsMultiLangual == true) { <ul class="nav nav-tabs" role="tablist"> @foreach (var item in Model.Details) { if (GlobalContext.WebSite.Language == item.Language) { <li role="presentation" class="active"> <a href="#@item.Language" aria-controls="@item.Language" role="tab" data-toggle="tab"> (D) @SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).FirstOrDefault().NativeName </a> </li> } else { <li role="presentation" class=""> <a href="#@item.Language" aria-controls="@item.Language" role="tab" data-toggle="tab"> @if (SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).Count() > 0) { <span>@SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).FirstOrDefault().NativeName</span> } else { <span>@item.Language</span> } </a> </li> } } </ul> tabBorderDesign = "tabBorderDesign"; } <!-- Tab panes --> <div class="tab-content @tabBorderDesign"> @{ var activeClass = ""; var i = 0;} @foreach (var item in Model.Details) { if (GlobalContext.WebSite.Language == item.Language) { activeClass = "active"; } else { activeClass = ""; } <div role="tabpanel" class="tab-pane row @activeClass" id="@item.Language"> <div class="" style="padding:10px 25px 25px 25px;"> <div class="col-md-12"> <input type="hidden" asp-for="Details[i].Id" /> <input type="hidden" asp-for="Details[i].Language" /> <input type="hidden" asp-for="Details[i].Status" /> <div class="form-group"> <label class="control-label col-md-2">Name: </label> <div class="col-md-10"> <input type="text" class="form-control categoryName" asp-for="Details[i].Name" placeholder="Enter Name in @item.Language"> <span asp-validation-for="Details[i].Name" class="text-danger"></span> </div> </div> <div class="form-group"> <label class="control-label col-md-2">Content: </label> <div class="col-md-10"> <textarea class="form-control newsContent" asp-for="Details[i].Content" placeholder="" value="@item.Content">@item.Content</textarea> </div> </div> <div class="form-group"> <label class="control-label col-md-2">Excerpt: </label> <div class="col-md-10"> <textarea class="form-control" asp-for="Details[i].Excerpt" placeholder="" value="@item.Excerpt">@item.Excerpt</textarea> </div> </div> </div> </div> </div> i++; } </div> </div> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading"> Information </div> <div class="panel-body"> <div class="form-group"> <label class="col-md-4 text-right">Date Range? </label> <div class="col-md-8"> <input type="checkbox" asp-for="HasDateRange" @{Model.HasDateRange == true ? "checked" : "";} /> </div> </div> <div class="form-group"> <label class="control-label col-md-4">Publish Date </label> <div class="col-md-8"> <div class='input-group date datetimepicker'> <input type="text" class="form-control" asp-for="PublishDate" placeholder="" value="@Model.PublishDate.ToString("MMM dd, yyyy hh:mm tt")" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-4">Expire Date </label> <div class="col-md-8"> <div class='input-group date datetimepicker'> <input type="text" class="form-control" asp-for="ExpireDate" placeholder="" value="@Model.ExpireDate.ToString("MMM dd, yyyy hh:mm tt")" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-4">Order </label> <div class="col-md-8"> <input type="text" class="form-control" asp-for="Order" placeholder="" value="@Model.Order" /> </div> </div> <div class="form-group"> <label class="text-right col-md-4">Category </label> <div class="col-md-8"> @foreach (var item in ViewBag.CategoryList) { if (Model.CategoryList != null && Model.CategoryList.Count() > 0 && Model.CategoryList.Where(x => x.CategoryId == item.Id).Count() > 0) { <input type="checkbox" name="LsCategory[]" value="@item.Id" checked /> @item.Name<br /> } else { <input type="checkbox" name="LsCategory[]" value="@item.Id" /> @item.Name<br /> } } </div> </div> </div> <div class="panel-footer"> <a asp-controller="@ControllerName" asp-action="Manage" class="btn btn-default">Back</a> <input type="submit" class="btn btn-primary" name="Save" value="Save" /> <input type="submit" class="btn btn-success" name="Save" value="Save And New" /> </div> </div> </div> </div> </form> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> </div> @section Scripts{ <script> KEDITOR_BASEPATH = "@Url.Content("~/lib/ckeditor/")"; </script> <script src="~/lib/ckeditor/ckeditor.js"></script> <script> $(document).ready(function () { var elements = document.getElementsByClassName('newsContent'); for (var i = 0; i < elements.length; ++i) { CKEDITOR.replace(elements[i], { enterMode: CKEDITOR.ENTER_DIV, allowedContent: true, filebrowserBrowseUrl: '/MediaHome/?isFile=true&inputId=ckeditor', filebrowserImageBrowseUrl: '/MediaHome/?inputId=ckeditor', //filebrowserUploadUrl: '/media/files', //filebrowserImageUploadUrl: '/MediaHome/Upload', //filebrowserWindowWidth: 800, //filebrowserWindowHeight: 500, toolbar: [ //{ name: 'document', items: ['Source', '-', /*'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates'*/] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste'] }, { name: 'clipboard1', items: ['PasteText', 'PasteFromWord'] }, { name: 'clipboard2', items: ['Undo', 'Redo'] }, //{ name: 'editing', items: ['Find', 'Replace', 'SelectAll'] }, //{ name: 'editing1', items: ['SpellChecker', 'Scayt'] }, { name: 'styles', items: ['Styles'] }, { name: 'styles1', items: ['Format'] }, { name: 'styles2', items: ['Font'] }, { name: 'styles3', items: ['FontSize'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline'] }, //{ name: 'basicstyles1', items: ['Strike', 'Subscript', 'Superscript'] }, //{ name: 'basicstyles2', items: ['-', 'RemoveFormat'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList'] }, { name: 'paragraph1', items: ['Outdent', 'Indent'] }, { name: 'paragraph2', items: ['Blockquote', 'CreateDiv'] }, { name: 'paragraph3', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] }, //{ name: 'paragraph4', items: ['-', 'BidiLtr', 'BidiRtl'] }, { name: 'links', items: ['Link', 'Unlink', 'Anchor'] }, { name: 'insert', items: ['Image', /*'Flash',*/ 'Table'] }, //'/', { name: 'colors', items: ['TextColor', 'BGColor'] }, //{ name: 'insert1', items: ['HorizontalRule', 'Smiley'] }, //{ name: 'insert2', items: ['SpecialChar', 'PageBreak'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks'] } ], }); } $("#Title").change(function () { $("#Slug").val(NccUtil.GetSafeSlug($(this).val())); }); $("#publish").click(function () { var element = document.getElementById('PageStatus'); element.value = "2"; console.log($("#Slug").val()); if ($("#Slug").val() == "") { document.getElementById("Slug").value = NccUtil.GetSafeSlug($("#Title").val()); console.log($("#Slug").val()); } document.getElementById("SubmitType").value = "publish"; //$("#SubmitType").value = "publish"; $('#PageContent').html(CKEDITOR.instances["PageContent"].getData()); document.getElementById("pageCreateEditForm").submit(); }); $("#save").click(function () { if ($("#Slug").val() == "") { $("#Slug").val(NccUtil.GetSafeSlug($(this).val())); } $("#SubmitType").val("Save"); $('#PageContent').html(CKEDITOR.instances["PageContent"].getData()); document.getElementById("pageCreateEditForm").submit(); }); }); </script> }
the_stack
BuildParameters.Tasks.InstallOpenCoverTask = Task("Install-OpenCover") .WithCriteria(() => BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows, "Not running on windows") .Does(() => RequireTool(ToolSettings.OpenCoverTool, () => { })); BuildParameters.Tasks.TestNUnitTask = Task("Test-NUnit") .IsDependentOn("Install-OpenCover") .WithCriteria(() => DirectoryExists(BuildParameters.Paths.Directories.PublishedNUnitTests), "No published NUnit tests") .Does(() => RequireTool(ToolSettings.NUnitTool, () => { EnsureDirectoryExists(BuildParameters.Paths.Directories.NUnitTestResults); if (BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows) { OpenCover(tool => { tool.NUnit3(GetFiles(BuildParameters.Paths.Directories.PublishedNUnitTests + (BuildParameters.TestFilePattern ?? "/**/*Tests.dll")), new NUnit3Settings { NoResults = true }); }, BuildParameters.Paths.Files.TestCoverageOutputFilePath, new OpenCoverSettings { OldStyle = true, ReturnTargetCodeOffset = 0 } .WithFilter(ToolSettings.TestCoverageFilter) .ExcludeByAttribute(ToolSettings.TestCoverageExcludeByAttribute) .ExcludeByFile(ToolSettings.TestCoverageExcludeByFile)); } }) ); BuildParameters.Tasks.TestxUnitTask = Task("Test-xUnit") .IsDependentOn("Install-OpenCover") .WithCriteria(() => DirectoryExists(BuildParameters.Paths.Directories.PublishedxUnitTests), "No published xUnit tests") .Does(() => RequireTool(ToolSettings.XUnitTool, () => { EnsureDirectoryExists(BuildParameters.Paths.Directories.xUnitTestResults); if (BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows) { OpenCover(tool => { tool.XUnit2(GetFiles(BuildParameters.Paths.Directories.PublishedxUnitTests + (BuildParameters.TestFilePattern ?? "/**/*Tests.dll")), new XUnit2Settings { OutputDirectory = BuildParameters.Paths.Directories.xUnitTestResults, XmlReport = true, NoAppDomain = true }); }, BuildParameters.Paths.Files.TestCoverageOutputFilePath, new OpenCoverSettings { OldStyle = true, ReturnTargetCodeOffset = 0 } .WithFilter(ToolSettings.TestCoverageFilter) .ExcludeByAttribute(ToolSettings.TestCoverageExcludeByAttribute) .ExcludeByFile(ToolSettings.TestCoverageExcludeByFile)); } }) ); BuildParameters.Tasks.TestMSTestTask = Task("Test-MSTest") .IsDependentOn("Install-OpenCover") .WithCriteria(() => DirectoryExists(BuildParameters.Paths.Directories.PublishedMSTestTests), "No published MSTest tests") .Does(() => { EnsureDirectoryExists(BuildParameters.Paths.Directories.MSTestTestResults); // TODO: Need to add OpenCover here MSTest(GetFiles(BuildParameters.Paths.Directories.PublishedMSTestTests + (BuildParameters.TestFilePattern ?? "/**/*Tests.dll")), new MSTestSettings() { NoIsolation = false }); }); BuildParameters.Tasks.TestVSTestTask = Task("Test-VSTest") .IsDependentOn("Install-OpenCover") .WithCriteria(() => DirectoryExists(BuildParameters.Paths.Directories.PublishedVSTestTests), "No published VSTest tests") .Does(() => { EnsureDirectoryExists(BuildParameters.Paths.Directories.VSTestTestResults); var vsTestSettings = new VSTestSettings() { InIsolation = true }; if (AppVeyor.IsRunningOnAppVeyor) { vsTestSettings.WithAppVeyorLogger(); } if (BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows) { OpenCover( tool => { tool.VSTest(GetFiles(BuildParameters.Paths.Directories.PublishedVSTestTests + (BuildParameters.TestFilePattern ?? "/**/*Tests.dll")), vsTestSettings); }, BuildParameters.Paths.Files.TestCoverageOutputFilePath, new OpenCoverSettings { OldStyle = true, ReturnTargetCodeOffset = 0 } .WithFilter(ToolSettings.TestCoverageFilter) .ExcludeByAttribute(ToolSettings.TestCoverageExcludeByAttribute) .ExcludeByFile(ToolSettings.TestCoverageExcludeByFile)); } }); BuildParameters.Tasks.DotNetCoreTestTask = Task("DotNetCore-Test") .IsDependentOn("Install-OpenCover") .Does<DotNetCoreMSBuildSettings>((context, msBuildSettings) => { var projects = GetFiles(BuildParameters.TestDirectoryPath + (BuildParameters.TestFilePattern ?? "/**/*Tests.csproj")); // We create the coverlet settings here so we don't have to create the filters several times var coverletSettings = new CoverletSettings { CollectCoverage = true, // It is problematic to merge the reports into one, as such we use a custom directory for coverage results CoverletOutputDirectory = BuildParameters.Paths.Directories.TestCoverage.Combine("coverlet"), CoverletOutputFormat = CoverletOutputFormat.opencover, ExcludeByFile = ToolSettings.TestCoverageExcludeByFile.Split(new [] {';' }, StringSplitOptions.None).ToList(), ExcludeByAttribute = ToolSettings.TestCoverageExcludeByAttribute.Split(new [] {';' }, StringSplitOptions.None).ToList() }; foreach (var filter in ToolSettings.TestCoverageFilter.Split(new [] {' ' }, StringSplitOptions.None)) { if (filter[0] == '+') { coverletSettings.WithInclusion(filter.TrimStart('+')); } else if (filter[0] == '-') { coverletSettings.WithFilter(filter.TrimStart('-')); } } var settings = new DotNetCoreTestSettings { Configuration = BuildParameters.Configuration, NoBuild = true }; foreach (var project in projects) { Action<ICakeContext> testAction = tool => { tool.DotNetCoreTest(project.FullPath, settings); }; var parsedProject = ParseProject(project, BuildParameters.Configuration); var coverletPackage = parsedProject.GetPackage("coverlet.msbuild"); bool shouldAddSourceLinkArgument = false; // Set it to false by default due to OpenCover if (coverletPackage != null) { // If the version is a pre-release, we will assume that it is a later // version than what we need, and thus TryParse will return false. // If TryParse is successful we need to compare the coverlet version // to ensure it is higher or equal to the version that includes the fix // for using the SourceLink argument. // https://github.com/coverlet-coverage/coverlet/issues/882 Version coverletVersion; shouldAddSourceLinkArgument = !Version.TryParse(coverletPackage.Version, out coverletVersion) || coverletVersion >= Version.Parse("2.9.1"); } settings.ArgumentCustomization = args => { args.AppendMSBuildSettings(msBuildSettings, context.Environment); if (shouldAddSourceLinkArgument && parsedProject.HasPackage("Microsoft.SourceLink.GitHub")) { args.Append("/p:UseSourceLink=true"); } return args; }; if (parsedProject.IsNetCore && coverletPackage != null) { coverletSettings.CoverletOutputName = parsedProject.RootNameSpace.Replace('.', '-'); DotNetCoreTest(project.FullPath, settings, coverletSettings); } else if (BuildParameters.BuildAgentOperatingSystem != PlatformFamily.Windows) { testAction(Context); } else { if (BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows) { // We can not use msbuild properties together with opencover settings.ArgumentCustomization = null; OpenCover(testAction, BuildParameters.Paths.Files.TestCoverageOutputFilePath, new OpenCoverSettings { ReturnTargetCodeOffset = 0, OldStyle = true, Register = "user", MergeOutput = FileExists(BuildParameters.Paths.Files.TestCoverageOutputFilePath) } .WithFilter(ToolSettings.TestCoverageFilter) .ExcludeByAttribute(ToolSettings.TestCoverageExcludeByAttribute) .ExcludeByFile(ToolSettings.TestCoverageExcludeByFile)); } } } }); BuildParameters.Tasks.IntegrationTestTask = Task("Run-Integration-Tests") .WithCriteria(() => BuildParameters.ShouldRunIntegrationTests, "Cake script integration tests have been disabled") .IsDependentOn("Default") .Does(() => { CakeExecuteScript(BuildParameters.IntegrationTestScriptPath, new CakeSettings { Arguments = new Dictionary<string, string> { { "verbosity", Context.Log.Verbosity.ToString("F") } } }); }); BuildParameters.Tasks.GenerateFriendlyTestReportTask = Task("Generate-FriendlyTestReport") .IsDependentOn("Test-VSTest") .IsDependentOn("Test-xUnit") .WithCriteria(() => BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows, "Skipping due to not running on Windows") .Does(() => RequireTool(ToolSettings.ReportUnitTool, () => { var possibleDirectories = new[] { BuildParameters.Paths.Directories.xUnitTestResults, BuildParameters.Paths.Directories.VSTestTestResults, }; foreach (var directory in possibleDirectories.Where((d) => DirectoryExists(d))) { ReportUnit(directory, directory, new ReportUnitSettings()); } }) ); BuildParameters.Tasks.GenerateLocalCoverageReportTask = Task("Generate-LocalCoverageReport") .WithCriteria(() => BuildParameters.IsLocalBuild, "Skipping due to not running a local build") .Does(() => RequireTool(BuildParameters.IsDotNetCoreBuild ? ToolSettings.ReportGeneratorGlobalTool : ToolSettings.ReportGeneratorTool, () => { var coverageFiles = GetFiles(BuildParameters.Paths.Directories.TestCoverage + "/coverlet/*.xml"); if (FileExists(BuildParameters.Paths.Files.TestCoverageOutputFilePath)) { coverageFiles += BuildParameters.Paths.Files.TestCoverageOutputFilePath; } if (coverageFiles.Any()) { var settings = new ReportGeneratorSettings(); if (BuildParameters.IsDotNetCoreBuild && BuildParameters.BuildAgentOperatingSystem != PlatformFamily.Windows) { // Workaround until 0.38.5+ version of cake is released // https://github.com/cake-build/cake/pull/2824 settings.ToolPath = Context.Tools.Resolve("reportgenerator"); } ReportGenerator(coverageFiles, BuildParameters.Paths.Directories.TestCoverage, settings); } else { Warning("No coverage files was found, no local report is generated!"); } }) ); BuildParameters.Tasks.TestTask = Task("Test");
the_stack
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> @Styles.Render("~/easyui-super/css") @Styles.Render("~/fsLayui/css") @Scripts.Render("~/fsLayui/js") @Scripts.Render(new string[] { "~/fsLayui/plugins/frame/js/frame.js" }) <style type="text/css"> .cs-navi-tab { display: block; /*width:90%;*/ color: #000; } ::-webkit-scrollbar { width: 3px; height: 4px; background-color: #F5F5F5; } /*定义滚动条轨道 内阴影+圆角*/ ::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); background: #fff; } /*定义滑块 内阴影+圆角*/ ::-webkit-scrollbar-thumb { border-radius: 3px; -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); background-color: rgba(7, 170, 247, 0.7); } ::-webkit-scrollbar-thumb:hover { border-radius: 3px; -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); background-color: rgba(7, 170, 247, 1); } /*导航右边图标样式*/ .nav-fun .accordion-expand, .nav-fun .accordion-collapse { background: none; } .selected-nav { border-bottom: 1px solid #2980B9; } </style> </head> <body id="main" class="easyui-layout"> <div data-options="region:'north',border:false" class="super-north" style="height: 50px;"> <!--顶部--> <div class="super-navigation"> <div class="super-navigation-title"> SUPER THEME </div> <div class="super-navigation-main"> <div class="super-setting-left"> <ul> <li><i class="fa fa-commenting-o"></i></li> <li><i class="fa fa-envelope-o"></i></li> <li><i class="fa fa-bell-o"></i></li> <!--<div id="mm2" class="easyui-menu"> <div>有情况</div> <div>你瞅啥</div> <div class="menu-sep"></div> <div>瞅你咋滴</div> </div>--> </ul> </div> <div class="super-setting-right"> <ul> <li class="user"> <span class="user-icon"><img src="../easyui-super-theme/img/favicon.png" /></span> <span>管理员</span> </li> <li> <div class="super-setting-icon"> <i class="fa fa-gears"></i> </div> <div id="mm2" class="easyui-menu"> <div>个人中心</div> @*<div id="themeSetting">主题</div>*@ <div class="menu-sep"></div> <div id="logout">退出</div> </div> </li> </ul> </div> </div> </div> </div> <div id="easyui-layout-west" data-options="region:'west',title:'<input type=text onchange=searchMenu(this) style=width:90%;height:20px;>',border:false"> <!--左侧导航--> <div class="easyui-accordion nav-fun" data-options="border:false,fit:false,selected:true" id="nav-fun"> @Html.Raw(ViewBag.NavHtml) </div> <div class="nav-fun" id="nav-fun-search" style="display:none;" data-options="border:false,fit:false,selected:true"> </div> </div> <div data-options="region:'center'" style="padding-top: 2px;"> <!--主要内容--> <div id="tabs" class="easyui-tabs" data-options="border:false,fit:true"> <div title="首页" data-options="iconCls:'fa fa-home'"> <iframe src="Demo" width="100%" height="99%" frameborder="no"></iframe> </div> </div> </div> <div data-options="region:'south'" class="super-south"> <!--页脚--> <div class="super-footer-info"> <span><i class="fa fa-info-circle"></i> 作者:Gemmy</span> <span><i class="fa fa-copyright"></i> CopyRight 2016 版权所有 <i class="fa fa-caret-right"></i></span> </div> </div> <!--主题设置弹窗--> <div id="win"> <div class="themeItem"> <ul> <li> <div class="TURQUOISE">TURQUOISE</div> </li> <li> <div class="EMERALD">EMERALD</div> </li> <li> <div class="PETER-RIVER">PETER RIVER</div> </li> <li> <div class="AMETHYST">AMETHYST</div> </li> <li> <div class="WET-ASPHALT">WET ASPHALT</div> </li> <li> <div class="SUN-FLOWER">SUN FLOWER</div> </li> <li> <div class="CARROT">CARROT</div> </li> <li class="themeActive"> <div class="ALIZARIN">ALIZARIN</div> </li> </ul> </div> </div> <div id="mm" class="easyui-menu cs-tab-menu"> <div id="mm-tabupdate">刷新</div> <div class="menu-sep"></div> <div id="mm-tabclose">关闭</div> <div id="mm-tabcloseother">关闭其他</div> <div id="mm-tabcloseall">关闭全部</div> </div> @Scripts.Render("~/easyui-super/js") <script type="text/javascript"> function addTab(title, url) { if ($('#tabs').tabs('exists', title)) { $('#tabs').tabs('select', title);//选中并刷新 var currTab = $('#tabs').tabs('getSelected'); var url = $(currTab.panel('options').content).attr('src'); if (url != undefined && currTab.panel('options').title != 'Home') { $('#tabs').tabs('update', { tab: currTab, options: { content: createFrame(url) } }) } } else { var content = createFrame(url); $('#tabs').tabs('add', { title: title, content: content, closable: true }); } tabClose(); } function createFrame(url) { var s = '<iframe class="sc-set" scrolling="auto" frameborder="0" src="' + url + '" style="width:100%;height:99%;"></iframe>'; return s; } function tabClose() { /*双击关闭TAB选项卡*/ $(".tabs-inner").dblclick(function () { var subtitle = $(this).children(".tabs-closable").text(); $('#tabs').tabs('close', subtitle); }) /*为选项卡绑定右键*/ $(".tabs-inner").bind('contextmenu', function (e) { $('#mm').menu('show', { left: e.pageX, top: e.pageY }); var subtitle = $(this).children(".tabs-closable").text(); $('#mm').data("currtab", subtitle); $('#tabs').tabs('select', subtitle); return false; }); } //绑定右键菜单事件 function tabCloseEven() { //刷新 $('#mm-tabupdate').click(function () { var currTab = $('#tabs').tabs('getSelected'); var url = $(currTab.panel('options').content).attr('src'); if (url != undefined && currTab.panel('options').title != 'Home') { $('#tabs').tabs('update', { tab: currTab, options: { content: createFrame(url) } }) } }) //关闭当前 $('#mm-tabclose').click(function () { var currtab_title = $('#mm').data("currtab"); $('#tabs').tabs('close', currtab_title); }) //全部关闭 $('#mm-tabcloseall').click(function () { $('.tabs-inner span').each(function (i, n) { var t = $(n).text(); if (t != 'Home') { $('#tabs').tabs('close', t); } }); }); //关闭除当前之外的TAB $('#mm-tabcloseother').click(function () { var prevall = $('.tabs-selected').prevAll(); var nextall = $('.tabs-selected').nextAll(); if (prevall.length > 0) { prevall.each(function (i, n) { var t = $('a:eq(0) span', $(n)).text(); if (t != 'Home') { $('#tabs').tabs('close', t); } }); } if (nextall.length > 0) { nextall.each(function (i, n) { var t = $('a:eq(0) span', $(n)).text(); if (t != 'Home') { $('#tabs').tabs('close', t); } }); } return false; }); //关闭当前右侧的TAB $('#mm-tabcloseright').click(function () { var nextall = $('.tabs-selected').nextAll(); if (nextall.length == 0) { //msgShow('系统提示','后边没有啦~~','error'); alert('后边没有啦~~'); return false; } nextall.each(function (i, n) { var t = $('a:eq(0) span', $(n)).text(); $('#tabs').tabs('close', t); }); return false; }); //关闭当前左侧的TAB $('#mm-tabcloseleft').click(function () { var prevall = $('.tabs-selected').prevAll(); if (prevall.length == 0) { alert('到头了,前边没有啦~~'); return false; } prevall.each(function (i, n) { var t = $('a:eq(0) span', $(n)).text(); $('#tabs').tabs('close', t); }); return false; }); //退出 $("#mm-exit").click(function () { $('#mm').menu('hide'); }) } $(function () { tabCloseEven(); navEven(); //$('.cs-navi-tab').click(function () { // var $this = $(this); // var href = $this.attr('src'); // var title = $this.text(); // addTab(title, href); //}); //左导航选中样式 $('#nav-fun').accordion({ 'onSelect': function () { $("#nav-fun > .panel").removeClass('selected-nav'); var p = $(this).accordion('getSelected'); $(p).closest('.panel').addClass('selected-nav'); } }); }); //菜单导航事件 function navEven() { $('.cs-navi-tab').on('click', function () { var $this = $(this); var href = $this.attr('src'); var title = $this.text(); addTab(title, href); }); } //菜单搜索 function searchMenu(src) { var txt = $.trim($(src).val()); var navSearch = $("#nav-fun-search"); var navFun = $("#nav-fun"); if (!txt) { navFun.show(); navSearch.hide(); } else { var html = ''; //标题包含 var panelArr = [];//已添加的panel集合 var div = navFun.find("div.panel-title"); var a = navFun.find("a.fun-search"); for (var i = 0; i < a.length; i++) { div.push(a[i]); } for (var i = 0; i < div.length; i++) { var divi = $(div[i]); if (divi.text().indexOf(txt) > -1) { var panel = divi.closest(".panel").html(); if (panelArr.indexOf(panel) > -1) { continue; } panelArr.push(panel); html += '<div class="panel panel-htop" style="width: 247px;">'; html += panel; html += '</div>' } } var re = new RegExp(txt, "g"); navSearch.html(html.replace(re, '<span style="color:red">' + txt + '</span>')); navFun.hide(); navSearch.show(); //panel-header 事件绑定及样式调整 navSearch.find(".panel-header").on('click', function () { $(this).siblings().toggle(); }).removeAttr("style").siblings().removeAttr("style"); navEven(); } } </script> </body> </html>
the_stack
@{ Layout = null; } <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>User Journey Player</title> <link rel="stylesheet" type="text/css" href="~/css/trace_102.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="~/js/config_102.js"></script> <script src="~/js/base64url_102.js"></script> <script> $(document).ready(function () { Config_ReadConfig(); Config_ReadLanguage(); }); var G_StatebagTruth = []; var G_StatebagLastShown = []; var G_RequestKind = ""; var G_RequestDetail = ""; var G_HtmlIdCounter = 1; var G_TokenContents = new Array(); var G_SuppressDisplay = false; // set in ProcessPredicate and Action then used in HandlerResult var G_SummaryDetails = new Array(); var G_DictionaryMoniker = "System.Collections.Generic.Dictionary"; var G_DictionaryMonikerLength = G_DictionaryMoniker.length; var G_LastCorrelationId = ""; var G_2linefeeds = "\r\n\r\n"; var G_linefeed = "\r\n"; var G_PredicateSuppressions = [ "Web.TPEngine.StateMachineHandlers.NoOpHandler", "Web.TPEngine.SSO.IsSSOSessionParticipantHandler", "Web.TPEngine.StateMachineHandlers.ShouldOrchestrationStepBeInvokedHandler", "Web.TPEngine.StateMachineHandlers.IsClaimsExchangeProtocolARedirectionHandler", "Web.TPEngine.StateMachineHandlers.IsClaimsExchangeProtocolAServiceCallHandler", "Web.TPEngine.StateMachineHandlers.IsClaimsExchangeProtocolAnApiHandler", "Web.TPEngine.StateMachineHandlers.IsPresentationTokenGeneratedHandler", "Web.TPEngine.StateMachineHandlers.CrossSiteRequestForgeryValidationHandler" ]; var G_ActionSuppressions = [ "Web.TPEngine.SSO.ResetSSOSessionHandler", "Web.TPEngine.StateMachineHandlers.RequestTracingHandler", "Web.TPEngine.StateMachineHandlers.PreSetupHandler", "Web.TPEngine.StateMachineHandlers.ClaimsExchangeCleanupHandler", "Web.TPEngine.StateMachineHandlers.SpecialCaseClaimsExchangeCleanupHandler", "Web.TPEngine.SSO.SSOSessionHandler", "Web.TPEngine.SSO.ActivateSSOSessionHandler", "Web.TPEngine.StateMachineHandlers.TransactionEndHandler", "Web.TPEngine.StateMachineHandlers.SigninSignUpApiLoadHandler" ]; var G_StatebagSuppressions = [ "$type", "MACHSTATE", "EID", "TID", "PID", "IPP", "RQCTX", "Complex-CLMS", "Complex-API_SETTINGS", "Complex-API_RESULT", "ComplexItems", "OTID", "JC", "APIURL", "CLIENTID", "CMESSAGE", "IMESSAGE" ]; var G_ExceptionsToSkip = [ "Please see the HTTP response returned by the 'Response' property of this exception for details" ]; function Clip(kind, content) { this.kind = kind; this.content = content; } function ManualRefresh() { var actionButton = document.getElementById("refreshActionButton"); actionButton.innerText = "Refreshing..."; retrieveRecording(); } function retrieveRecording() { var url = getStreamUrl(); $.get(url, processRecording, "json"); } function processStreamDelete() { G_StatebagTruth = []; G_StatebagLastShown = []; window.location.reload(true); } function processRecording(recording, status, jqXHR) { var actionButton = document.getElementById("refreshActionButton"); actionButton.innerText = "Refresh"; if (recording !== undefined && recording.value !== undefined && recording.value.length) { var journeySegments = recording.value; for (var journeySegmentIndex = 0; journeySegmentIndex < journeySegments.length; journeySegmentIndex++) { var journeySegment = journeySegments[journeySegmentIndex]; if (journeySegment.trace.message.length >= 32768) { ProcessTruncatedTrace(journeySegment); continue; } var clips = JSON.parse(journeySegment.trace.message); // hydrate the clips in a journey segment for (var clipCount = 0; clipCount < clips.length; clipCount++) { var clip = clips[clipCount]; switch (clip.Kind) { case "Headers": ProcessHeaders(clip); break; case "Transition": ProcessTransition(clip); break; case "Predicate": ProcessPredicate(clip); break; case "Action": ProcessAction(clip); break; case "HandlerResult": ProcessHandlerResult(clip); break; case "FatalException": ProcessFatalException(clip); break; default: ProcessUnrecognized(clip) break; } } } } } function GetPresentationRow(kind, rowTitle) { var table = document.getElementById("ClipTable"); var rowCount = table.rows.length; var row = table.insertRow(rowCount); row.className = kind; var cell1 = row.insertCell(0); cell1.className = "KindColumn"; cell1.innerHTML = rowTitle; var cell2 = row.insertCell(1); cell2.className = kind + "_c2"; return (cell2); } function ProcessHeaders(clip) { G_StatebagTruth = []; var cell2 = GetPresentationRow(clip.Kind, G_HeadersTitle); var headers = clip.Content; var text = ""; text += OutputValue(headers.EventInstance); if (headers.CurrentOrchestrationStep === undefined) { G_StatebagLastShown = []; G_LastCorrelationId = ""; } if (headers.CorrelationId !== G_LastCorrelationId) { text += OutputKeyValue(G_Resources.CorrelationId, headers.CorrelationId); text += OutputKeyValue(G_Resources.TenantId, headers.TenantId); text += OutputKeyValue(G_Resources.PolicyId, headers.PolicyId); text += OutputKeyValue(G_Resources.UserJourneyRecorderEndpoint, headers.UserJourneyRecorderEndpoint); G_LastCorrelationId = headers.CorrelationId; } text += renderHeaderThatIsStatebagElement("ORCH_CS", headers.CurrentOrchestrationStep); text += renderHeaderThatIsStatebagElement("TAGE", headers.TargetEntity); text += renderHeaderThatIsStatebagElement("IPP", headers.ClaimsProviderProtocolProviderType); cell2.innerHTML = text; } function renderHeaderThatIsStatebagElement(key, value) { var text = ""; if (value !== undefined) { text = OutputKeyValue(stateitemKeyFriendlyName(key), value); G_StatebagLastShown[key] = new Item(key, value); } return text; } function Item(key, value) { this.k; this.p = key; this.v = value; } function OutputKeyValue(key, value) { var result = "<p>" + key + ": " + value + "</p>\r\n"; return result; } function OutputValue(value) { var result = "<p>" + value + "</p>\r\n"; return result; } function ProcessTransition(clip) { if (Config_ShowTransitions) { var cell2 = GetPresentationRow(clip.Kind, G_Resources.Transition); var text = ""; text += OutputKeyValue(G_Resources.StateName, clip.Content.StateName); text += OutputKeyValue(G_Resources.EventName, clip.Content.EventName); cell2.innerHTML = text; } } function ProcessPredicate(clip) { G_RequestKind = clip.Kind; G_RequestDetail = clip.Content; if (Config_EnablePredicateSuppression && G_PredicateSuppressions.indexOf(clip.Content) >= 0) { G_SuppressDisplay = true; } else { G_SuppressDisplay = false; if (Config_ShowUnsuppressedRequests) { var cell2 = GetPresentationRow(clip.Kind, G_Resources.Predicate); var text = ""; text += OutputKeyValue(G_Resources.Predicate, clip.Content); cell2.innerHTML = text; } } } function ProcessAction(clip) { G_RequestKind = clip.Kind; G_RequestDetail = clip.Content; if (Config_EnableActionSuppression && G_ActionSuppressions.indexOf(clip.Content) >= 0) { G_SuppressDisplay = true; } else { G_SuppressDisplay = false; if (Config_ShowUnsuppressedRequests) { var cell2 = GetPresentationRow(clip.Kind, G_Resources.Action); var text = ""; text += OutputKeyValue(G_Resources.Action, clip.Content); cell2.innerHTML = text; } } } function ProcessHandlerResult(clip) { var statebagContent = false; if (clip.Content.Statebag !== undefined) { statebagContent = hydrateStatebagTruth(clip); } if (G_SuppressDisplay) { if (!Config_SummariesTrumpSuppressions || clip.Content.RecorderRecord === undefined) { return; } } if (SpecializedResultProcessing(G_RequestDetail, clip)) { return; } var idtext = ""; var friendlyName = handlerFriendlyName(G_RequestDetail); var resultTitle; switch (G_RequestKind) { case "Action": resultTitle = G_Resources.Result; idtext += OutputValue(friendlyName); idtext += renderHandlerDescription(G_RequestDetail); break; case "Predicate": resultTitle = G_Resources.Result; idtext += OutputValue(friendlyName); idtext += renderHandlerDescription(G_RequestDetail); break; default: resultTitle = G_Resources.UnknownRequest + G_RequestKind; break; } var text = ""; if (clip.Content.RecorderRecord !== undefined) { text += ProcessRecorderRecord(clip.Content.RecorderRecord); } if (statebagContent) { text += getPresentationDelta(clip); } if (clip.Content.Exception !== undefined) { text += "<div class=\"Exception\"><p>" + stringFormat(G_Resources.Exception, [null]) + "</p>"; text += renderException(clip.Content.Exception); text += "</div>"; } if (text.length === 0) { if (Config_EnableSuppressionOfEmptyHandlerResults) { return; } } var cell2 = GetPresentationRow(clip.Kind, resultTitle); cell2.innerHTML = idtext + text; } function ProcessRecorderRecord(recorderRecord) { var text = ""; if (recorderRecord === undefined || recorderRecord.Values === undefined) { return text; } for (var infoCount = 0; infoCount < recorderRecord.Values.length; infoCount++) { var info = recorderRecord.Values[infoCount]; switch (info.Key) { case "Validation": var details = ""; for (var count = 0; count < info.Value.Values.length; count++) { var item = info.Value.Values[count]; switch (item.Key) { case "SubmittedBy": var sender = item.Value; if (sender === "Application") { sender = G_Resources.TheApplication; } text += "<p>" + stringFormat(G_Resources.MessageSubmittedBy, [sender]) + "</p>"; break; case "ProtocolProviderType": text += "<p>" + stringFormat(G_Resources.ProtocolProviderType, [item.Value]) + "</p>"; break; case "ValidationTechnicalProfile": text += "<p>" + stringFormat(G_Resources.AdditionalValidation, [null]) + "</p>"; text += "<div class=\"ValidationTechnicalProfile\">" + ProcessRecorderRecord(item.Value) + "</div>"; } } if (details.length > 0) { var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; text += "<p class=\"ExecutingStep\">" + G_Resources.PreconditionList + ": &nbsp;<button type=\"button\" class=\"InfoButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.LogicDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; } break; case "PreconditionList": var details = ""; for (var count = 0; count < info.Value.Values.length; count++) { var key = info.Value.Values[count].Key; if (key === "Precondition") { var precondition = info.Value.Values[count].Value; var claimNames = ""; // if claims are present for (var claimCount = 0; claimCount < precondition.Values.length; claimCount++) { if (claimCount > 0) { claimNames += " " + G_Resources.AndConjunction + " "; } claimNames += precondition.Values[claimCount]; } var intent = getIntent(precondition.ExecuteActionsIf); if (precondition.Type === 0) { details += stringFormat(G_Resources.IfClaimsPresent, [intent, claimNames]) + G_linefeed; } else if (precondition.Type === 1) { details += stringFormat(G_Resources.IfClaimsEqual, [intent, claimNames]) + G_linefeed; } } else if (key === "SkippingStep") { var value = info.Value.Values[count].Value; details += stringFormat(G_Resources.SkippingStep, [value]) + G_linefeed; } } var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; text += "<p class=\"ExecutingStep\">" + G_Resources.PreconditionList + ": &nbsp;<button type=\"button\" class=\"InfoButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.LogicDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; break; case "InitiatingClaimsExchange": text += "<p>" + stringFormat(G_Resources.InitiatingClaimsExchange, [info.Value.ProtocolType, info.Value.TargetEntity, info.Value.TechnicalProfileId, info.Value.ProtocolProviderType ]) + "</p>"; break; case "InitiatingBackendClaimsExchange": text += "<p>" + stringFormat(G_Resources.InitiatingBackendClaimsExchange, [info.Value.TechnicalProfileId, info.Value.ProtocolProviderType ]) + "</p>"; break; case "OAuth1RequestInfo": var details = ""; details += stringFormat(G_Resources.OAuth1RequestInfo, [info.Value.TechnicalProfileId, info.Value.AccessTokenEndpoint]) + G_2linefeeds; details += stringFormat(G_Resources.AuthorizationEndpoint, [info.Value.AuthorizationEndpoint]) + G_2linefeeds; details += stringFormat(G_Resources.CallbackUri, [info.Value.CallbackUri]) + G_2linefeeds; details += stringFormat(G_Resources.ClientId, [info.Value.ClientId]) + G_linefeed; var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; text += "<p><button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.Request + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; break; case "MappingPartnerTypeForClaim": if (info.Value.PartnerClaimType !== info.Value.PolicyClaimType) { text += "<p>" + stringFormat(G_Resources.MappingPartnerClaim, [info.Value.PartnerClaimType, info.Value.PolicyClaimType]) + "</p>"; } break; case "MappingDefaultValueForClaim": text += "<p>" + stringFormat(G_Resources.MappingDefaultValueForClaim, [info.Value.DefaultValue, info.Value.PolicyClaimType]) + "</p>"; break; case "Response": var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = info.Value + G_linefeed; text += "<p><button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.Response + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; break; case "SkippingStep": text += "<p>" + stringFormat(G_Resources.SkippingStep, [info.Value]) + "</p>"; break; case "SendingRequest": text += "<p>" + stringFormat(G_Resources.SendingRequest, [info.Value]) + "</p>"; break; case "HomeRealmDiscovery": case "EnabledForUserJourneysTrue": case "EnabledForUserJourneysFalse": if (info.Key === "EnabledForUserJourneysFalse" || Config_ReportEnabledTechnicalProfiles) { var details = ""; var currentStep = 0; for (var count = 0; count < info.Value.Values.length; count++) { var profile = info.Value.Values[count].Value; if (count === 0) { currentStep = profile; continue; } var enabled; if (profile.EnabledResult === true) { enabled = G_Resources.IsEnabled; } else { enabled = G_Resources.IsDisabled; } details += stringFormat(G_Resources.TechnicalProfileEnabled, [profile.TechnicalProfile, enabled, profile.EnabledRule]) + G_linefeed; } var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; var explanation = stringFormat(G_Resources[info.Key], [currentStep]); text += "<p class=\"newInfo\">" + explanation + ": <button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.LogicDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; } break; case "GettingClaims": var details = ""; for (var count = 0; count < info.Value.Values.length; count++) { var key = info.Value.Values[count].Key; var mapping = info.Value.Values[count].Value; switch (key) { case "InitiatingBackendClaimsExchange": text += stringFormat(G_Resources.InitiatingBackendClaimsExchange, [mapping.TechnicalProfileId, mapping.ProtocolProviderType]) + G_linefeed; break; case "RequestEndpointUrl": details += stringFormat(G_Resources.RequestEndpointUrl, [mapping]) + G_2linefeeds; break; case "MappingFromPartnerClaimType": details += stringFormat(G_Resources.MappingFromPartnerClaimType, [mapping.PartnerClaimType, mapping.PolicyClaimType]) + G_2linefeeds; break; case "MappingToPartnerClaimType": details += stringFormat(G_Resources.MappingToPartnerClaimType, [mapping.PolicyClaimType, mapping.PartnerClaimType]) + G_2linefeeds; break; case "MappingDefaultValueForClaim": details += stringFormat(G_Resources.MappingDefaultValueForClaim, [mapping.DefaultValue, mapping.PolicyClaimType]) + G_2linefeeds; break; default: alert("Undefined key " + key); break; } } if (details.length > 0) { var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; var explanation = stringFormat(G_Resources.GettingClaimsTransformation, [null]); text += "<p class=\"newInfo\">" + explanation + ": <button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.LogicDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; } break; case "MappingToPartnerClaimType": var mapping = info.Value; text += stringFormat(G_Resources.MappingToPartnerClaimType, [mapping.PolicyClaimType, mapping.PartnerClaimType]) + G_linefeed; break; case "OutputClaimsTransformation": var details = ""; for (var count = 0; count < info.Value.Values.length; count++) { var key = info.Value.Values[count].Key; var mapping = info.Value.Values[count].Value; switch (key) { case "MappingFromPartnerClaimType": details += stringFormat(G_Resources.MappingFromPartnerClaimType, [mapping.PartnerClaimType, mapping.PolicyClaimType]) + G_linefeed; break; case "MappingDefaultValueForClaim": details += stringFormat(G_Resources.MappingDefaultValueForClaim, [mapping.DefaultValue, mapping.PolicyClaimType]) + G_linefeed; break; case "MappingPartnerTypeForClaim": break; case "ClaimsTransformation": for (var ctCount = 0; ctCount < mapping.Values.length; ctCount++) { var field = mapping.Values[ctCount]; switch (field.Key) { case "Id": details += G_linefeed + stringFormat(G_Resources.ClaimsTransformationId, [field.Value]) + G_linefeed; break; case "InputClaim": var claim = field.Value; details += stringFormat(G_Resources.TransformationInputClaim, [claim.PolicyClaimType, claim.Value]) + G_linefeed; break; case "InputParameter": var parameter = field.Value; details += stringFormat(G_Resources.TransformationInputParameter, [parameter.Id, parameter.Value]) + G_linefeed; break; case "Result": var claim = field.Value; details += stringFormat(G_Resources.TransformationResult, [claim.PolicyClaimType, claim.Value]) + G_linefeed; break; } } break; } } var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; var explanation = stringFormat(G_Resources.OutputClaimsTransformation, [null]); text += "<p class=\"newInfo\">" + explanation + ": <button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.LogicDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; break; case "ApiUiManagerInfo": var details = ""; var apiName = ""; for (var count = 0; count < info.Value.Values.length; count++) { var key = info.Value.Values[count].Key; var json = info.Value.Values[count].Value; switch (key) { case "Settings": var settings = eval("(" + json + ")"); apiName = settings === undefined || settings.api === undefined ? "Api" : settings.api; details += json + G_linefeed; break; default: break; } } var htmlId = "HtmlId_" + G_HtmlIdCounter++; G_SummaryDetails[htmlId] = details; var explanation = stringFormat(G_Resources.ApiUIManagerInfo, [apiName]); text += "<p class=\"newInfo\">" + explanation + ": <button type=\"button\" class=\"TokenButton\" onclick=\"populateSummaryDetailsDiv('" + htmlId + "');\">" + G_Resources.ApiDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; break; case "SendErrorTechnicalProfile": case "ValidationRequestUrl": case "TechnicalProfileId": case "ErrorResponseReceived": text += "<p>" + stringFormat(G_Resources[info.Key], [info.Value]) + "</p>"; break; case "Exception": text += "<div class=\"Exception\"><p>" + stringFormat(G_Resources.Exception, [null]) + "</p>"; text += renderException(info.Value); text += "</div>"; break; case "ValidationResult": break; default: alert("Unrecognized RecorderRecord Key: " + recorderRecord.Values[infoCount].Key); break; } } return text; } function renderTruncatedTraceData(data) { var text = "<p>The trace data for the Application Insights event '" + data.id + "' cannot be displayed because it is larger than 32 KB. Click the Download button to download the trace data.</p>"; text += "<ul>"; var properties = Object.getOwnPropertyNames(data.customDimensions); for (var count = 1; count < properties.length; count++) { var name = properties[count]; var value = data.customDimensions[properties[count]]; text += "<li>" + name + ": " + value + "</li>" } text += "</ul>"; return text; } function renderExceptionData(data) { var text = ""; var properties = Object.getOwnPropertyNames(data); for (var count = 1; count < properties.length; count++) { if (text === "") { text = "<ul>"; } var name = properties[count]; var value = data[properties[count]]; if (name === "Headers" && value.length > 0) { // string trailing cr/lf if (value.lastIndexOf("\r\n") == value.length - 2) { value = value.substring(0, value.length - 2); } // now replace cr/lf with li's var regex = new RegExp('\r\n', 'g'); value = value.replace(regex, "</li><li>"); value = "<ul><li>" + value + "</li></ul>"; } text += "<li>" + name + ": " + value + "</li>" } if (text !== "") { text += "</ul>" } return text; } function renderException(exception) { var text = ""; while (exception) { var exit = false; for (var count = 0; count < G_ExceptionsToSkip.length; count++) { if (~exception.Message.indexOf(G_ExceptionsToSkip[count])) { exit = true; break; } } if (exit) { break; } text += "<p>" + exception.Message + "</p>"; if (exception.Data !== undefined) { text += renderExceptionData(exception.Data); } exception = exception.Exception; } return text; } function getIntent(boolean) { var intent = ""; if (boolean === true) { intent = G_Resources.SkipStep; } else { intent = G_Resources.DontSkipStep; } return intent; } function stringFormat(format, arguments) { if (format !== undefined) { for (var count = 0; count < arguments.length; count++) { format = format.replace("{" + count.toString() + "}", arguments[count]); } } else { format = "FIX FORMAT: "; for (var count = 0; count < arguments.length; count++) { if (count > 1) { format += " - "; } format += arguments[count]; } } return format; } function SpecializedResultProcessing(requestDetail, clip) { var retval = true; switch (requestDetail) { case "Web.TPEngine.OrchestrationManager": var currentStep = G_StatebagTruth["ORCH_CS"]; G_StatebagLastShown["ORCH_CS"] = currentStep; var cell2 = GetPresentationRow("ExecutingStep", handlerFriendlyName(requestDetail)); var text = ProcessRecorderRecord(clip.Content.RecorderRecord); text += OutputKeyValue(G_Resources.ExecutingStep, currentStep.v); cell2.innerHTML = text; break; case "Web.TPEngine.StateMachineHandlers.SendRequestHandler": retval = false; break; default: retval = false; break; } return retval; } function handlerFriendlyName(name) { var result = name; if (G_HandlerFriendlyNames[name] !== undefined) { result = G_HandlerFriendlyNames[name]; } else { var offset = name.lastIndexOf("."); if (offset > 0) { result = name.substring(offset + 1, name.length); } } return result; } function stateitemKeyFriendlyName(name) { var result = G_StateitemKeyNames[name]; if (result === undefined) { result = name; } return result; } function renderHandlerDescription(name) { var text = ""; if (G_HandlerDescriptions[name] !== undefined) { text += "<p class=\"handlerDesc\">" + G_HandlerDescriptions[name] + "</p>"; } return text; } function getPresentationDelta(clip) { var newStatebagShown = []; var text = ""; var keys = Object.keys(G_StatebagTruth); for (var count = 0; count < keys.length; count++) { var itemKey = keys[count]; if (StateBagIgnoreKey(itemKey)) { continue; } var htmlClass = "newInfo"; var lastItemShown = G_StatebagLastShown[itemKey]; if (lastItemShown !== undefined && (lastItemShown.v !== undefined || lastItemShown.Value !== undefined)) { lastValueShown = lastItemShown.v; itemTruth = G_StatebagTruth[itemKey]; if (lastValueShown === itemTruth.v || lastValueShown === itemTruth.Value) { htmlClass = "seenInfo"; } } if (Config_ShowFullStatebag || htmlClass === "newInfo") { if (statebagEntryIsMsgToken(itemKey)) { var tokenType = G_StatebagTruth[itemKey].t; var htmlId = "HtmlId_" + G_HtmlIdCounter++; text += "<p class=\"newInfo\">" + tokenType + " " + G_Resources.Message + ": " + itemKey + " <button type=\"button\" class=\"TokenButton\" onclick=\"populateTokenDiv('" + htmlId + "');\">" + G_Resources.MessageDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; G_TokenContents[htmlId] = renderJson(G_StatebagTruth[itemKey].v, false); } else if (statebagEntryIsTokenStatebagItem(itemKey)) { var spacer = " "; var tokenType = G_StatebagTruth[itemKey].ContentType; if (!tokenType) { tokenType = ""; spacer = ""; } var htmlId = "HtmlId_" + G_HtmlIdCounter++; text += "<p class=\"newInfo\">" + tokenType + spacer + G_Resources.Message + " " + itemKey + " <button type=\"button\" class=\"TokenButton\" onclick=\"populateTokenDiv('" + htmlId + "');\">" + G_Resources.MessageDetail + "</button> </p>"; text += "<div id=\"" + htmlId + "\"></div>"; switch (tokenType) { case "Jwt": G_TokenContents[htmlId] = renderOAuthMessage(G_StatebagTruth[itemKey].Value); break; case "Json": G_TokenContents[htmlId] = renderJsonMessage(G_StatebagTruth[itemKey].Value); break; case "WsFed": case "Saml11": //G_TokenContents[htmlId] = renderXmlMessage(G_StatebagTruth[itemKey].Value); G_TokenContents[htmlId] = G_StatebagTruth[itemKey].Value; break; default: G_TokenContents[htmlId] = G_StatebagTruth[itemKey].Value; break; } } else { text += "<p class=\"" + htmlClass + "\">" + stateitemKeyFriendlyName(itemKey) + ": " + htmlEncode(G_StatebagTruth[itemKey].v) + "</p>"; } } newStatebagShown[itemKey] = G_StatebagTruth[itemKey]; } text += getComplexItemsRendering(clip); G_StatebagLastShown = newStatebagShown; return text; } function statebagEntryIsTokenStatebagItem(itemKey) { var tokenStatebagItem = "Web.TPEngine.TokenStateBagItem"; if (G_StatebagTruth[itemKey].$type !== undefined && G_StatebagTruth[itemKey].$type.substring(0, tokenStatebagItem.length) === tokenStatebagItem) { return true; } return false; } function populateTokenDiv(id) { var text = ""; var div = document.getElementById(id); if (div.innerHTML.length === 0) { text = "<textarea rows=\"10\" cols=\"80\" class=\"token\">" + G_TokenContents[id] + "</textarea>"; } div.innerHTML = text; } function populateSummaryDetailsDiv(id) { var text = ""; var div = document.getElementById(id); if (div.innerHTML.length === 0) { text = "<textarea rows=\"10\" cols=\"80\" class=\"SummaryDetails\">" + G_SummaryDetails[id] + "</textarea>"; } div.innerHTML = text; } function statebagEntryIsMsgToken(itemKey) { if (itemKey.substring(0, 4) === "MSG(") { return true; } else { return false; } } function hydrateStatebagTruth(clip) { var contentPresent = false; var keys = Object.keys(clip.Content.Statebag); for (var count = 0; count < keys.length; count++) { var itemKey = keys[count]; if (itemKey === "$type") { continue; } G_StatebagTruth[itemKey] = clip.Content.Statebag[itemKey]; contentPresent = true; } return contentPresent; } function getComplexItemsRendering(clip) { var itemText = ""; var complexItemNames = Object.keys(G_ComplexStatebagItems); for (var itemCount = 0; itemCount < complexItemNames.length; itemCount++) { var itemName = complexItemNames[itemCount]; var item = clip.Content.Statebag[itemName]; if (item === undefined) { continue; } var itemLastShownJson = JSON.stringify(G_StatebagLastShown[itemName]); if (itemLastShownJson === JSON.stringify(item)) { continue; } var itemTitle = G_ComplexStatebagItems[itemName]; var fieldKeyNames = Object.keys(item); if (fieldKeyNames.length > 1) { itemText += "<div class=\"" + itemName + "\"><p>" + itemTitle + "</p>"; itemText += renderDictionary(item, itemName); itemText += "</div>"; } } return itemText; } function isFieldADictionary(field) { return typeof field === "object" && field["$type"].substring(0, G_DictionaryMonikerLength) === G_DictionaryMoniker; } function renderDictionary(dictionary, dictionaryName) { var text = ""; var dictionaryKeyNames = Object.keys(dictionary); if (dictionaryKeyNames.length > 1) { text = "<ul class=\"" + dictionaryName + "\">"; for (var keyCount = 1; keyCount < dictionaryKeyNames.length; keyCount++) { var dictionaryKey = dictionaryKeyNames[keyCount]; var field = dictionary[dictionaryKey]; if (isFieldADictionary(field)) { text += renderDictionary(field, dictionaryKey); } else { text += "<li>" + dictionaryKey + ": " + field + "</li>"; } } text += "</ul>"; } return text; } function htmlEncode(value) { //create a in-memory div, set it's inner text(which jQuery automatically encodes) //then grab the encoded contents back out. The div never exists on the page. return $('<div/>').text(value).html(); } function ProcessFatalException(clip) { var cell2 = GetPresentationRow(clip.Kind, G_Resources.FatalException); var exception = clip.Content.Exception; var exceptionText = renderException(exception); exceptionText = "<div class=\"ExceptionDetail\">" + exceptionText + OutputKeyValue(G_Resources.Time, clip.Content.Time) + "</div>"; cell2.innerHTML = exceptionText; } function ProcessUnrecognized(clip) { var cell2 = GetPresentationRow("Unrecognized", G_Resources.UnknownTrace); var kind = "Empty"; if (clip.Kind !== undefined) { kind = clip.Kind; } cell2.innerHTML = "Clip Kind: " + kind; } function ProcessTruncatedTrace(e) { var cell2 = GetPresentationRow("TraceWarning", G_Resources.JourneySegment); var eventText = renderTruncatedTraceData(e); eventText = "<div class=\"WarningDetail\">" + eventText + "</div>"; cell2.innerHTML = eventText; } function StateBagIgnoreKey(key) { return G_StatebagSuppressions.indexOf(key) >= 0; } function ConfigureReader() { document.location = "config"; } function DownloadStream() { var url = getStreamUrl(); $.get(url, processDownloadStream, "text"); } function processDownloadStream(recording, status, jqXHR) { browserDownload(recording, "recording.json", "application/json"); } function browserDownload(strData, strFileName, strMimeType) { var D = document, a = D.createElement("a"); strMimeType = strMimeType || "application/octet-stream"; if (navigator.msSaveBlob) { // IE10 return navigator.msSaveBlob(new Blob([strData], { type: strMimeType }), strFileName); } /* end if(navigator.msSaveBlob) */ if ('download' in a) { //html5 A[download] a.href = "data:" + strMimeType + "," + encodeURIComponent(strData); a.setAttribute("download", strFileName); a.innerHTML = "downloading..."; D.body.appendChild(a); setTimeout(function () { a.click(); D.body.removeChild(a); }, 66); return true; } /* end if('download' in a) */ //do iframe dataURL download (old ch+FF): var f = D.createElement("iframe"); D.body.appendChild(f); f.src = "data:" + strMimeType + "," + encodeURIComponent(strData); setTimeout(function () { D.body.removeChild(f); }, 333); return true; } /* end browserDownload() */ </script> </head> <body> <button id="refreshActionButton" class="InfoButton" onclick="ManualRefresh();">Refresh</button> <button id="downloadButton" class="InfoButton" onclick="DownloadStream();">Download</button> <button id="configureButton" class="InfoButton" onclick="ConfigureReader();">Configure</button> <table border="0" width="100%" cellspacing="15" id="ClipTable"></table> </body> </html>
the_stack
var publishingError = false; /////////////////////////////////////////////////////////////////////////////// // Support function for comparing cake version support /////////////////////////////////////////////////////////////////////////////// public bool IsSupportedCakeVersion(string supportedVersion, string currentVersion) { var onePartSupported = Version.Parse(supportedVersion).ToString(1); var onePartCurrent = Version.Parse(currentVersion).ToString(1); return onePartCurrent == onePartSupported; } /////////////////////////////////////////////////////////////////////////////// // TEARDOWN /////////////////////////////////////////////////////////////////////////////// Teardown<BuildVersion>((context, buildVersion) => { Information("Starting Teardown..."); if (BuildParameters.PublishReleasePackagesWasSuccessful) { if (!BuildParameters.IsLocalBuild && !BuildParameters.IsPullRequest && BuildParameters.IsMainRepository && (BuildParameters.BranchType == BranchType.Master || ((BuildParameters.BranchType == BranchType.Release || BuildParameters.BranchType == BranchType.HotFix) && BuildParameters.ShouldNotifyBetaReleases)) && BuildParameters.IsTagged && !BuildParameters.IsRunningIntegrationTests) { if (BuildParameters.CanPostToTwitter && BuildParameters.ShouldPostToTwitter) { SendMessageToTwitter(string.Format(BuildParameters.TwitterMessage, buildVersion.Version, BuildParameters.Title)); } if (BuildParameters.CanPostToGitter && BuildParameters.ShouldPostToGitter) { SendMessageToGitterRoom(string.Format(BuildParameters.GitterMessage, buildVersion.Version, BuildParameters.Title)); } if (BuildParameters.CanPostToMicrosoftTeams && BuildParameters.ShouldPostToMicrosoftTeams) { SendMessageToMicrosoftTeams(string.Format(BuildParameters.MicrosoftTeamsMessage, buildVersion.Version, BuildParameters.Title)); } if (BuildParameters.CanSendEmail && BuildParameters.ShouldSendEmail && !string.IsNullOrEmpty(BuildParameters.EmailRecipient)) { var subject = $"Continuous Integration Build of {BuildParameters.Title} completed successfully"; var message = new StringBuilder(); message.AppendLine(string.Format(BuildParameters.StandardMessage, buildVersion.Version, BuildParameters.Title) + "<br/>"); message.AppendLine("<br/>"); message.AppendLine($"<strong>Name</strong>: {BuildParameters.Title}<br/>"); message.AppendLine($"<strong>Version</strong>: {buildVersion.SemVersion}<br/>"); message.AppendLine($"<strong>Configuration</strong>: {BuildParameters.Configuration}<br/>"); message.AppendLine($"<strong>Target</strong>: {BuildParameters.Target}<br/>"); message.AppendLine($"<strong>Cake version</strong>: {buildVersion.CakeVersion}<br/>"); message.AppendLine($"<strong>Cake.Recipe version</strong>: {BuildMetaData.Version}<br/>"); SendEmail(subject, message.ToString(), BuildParameters.EmailRecipient, BuildParameters.EmailSenderName, BuildParameters.EmailSenderAddress); } } } if(!context.Successful) { if (!BuildParameters.IsLocalBuild && BuildParameters.IsMainRepository && !BuildParameters.IsRunningIntegrationTests) { if (BuildParameters.CanPostToSlack && BuildParameters.ShouldPostToSlack) { SendMessageToSlackChannel("Continuous Integration Build of " + BuildParameters.Title + " just failed :-("); } if (BuildParameters.CanSendEmail && BuildParameters.ShouldSendEmail && !string.IsNullOrEmpty(BuildParameters.EmailRecipient)) { var subject = $"Continuous Integration Build of {BuildParameters.Title} failed"; var message = context.ThrownException.ToString().Replace(System.Environment.NewLine, "<br/>"); SendEmail(subject, message, BuildParameters.EmailRecipient, BuildParameters.EmailSenderName, BuildParameters.EmailSenderAddress); } } } // Clear nupkg files from tools directory if ((!BuildParameters.IsLocalBuild || BuildParameters.ShouldDeleteCachedFiles) && DirectoryExists(Context.Environment.WorkingDirectory.Combine("tools"))) { Information("Deleting nupkg files..."); var nupkgFiles = GetFiles(Context.Environment.WorkingDirectory.Combine("tools") + "/**/*.nupkg"); DeleteFiles(nupkgFiles); } Information("Finished running tasks."); }); /////////////////////////////////////////////////////////////////////////////// // TASK DEFINITIONS /////////////////////////////////////////////////////////////////////////////// BuildParameters.Tasks.ShowInfoTask = Task("Show-Info") .Does(() => { Information("Build Platform: {0}", BuildParameters.Platform); Information("Target: {0}", BuildParameters.Target); Information("Configuration: {0}", BuildParameters.Configuration); Information("PrepareLocalRelease: {0}", BuildParameters.PrepareLocalRelease); Information("ShouldDownloadMilestoneReleaseNotes: {0}", BuildParameters.ShouldDownloadMilestoneReleaseNotes); Information("ShouldDownloadFullReleaseNotes: {0}", BuildParameters.ShouldDownloadFullReleaseNotes); Information("IsLocalBuild: {0}", BuildParameters.IsLocalBuild); Information("IsPullRequest: {0}", BuildParameters.IsPullRequest); Information("IsMainRepository: {0}", BuildParameters.IsMainRepository); Information("IsTagged: {0}", BuildParameters.IsTagged); Information("Solution FilePath: {0}", MakeAbsolute((FilePath)BuildParameters.SolutionFilePath)); Information("Solution DirectoryPath: {0}", MakeAbsolute((DirectoryPath)BuildParameters.SolutionDirectoryPath)); Information("Source DirectoryPath: {0}", MakeAbsolute(BuildParameters.SourceDirectoryPath)); Information("Build DirectoryPath: {0}", MakeAbsolute(BuildParameters.Paths.Directories.Build)); }); BuildParameters.Tasks.CleanTask = Task("Clean") .IsDependentOn("Show-Info") .IsDependentOn("Print-CI-Provider-Environment-Variables") .Does(() => { Information("Cleaning..."); CleanDirectories(BuildParameters.Paths.Directories.ToClean); }); BuildParameters.Tasks.RestoreTask = Task("Restore") .Does(() => { Information("Restoring {0}...", BuildParameters.SolutionFilePath); RequireToolNotRegistered(ToolSettings.NuGetTool, new[] { "nuget", "nuget.exe" }, () => { NuGetRestore( BuildParameters.SolutionFilePath, new NuGetRestoreSettings { Source = BuildParameters.NuGetSources }); }); }); BuildParameters.Tasks.DotNetCoreRestoreTask = Task("DotNetCore-Restore") .Does<BuildVersion>((context, buildVersion) => { // We need to clone the settings class, so we don't // add additional properties to every other task. var msBuildSettings = new DotNetCoreMSBuildSettings(); foreach (var kv in context.Data.Get<DotNetCoreMSBuildSettings>().Properties) { string value = string.Join(" ", kv.Value); msBuildSettings.WithProperty(kv.Key, value); } msBuildSettings.WithProperty("Configuration", BuildParameters.Configuration); DotNetCoreRestore(BuildParameters.SolutionFilePath.FullPath, new DotNetCoreRestoreSettings { Sources = BuildParameters.NuGetSources, MSBuildSettings = msBuildSettings, PackagesDirectory = BuildParameters.RestorePackagesDirectory }); }); BuildParameters.Tasks.BuildTask = Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does<BuildVersion>((context, buildVersion) => { Information("Building {0}", BuildParameters.SolutionFilePath); if (BuildParameters.BuildAgentOperatingSystem == PlatformFamily.Windows || Context.Tools.Resolve("msbuild") != null) { var msbuildSettings = new MSBuildSettings() .SetPlatformTarget(ToolSettings.BuildPlatformTarget) .UseToolVersion(ToolSettings.BuildMSBuildToolVersion) .WithProperty("TreatWarningsAsErrors", BuildParameters.TreatWarningsAsErrors.ToString()) .WithTarget("Build") .SetMaxCpuCount(ToolSettings.MaxCpuCount) .SetConfiguration(BuildParameters.Configuration); msbuildSettings.ArgumentCustomization = args => args.Append(string.Format("/logger:BinaryLogger,\"{0}\";\"{1}\"", context.Tools.Resolve("Cake.Issues.MsBuild*/**/StructuredLogger.dll"), BuildParameters.Paths.Files.BuildBinLogFilePath)); // This is used in combination with SourceLink to ensure a deterministic // package is generated if(BuildParameters.ShouldUseDeterministicBuilds) { msbuildSettings.WithProperty("ContinuousIntegrationBuild", "true"); } MSBuild(BuildParameters.SolutionFilePath, msbuildSettings); // Pass path to MsBuild log file to Cake.Issues.Recipe IssuesParameters.InputFiles.MsBuildBinaryLogFilePath = BuildParameters.Paths.Files.BuildBinLogFilePath; } else { var xbuildSettings = new XBuildSettings() .SetConfiguration(BuildParameters.Configuration) .WithTarget("Build") .WithProperty("TreatWarningsAsErrors", "true"); XBuild(BuildParameters.SolutionFilePath, xbuildSettings); } CopyBuildOutput(buildVersion); }); BuildParameters.Tasks.DotNetCoreBuildTask = Task("DotNetCore-Build") .IsDependentOn("Clean") .IsDependentOn("DotNetCore-Restore") .Does<BuildVersion>((context, buildVersion) => { Information("Building {0}", BuildParameters.SolutionFilePath); // We need to clone the settings class, so we don't // add additional properties to every other task. var msBuildSettings = new DotNetCoreMSBuildSettings(); foreach (var kv in context.Data.Get<DotNetCoreMSBuildSettings>().Properties) { string value = string.Join(" ", kv.Value); msBuildSettings.WithProperty(kv.Key, value); } msBuildSettings.WithLogger("BinaryLogger," + context.Tools.Resolve("Cake.Issues.MsBuild*/**/StructuredLogger.dll"), "", BuildParameters.Paths.Files.BuildBinLogFilePath.ToString()); DotNetCoreBuild(BuildParameters.SolutionFilePath.FullPath, new DotNetCoreBuildSettings { Configuration = BuildParameters.Configuration, MSBuildSettings = msBuildSettings, NoRestore = true }); // We set this here, so we won't have a failure in case this task is never called IssuesParameters.InputFiles.MsBuildBinaryLogFilePath = BuildParameters.Paths.Files.BuildBinLogFilePath; CopyBuildOutput(buildVersion); }); public void CopyBuildOutput(BuildVersion buildVersion) { Information("Copying build output..."); foreach (var project in ParseSolution(BuildParameters.SolutionFilePath).GetProjects()) { // There is quite a bit of duplication in this function, that really needs to be tidied Upload Information("Input BuildPlatformTarget: {0}", ToolSettings.BuildPlatformTarget.ToString()); var platformTarget = ToolSettings.BuildPlatformTarget == PlatformTarget.MSIL ? "AnyCPU" : ToolSettings.BuildPlatformTarget.ToString(); Information("Using BuildPlatformTarget: {0}", platformTarget); var parsedProject = ParseProject(project.Path, BuildParameters.Configuration, platformTarget); if (project.Path.FullPath.ToLower().Contains("wixproj")) { Warning("Skipping wix project"); continue; } if (project.Path.FullPath.ToLower().Contains("shproj")) { Warning("Skipping shared project"); continue; } if (parsedProject.OutputPaths.FirstOrDefault() == null || parsedProject.RootNameSpace == null || parsedProject.OutputType == null) { Information("OutputPath: {0}", parsedProject.OutputPaths.FirstOrDefault()); Information("RootNameSpace: {0}", parsedProject.RootNameSpace); Information("OutputType: {0}", parsedProject.OutputType); throw new Exception(string.Format("Unable to parse project file correctly: {0}", project.Path)); } // If the project is an exe, then simply copy all of the contents to the correct output folder if (!parsedProject.IsLibrary()) { Information("Project has an output type of exe: {0}", parsedProject.RootNameSpace); var outputFolder = BuildParameters.Paths.Directories.PublishedApplications.Combine(parsedProject.RootNameSpace); EnsureDirectoryExists(outputFolder); // If .NET SDK project, copy using dotnet publish for each target framework // Otherwise just copy if (parsedProject.IsVS2017ProjectFormat) { var msBuildSettings = Context.Data.Get<DotNetCoreMSBuildSettings>(); foreach (var targetFramework in parsedProject.NetCore.TargetFrameworks) { DotNetCorePublish(project.Path.FullPath, new DotNetCorePublishSettings { OutputDirectory = outputFolder.Combine(targetFramework), Framework = targetFramework, Configuration = BuildParameters.Configuration, MSBuildSettings = msBuildSettings, NoRestore = true, NoBuild = true }); } } else { CopyMsBuildProjectOutput(outputFolder, parsedProject); } continue; } // Now we need to test for whether this is a unit test project. // If this is found, move the output to the unit test folder, otherwise, simply copy to normal output folder if (!BuildParameters.IsDotNetCoreBuild) { Information("Not a .Net Core Build"); } else { Information("Is a .Net Core Build"); } if (parsedProject.IsLibrary() && (parsedProject.HasPackage("xunit") || parsedProject.HasReference("xunit.core"))) { Information("Project has an output type of library and is an xUnit Test Project: {0}", parsedProject.RootNameSpace); CopyMsBuildProjectOutput(BuildParameters.Paths.Directories.PublishedxUnitTests, parsedProject); } else if (parsedProject.IsLibrary() && (parsedProject.HasPackage("nunit") || parsedProject.HasReference("nunit.framework"))) { Information("Project has an output type of library and is a NUnit Test Project: {0}", parsedProject.RootNameSpace); CopyMsBuildProjectOutput(BuildParameters.Paths.Directories.PublishedNUnitTests, parsedProject); } else if (parsedProject.IsLibrary() && parsedProject.IsMSTestProject()) { // We will use vstest.console.exe by default for MSTest Projects Information("Project has an output type of library and is an MSTest Project: {0}", parsedProject.RootNameSpace); CopyMsBuildProjectOutput(BuildParameters.Paths.Directories.PublishedVSTestTests, parsedProject); } else { Information("Project has an output type of library: {0}", parsedProject.RootNameSpace); CopyMsBuildProjectOutput(BuildParameters.Paths.Directories.PublishedLibraries, parsedProject); } } } public void CopyMsBuildProjectOutput(DirectoryPath outputBase, CustomProjectParserResult parsedProject) { if (parsedProject.IsVS2017ProjectFormat) { foreach (var outputPath in parsedProject.OutputPaths) { var outputFolder = outputBase.Combine(parsedProject.RootNameSpace).Combine(outputPath.GetDirectoryName()); EnsureDirectoryExists(outputFolder); var files = GetFiles(outputPath + "/**/*"); if (files.Any()) { CopyFiles(files, outputFolder, true); } else { Warning("No files were found in the project output directory: '{0}'", outputPath); } } } else { var outputFolder = outputBase.Combine(parsedProject.RootNameSpace); EnsureDirectoryExists(outputFolder); var outputPath = parsedProject.OutputPaths.First().FullPath; var files = GetFiles(outputPath + "/**/*"); if (files.Any()) { CopyFiles(files, outputFolder, true); } else { Warning("No files were found in the project output directory: '{0}'", outputPath); } } } BuildParameters.Tasks.PackageTask = Task("Package") .IsDependentOn("Export-Release-Notes"); BuildParameters.Tasks.DefaultTask = Task("Default") .IsDependentOn("Package") // Run issues task from Cake.Issues.Recipe by default. .IsDependentOn("Issues"); BuildParameters.Tasks.UploadArtifactsTask = Task("Upload-Artifacts") .IsDependentOn("Package") .WithCriteria(() => !BuildParameters.IsLocalBuild) .WithCriteria(() => DirectoryExists(BuildParameters.Paths.Directories.NuGetPackages) || DirectoryExists(BuildParameters.Paths.Directories.ChocolateyPackages)) .Does(() => { var artifacts = GetFiles(BuildParameters.Paths.Directories.Packages + "/*") + GetFiles(BuildParameters.Paths.Directories.NuGetPackages + "/*") + GetFiles(BuildParameters.Paths.Directories.ChocolateyPackages + "/*") + GetFiles(BuildParameters.Paths.Directories.TestCoverage + "/coverlet/*.xml"); if (FileExists(BuildParameters.Paths.Files.TestCoverageOutputFilePath)) { artifacts += BuildParameters.Paths.Files.TestCoverageOutputFilePath; } foreach (var artifact in artifacts) { BuildParameters.BuildProvider.UploadArtifact(artifact); } }); BuildParameters.Tasks.ContinuousIntegrationTask = Task("CI") // Run issues task from Cake.Issues.Recipe by default. .IsDependentOn("Upload-Artifacts") .IsDependentOn("Issues") .IsDependentOn("Publish-PreRelease-Packages") .IsDependentOn("Publish-Release-Packages") .IsDependentOn("Publish-GitHub-Release") .IsDependentOn("Publish-Documentation") .Finally(() => { if (publishingError) { throw new Exception("An error occurred during the publishing of " + BuildParameters.Title + ". All publishing tasks have been attempted."); } }); BuildParameters.Tasks.UploadCoverageReportTask = Task("Upload-Coverage-Report") .IsDependentOn("Upload-Coveralls-Report") .IsDependentOn("Upload-Codecov-Report"); BuildParameters.Tasks.ReleaseNotesTask = Task("ReleaseNotes") .IsDependentOn("Create-Release-Notes"); BuildParameters.Tasks.LabelsTask = Task("Labels") .IsDependentOn("Create-Default-Labels"); BuildParameters.Tasks.ClearCacheTask = Task("ClearCache") .IsDependentOn("Clear-AppVeyor-Cache"); BuildParameters.Tasks.PreviewTask = Task("Preview") .IsDependentOn("Preview-Documentation"); BuildParameters.Tasks.PublishDocsTask = Task("PublishDocs") .IsDependentOn("Force-Publish-Documentation"); /////////////////////////////////////////////////////////////////////////////// // EXECUTION /////////////////////////////////////////////////////////////////////////////// public Builder Build { get { return new Builder(target => RunTarget(target)); } } public class Builder { private Action<string> _action; public Builder(Action<string> action) { _action = action; } public void Run() { BuildParameters.IsDotNetCoreBuild = false; BuildParameters.IsNuGetBuild = false; SetupTasks(BuildParameters.IsDotNetCoreBuild); _action(BuildParameters.Target); } public void RunDotNetCore() { BuildParameters.IsDotNetCoreBuild = true; BuildParameters.IsNuGetBuild = false; SetupTasks(BuildParameters.IsDotNetCoreBuild); _action(BuildParameters.Target); } public void RunNuGet() { BuildParameters.Tasks.PackageTask.IsDependentOn("Create-NuGet-Package"); BuildParameters.IsDotNetCoreBuild = false; BuildParameters.IsNuGetBuild = true; _action(BuildParameters.Target); } private static void SetupTasks(bool isDotNetCoreBuild) { var prefix = isDotNetCoreBuild ? "DotNetCore-" : ""; BuildParameters.Tasks.CreateNuGetPackagesTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.CreateChocolateyPackagesTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.TestTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.DupFinderTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.InspectCodeTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.PackageTask.IsDependentOn("Analyze"); BuildParameters.Tasks.PackageTask.IsDependentOn("Test"); BuildParameters.Tasks.PackageTask.IsDependentOn("Create-NuGet-Packages"); BuildParameters.Tasks.PackageTask.IsDependentOn("Create-Chocolatey-Packages"); BuildParameters.Tasks.UploadCodecovReportTask.IsDependentOn("Test"); BuildParameters.Tasks.UploadCoverallsReportTask.IsDependentOn("Test"); BuildParameters.Tasks.ContinuousIntegrationTask.IsDependentOn("Upload-Coverage-Report"); if (!isDotNetCoreBuild) { if (BuildParameters.TransifexEnabled) { BuildParameters.Tasks.BuildTask.IsDependentOn("Transifex-Pull-Translations"); } BuildParameters.Tasks.TestMSTestTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.TestNUnitTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.TestVSTestTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.TestxUnitTask.IsDependentOn(prefix + "Build"); BuildParameters.Tasks.GenerateLocalCoverageReportTask.IsDependentOn("Test-MSTest"); BuildParameters.Tasks.GenerateLocalCoverageReportTask.IsDependentOn("Test-NUnit"); BuildParameters.Tasks.GenerateLocalCoverageReportTask.IsDependentOn("Test-VSTest"); BuildParameters.Tasks.GenerateLocalCoverageReportTask.IsDependentOn("Test-xUnit"); BuildParameters.Tasks.TestTask.IsDependentOn("Generate-FriendlyTestReport"); BuildParameters.Tasks.TestTask.IsDependentOn("Generate-LocalCoverageReport"); } else { if (BuildParameters.TransifexEnabled) { BuildParameters.Tasks.DotNetCoreBuildTask.IsDependentOn("Transifex-Pull-Translations"); } BuildParameters.Tasks.GenerateLocalCoverageReportTask.IsDependentOn(prefix + "Test"); BuildParameters.Tasks.TestTask.IsDependentOn("Generate-LocalCoverageReport"); BuildParameters.Tasks.PackageTask.IsDependentOn(prefix + "Pack"); } } }
the_stack
@{ ViewBag.title = "数据字典管理"; } <script src="~/js/vue/vue.min.js"></script> <div class="wrapper wrapper-content "> <div class="row" id="app"> <div class="col-sm-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>@ViewBag.Title</h5> <div class="ibox-tools"> </div> </div> <div class="ibox-content"> <div class="panel panel-default"> <div class="panel-heading">筛选条件</div> <div class="panel-body"> <form id="formSearch" class="form-horizontal form-inline" onsubmit="return doSearch(); return false;"> <div> <label class="control-label">关键字:</label> <input type="text" placeholder="Key关键字" name="keyword" id="keyword" class="form-control"> <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary" onclick="doSearch();">查询</button> </div> </form> </div> </div> <div id="toolbar" class="btn-group"> <button id="btn_add" type="button" class="btn btn-outline btn-default" onclick="app.getDataDictionary(0)"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增 </button> </div> <table id="tb_departments"></table> <script> $(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); //2.初始化Button的点击事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); }); function doSearch() { var params = $('#tb_departments').bootstrapTable('getOptions'); //console.log(params); params.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 page: (params.offset / params.limit) + 1, //页码 keyword: $("#keyword").val(), }; return temp; } $('#tb_departments').bootstrapTable('refresh', params); } var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#tb_departments').bootstrapTable({ url: '/AdminCP/DataDictionary/GetDataDictionaryList', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: false, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 25, //每页的记录行数(*) pageList: [10, 25, 50, 100], //可供选择的每页的行数(*) search: false, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 height: 0, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "id", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 columns: [{ field: 'id', title: 'ID' }, { field: 'key', title: '字典Key' }, { field: 'description', title: '说明' }, { field: 'rank', title: '排序' }, { field: 'addTime', title: '添加时间' }, { field: 'id', title: '操作', formatter: 'actionFormatter', width:215 } ] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 page: (params.offset / params.limit) + 1, //页码 kid: $("#kid").val(), keyword: $("#keyword").val(), isshowsub: $("#isshowsub").prop("checked") ? 1 : 0 }; return temp; }; return oTableInit; }; function actionFormatter(value, row, index) { return [ '<a href="javascript:;" class="btn btn-xs btn-primary" title="编辑" onclick="app.getDataDictionary(' + value + ')"><i class="fa fa-edit"></i> 编辑</a>', '<a href="javascript:;" class="btn btn-xs btn-success m-l-xs" title="编辑" onclick="app.getDataDictionaryDetail(' + value + ')"><i class="fa fa-edit"></i> 管理字典值</a>', '<a href="javascript:;" class="btn btn-xs btn-danger m-l-xs" title="删除" onclick="doDel(\'/AdminCP/DataDictionary/DelDataDictionary\',' + value + ');"><i class="fa fa-close"></i> 删除</a>', ].join(''); } var ButtonInit = function () { var oInit = new Object(); var postdata = {}; oInit.Init = function () { //初始化页面上面的按钮事件 }; return oInit; }; </script> </div> </div> <div id="myModal" class="modal fade" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> <div class="row form-horizontal"> <div class="col-sm-12"> <h3 class="m-t-none m-b">{{model.id==0?'添加新数据字典':'编辑数据字典'}}</h3> <div class="row"> <div class="form-group"> <label class="col-sm-3 control-label">字典Key:</label> <div class="col-sm-8"> <input v-model="model.key" type="text" class="form-control" maxlength="250" placeholder="字典Key,请填写英文" aria-required="true"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">字典说明:</label> <div class="col-sm-8"> <input v-model="model.description" type="text" class="form-control" maxlength="250" placeholder="字典说明" aria-required="true"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">字典排序:</label> <div class="col-sm-8"> <input v-model="model.rank" type="number" class="form-control" maxlength="250" placeholder="字典排序,越小越前,仅后台" aria-required="true"> </div> </div> <div class="form-group"> <div class="col-sm-5 col-sm-offset-3"> <input type="hidden" v-model="model.id" /> <button class="btn btn-primary" type="button" v-on:click="doSaveDataDictionary"><i class="fa fa-save"></i> 确定 </button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-sm-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>字典值详情</h5> <div class="ibox-tools"> </div> </div> <div class="ibox-content"> <div v-show="showDetail"> <div id="toolbar" class="btn-group"> <button id="btn_add" type="button" class="btn btn-outline btn-default" v-on:click="addDetail"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增 </button> </div> <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>值</th> <th>标签</th> <th>排序</th> <th>是否默认</th> <th>说明</th> <th>添加时间</th> <th style="width:125px">操作</th> </tr> </thead> <tbody> <tr v-for="(item,index) in detailList"> <td>{{item.id}}</td> <td>{{item.val}}</td> <td>{{item.title}}</td> <td>{{item.rank}}</td> <td>{{item.isDefault==1?'是':'否'}}</td> <td>{{item.description}}</td> <td>{{item.addTime}}</td> <td> <button class="btn btn-primary btn-xs" v-on:click="doEditDetail(item)"><i class="fa fa-edit"></i> 编辑</button> <button class="btn btn-danger btn-xs" v-on:click="doDelDetail(item.id)"><i class="fa fa-close"></i> 删除</button> </td> </tr> <tr v-if="detailList.length<=0"> <td colspan="8">暂无记录</td> </tr> </tbody> </table> <div id="detailModal" class="modal fade" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> <div class="row form-horizontal"> <div class="col-sm-12"> <h3 class="m-t-none m-b">{{detailModel.id==0?'添加新数据字典值':'编辑数据字典值'}}</h3> <div class="row"> <div class="form-group"> <label class="col-sm-3 control-label">字典值(存放数据库):</label> <div class="col-sm-8"> <input v-model="detailModel.val" type="text" class="form-control" maxlength="250" placeholder="字典值(存放数据库)" aria-required="true"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">字典值标签名称:</label> <div class="col-sm-8"> <input v-model="detailModel.title" type="text" class="form-control" maxlength="250" placeholder="字典值标签名称(显示)" aria-required="true"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">是否默认值:</label> <div class="col-sm-8"> <input type="radio" id="y" value="1" v-model="detailModel.isDefault"> <label for="y">是(将默认选中)</label> <input type="radio" id="n" value="0" v-model="detailModel.isDefault"> <label for="n">否</label> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">字典值排序:</label> <div class="col-sm-8"> <input v-model="detailModel.rank" type="number" class="form-control" maxlength="250" placeholder="字典排序,越小越前" aria-required="true"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">字典值备注:</label> <div class="col-sm-8"> <input v-model="detailModel.description" type="text" class="form-control" maxlength="250" placeholder="字典说明" aria-required="true"> </div> </div> <div class="form-group"> <div class="col-sm-5 col-sm-offset-3"> <input type="hidden" v-model="detailModel.id" /> <button class="btn btn-primary" type="button" v-on:click="doSaveDataDictionaryDetail"><i class="fa fa-save"></i> 确定 </button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <script> var app = new Vue({ el: '#app', data: { model: { key: '', id: 0, rank: 0, description:''}, optTitle: '添加字典', showDetail: false, detailList: [], detailModel: { dataDictionaryId: 0, id: 0, val: '', title: '', description: '', rank: 0, isDefault:0}, dataDictId:0 }, methods: { getDataDictionary: function (id) { //console.log('获取详情:', id); let that = this; if (id == 0) { this.model = { key: '', id: 0, rank: 0, description: '' }; $("#myModal").modal('show'); return; } var loading = layer.load(0, { shade: [0.2, '#000'] //0.1透明度的背景 }); $.ajax({ type: "POST", url: "/AdminCP/DataDictionary/GetDataDictionary", data: {id:id}, dataType: "JSON", success: function (data) { if (data.status == "success") { layer.close(loading); that.model = data.detail; $("#myModal").modal('show'); } else { layer.close(loading); layer.alert(data.message, { icon: 2 }); } }, error: function () { layer.close(loading); layer.alert('执行错误,请联系管理员!', { icon: 2 }); } }); }, doSaveDataDictionary: function () { var that = this; if (!that.model.key) { alert('请输入字典Key!'); return; } var loading = layer.load(0, { shade: [0.2, '#000'] //0.1透明度的背景 }); $.ajax({ type: "POST", url: "/AdminCP/DataDictionary/DoSaveDataDictionary", data: that.model, dataType: "JSON", success: function (data) { if (data.status == "success") { layer.close(loading); layer.msg(data.message, { time: 1000 //2秒关闭(如果不配置,默认是3秒) }, function () { $('#myModal').modal('hide') $("#tb_departments").bootstrapTable('refresh'); }); } else { layer.close(loading); layer.alert(data.message, { icon: 2 }); } }, error: function () { layer.close(loading); layer.alert('执行错误,请联系管理员!', { icon: 2 }); } }); }, getDataDictionaryDetail: function (id) { var that = this; var loading = layer.load(0, { shade: [0.2, '#000'] //0.1透明度的背景 }); $.ajax({ type: "POST", url: "/AdminCP/DataDictionary/GetDataDictionaryDetail", data: { id: id }, dataType: "JSON", success: function (data) { if (data.status == "success") { layer.close(loading); that.showDetail = true; that.detailList = data.detail; that.dataDictId = id; } else { layer.close(loading); layer.alert(data.message, { icon: 2 }); } }, error: function () { layer.close(loading); layer.alert('执行错误,请联系管理员!', { icon: 2 }); } }); }, doEditDetail: function (item) { this.detailModel = item; $("#detailModal").modal('show'); }, doDelDetail: function (id) { var that = this; top.layer.confirm('确认要删除当前记录?此操作不可恢复!', { icon: 3, title: '系统提示', btn: ['确定', '取消 '] //按钮 }, function () { var loading = layer.load(0, { shade: [0.2, '#000'] //0.1透明度的背景 }); $.ajax({ type: "POST", url: "/AdminCP/DataDictionary/DelDataDictionaryDetail", data: { id: id }, dataType: "JSON", success: function (data) { if (data.status == "success") { layer.close(loading); that.getDataDictionaryDetail(that.dataDictId); } else { layer.close(loading); layer.alert(data.message, { icon: 2 }); } }, error: function () { layer.close(loading); layer.alert('执行错误,请联系管理员!', { icon: 2 }); } }); }, function () { }); }, addDetail:function() { this.detailModel = { dataDictionaryId: this.dataDictId, id: 0, val: '', title: '', description: '', rank: 0, isDefault: 0 }; $("#detailModal").modal('show'); return; }, doSaveDataDictionaryDetail: function () { var that = this; if (!that.detailModel.val) { alert('请输入字典值!'); return; } if (!that.detailModel.title) { alert('请输入字典值标签名称!'); return; } var loading = layer.load(0, { shade: [0.2, '#000'] //0.1透明度的背景 }); $.ajax({ type: "POST", url: "/AdminCP/DataDictionary/DoSaveDataDictionaryDetail", data: that.detailModel, dataType: "JSON", success: function (data) { if (data.status == "success") { layer.close(loading); layer.msg(data.message, { time: 1000 //2秒关闭(如果不配置,默认是3秒) }, function () { $('#detailModal').modal('hide'); that.getDataDictionaryDetail(that.dataDictId); //$("#tb_departments").bootstrapTable('refresh'); }); } else { layer.close(loading); layer.alert(data.message, { icon: 2 }); } }, error: function () { layer.close(loading); layer.alert('执行错误,请联系管理员!', { icon: 2 }); } }); } } }) </script>
the_stack
@using Xms.Schema.Extensions; @model Xms.Web.Models.SelectEntityRecordsDialogModel @{ Layout = null; } @{ var mainEntity = Model.EntityList.First(); var __ModalGuid = Guid.NewGuid().ToString().Replace("-", ""); DialogModel dialogModel = ViewData["DialogModel"] as DialogModel; } <link rel="stylesheet" href="/content/js/jqgird/css/ui.jqgrid-bootstrap.css?v=@app.PlatformSettings.VersionNumber"> <link rel="stylesheet" href="/content/js/jqgird/plugins/bootstrap-datepicker.min.css?v=@app.PlatformSettings.VersionNumber"> <!-- (Modal) --> <div class="modal fade in" id="entityRecordsModal" tabindex="-1" role="dialog" aria-labelledby="entityRecordsModalLabel" style="display:block;" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="entityRecordsModalLabel"> <span class="glyphicon glyphicon-th"></span> @mainEntity.LocalizedName - @Model.QueryView.Name - @app.T["queryview"] </h4> </div> <div class="modal-body"> <div id="queryview-section"> <div class="container-fluid"> <form id="searchForm" action="/entity/RecordsDialog" onkeydown="if(event.keyCode==13)return false;" method="post" class="form-horizontal"> @Html.HiddenFor(x => x.EntityId) @Html.HiddenFor(x => x.QueryId, new { id = "SelectEntityRecordsQueryId" }) @Html.HiddenFor(x => x.SortBy) @Html.HiddenFor(x => x.SortDirection) <input type="hidden" value="1" name="page" /> <input type="hidden" name="QField" id="QField" value="@Model.QField" /> <input type="hidden" name="mutilChecker" id="mutilChecker" value="" /> <div class="form-group"> <div class="col-sm-2"> <a id="fieldDropdown" class="dropdown-toggle btn btn-link btn-sm" data-toggle="dropdown" href="#"> <span>@app.T["search_allfield"]</span> <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="javascript:void(0)" data-name="">@app.T["search_allfield"]</a></li> @foreach (var cell in Model.Grid.Rows[0].Cells) { var isrelated = cell.Name.IndexOf(".") > 0; var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower(); var label = cell.Label; Xms.Schema.Domain.Attribute attr = null; if (!isrelated) { attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k)); //label = attr.LocalizedName; } else { attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k)); //显示字段+引用字段 //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0])); //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")"; } if (attr == null || attr.TypeIsDateTime()) { continue; } <li><a href="javascript:void(0)" data-name="@cell.Name.ToLower()" data-type="@attr.AttributeTypeName">@cell.Label</a></li> } </ul> </div> <div class=" col-sm-4" style="width:282px;"> <div class="input-group input-group-sm"> @Html.TextBoxFor(x => x.Q, new { @class = "form-control", @style = "width:200px;", @placeholder = app.T["search_quickly"] }) <span class="input-group-btn"> <button class="btn btn-default" type="button" name="clearBtn"> <span class="glyphicon glyphicon-remove-sign"></span> </button> <button class="btn btn-default" type="button" name="searchBtn"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </div> <div class="input-group input-group-sm col-sm-3" id="filterSearcher"> </div> </div> </form> </div> <div class="panel panel-default " id="gridview" style="margin-bottom:0;"> <div class="table-responsive" style="min-height:300px;max-height:350px;"> <table class="table table-hover table-striped table-condensed datatable" id="" data-pageurl="@app.Url" data-ajax="true" data-ajaxcontainer="gridview" data-ajaxcallback="EntityRecordsModel@(__ModalGuid).ajaxgrid_reset()" data-sortby="@Model.SortBy.ToLower()" data-sortdirection="@Model.SortDirection" data-singlemode="@dialogModel.SingleMode" style="table-layout:fixed;"> <thead> <tr> <th width="22"><input type="checkbox" name="checkall" /></th> <th width="35"></th> @foreach (var cell in Model.Grid.Rows[0].Cells) { var isrelated = cell.Name.IndexOf(".") > 0; var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower(); var label = cell.Label; var itemStr = ""; Xms.Schema.Domain.Attribute attr = null; if (!isrelated) { attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k)); //label = attr.LocalizedName; } else { attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k)); //显示字段+引用字段 //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0])); //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")"; } if (attr == null) { continue; } if (attr.TypeIsPickList() || attr.TypeIsBit() || attr.TypeIsStatus() || attr.TypeIsState()) { itemStr = (attr.TypeIsPickList() || attr.TypeIsStatus()) ? attr.OptionSet.Items.SerializeToJson() : attr.PickLists.SerializeToJson(); } <th data-name="@cell.Name.ToLower()" style="width:@(cell.Width+"px")" data-label="@cell.Label" data-type="@attr.AttributeTypeName" data-opts='@Html.UrlEncoder.Encode(itemStr)' data-entityid="@attr.ReferencedEntityId" data-referencedentityid="@attr.ReferencedEntityId"> </th> } </tr> </thead> <tbody> @{ var primaryKey = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.TypeIsPrimaryKey()); var primaryField = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.IsPrimaryField == true); } @foreach (var item in Model.Items) { var lines = (item as IDictionary<string, object>).ToList(); var id = lines.Find(n => n.Key.IsCaseInsensitiveEqual(primaryKey.Name)).Value; var name = lines.Find(n => n.Key.IsCaseInsensitiveEqual(primaryField.Name)).Value; <tr data-dbclick="EntityRecordsModel@(__ModalGuid).selectedrow('@id')" data-id="@id"> <td> <input type="checkbox" name="recordid" value="@id" /> </td> <td> <input type="hidden" name="recordname" value="@name" /> <a class="btn btn-link btn-xs selectBtn"><span class="glyphicon glyphicon-ok"></span></a> </td> @foreach (var cell in Model.Grid.Rows[0].Cells) { var columnName = cell.Name.ToLower(); var isrelated = columnName.IndexOf(".") > 0; var attrName = isrelated ? columnName.Split('.')[1] : columnName; Xms.Schema.Domain.Attribute attr = null; if (isrelated) { attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(attrName)); } else { attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(attrName)); } if (attr == null) { continue; } if (attr.TypeIsPrimaryKey() || attr.TypeIsLookUp() || attr.TypeIsOwner()) { columnName = attr.TypeIsPrimaryKey() ? primaryField.Name : columnName += "Name"; var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value; var recordid = lines.Find(n => n.Key.IsCaseInsensitiveEqual(cell.Name)).Value; <td> @if (attr.TypeIsPrimaryKey() || attr.DisplayStyle == "link") { <a href="@("/"+app.OrganizationUniqueName)/entity/edit?entityid=@attr.ReferencedEntityId&recordid=@recordid" target="_blank" title=""> @value </a> } else { @value } </td> } else if (attr.TypeIsPickList() || attr.TypeIsBit() || attr.TypeIsState() || attr.TypeIsStatus()) { columnName += "Name"; var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value; <td> @value </td> } else { var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value; if (value != null && (attr.TypeIsDecimal() || attr.TypeIsFloat())) { value = string.Format("{0:N2}", value); } else if (value != null && attr.TypeIsMoney()) { value = string.Format("¥{0:N2}", value); } else if (value != null && attr.TypeIsDateTime()) { if (attr.DataFormat == "yyyy/MM/dd") { value = DateTime.Parse(value + "").ToString("yyyy/MM/dd"); } value = string.Format("{0:G}", value); } else if (attr.IsPrimaryField) { value = string.Format("<a href=\"/" + app.OrganizationUniqueName + "/entity/create?entityid={0}&recordid={1}\" target=\"_blank\">{2}</a>", mainEntity.EntityId, id, value); } <td>@Html.Raw(value)</td> } } </tr> } </tbody> </table> </div> <div class="panel-footer"> <div class="row"> <div class="col-sm-4"> @(app.T["pagination_label"].Replace("{page}", Model.Page.ToString()).Replace("{totalpages}", Model.TotalPages.ToString()).Replace("{totalitems}", Model.TotalItems.ToString())) </div> <div id="page-selection" class="col-sm-8 page-selection" data-total="@Model.TotalPages" data-page="@Model.Page"></div> </div> </div> </div> <div class="selectEntityRecords-datagrid"></div> </div> <script src="/content/js/jquery.bootpag.min.js?v=@app.PlatformSettings.VersionNumber"></script> <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script> <script src="/content/js/bootstrap-datepicker-1.5.0/js/bootstrap-datepicker.min.js?v=@app.PlatformSettings.VersionNumber"></script> <script src="/content/js/bootstrap-datepicker-1.5.0/locales/bootstrap-datepicker.zh-CN.min.js?v=@app.PlatformSettings.VersionNumber" charset="UTF-8"></script> <script src="~/content/js/fetch.js?v=@app.PlatformSettings.VersionNumber"></script> @{await Html.RenderPartialAsync("FetchLabel"); } <script> ;(function () { var MODAL_GUID = '@Html.Raw(__ModalGuid)'; var EntityRecordsModel = { dialogid: '#entityRecordsModal', dialog: $('#entityRecordsModal'), datatable: $('#entityRecordsModal .datatable'), pageUrl: $("#entityRecordsModal .datatable").attr('data-pageurl'), queryid: '@Html.Raw(Model.QueryId)', entityid: '@Html.Raw(Model.EntityId)', cacheFilters:new Xms.Fetch.FilterExpression(), filters: @Html.Raw(Model.Filter.SerializeToJson()), sortby: '@Model.SortBy', sortdir: '@Model.SortDirection', q: '@Model.Q', qfield: '@Model.QField', page: @Model.Page, currentUrl:'', callback:@Html.Raw(dialogModel.CallBack), inputid:'@Html.Raw(dialogModel.InputId)', singlemode: @(dialogModel.SingleMode?"true":"false"), checkedList:[], ajaxTable : function () { var self = $('#entityRecordsModal .datatable'); var containerId = '#' + self.attr('data-ajaxcontainer'); $(EntityRecordsModel.dialogid + " " + containerId).parent().delegate('a[data-ajax="true"]', 'click', function () { var url = $(this).attr('href'); url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime(); //EntityRecordsModel.pageUrl = url; $("#entityRecordsModal .datatable").attr('data-pageurl',url); EntityRecordsModel.rebind(url); return false; }); }, ajaxgrid_reset : function () { var self = $('#entityRecordsModal .datatable'); EntityRecordsModel.pageUrl = EntityRecordsModel.datatable.attr('data-pageurl'); EntityRecordsModel.pag_init(); var $inputid = $('#'+EntityRecordsModel.inputid); var $mutilChecker = $('#mutilChecker') if(!EntityRecordsModel.singlemode && $inputid.length>0 && $inputid.val()!=='' && $inputid.attr('data-value') && $inputid.attr('data-value')!=""){ try{ var checklist = $inputid.attr('data-value').split(','); var checknamelist = $inputid.val().split(','); var _res = []; $.each(checklist,function(key,item){ var tempobj = { id:item, name:checknamelist[key] } _res.push(tempobj); }); $mutilChecker.val(encodeURIComponent(JSON.stringify(_res))); }catch(e){ console.log(e); } } Xms.Web.DataTable(self,{ changeHandler:function(obj,type,target){ if(type=='item'){ var $obj = null if($(obj).find('input[name="recordid"]').length==0){ $obj = $(obj); }else{ $obj = $(obj).find('input[name="recordid"]'); } var _check = $obj.prop('checked'); if(_check){ EntityRecordsModel._addRowInHidden(); }else{ EntityRecordsModel._removeRowByHidden($obj.val()); } }else{ var _check = $(obj).prop('checked'); if(_check){ EntityRecordsModel._addRowInHidden(); }else{ EntityRecordsModel.datatable.find('tbody').find('input[name="recordid"]').each(function(){ EntityRecordsModel._removeRowByHidden($(this).val()); }); } } console.log('changeHandler',_check) } }); console.log('pageclick'); if(EntityRecordsModel.singlemode==false){ console.log('tr.click.binding'); EntityRecordsModel.dialog.find(".datatable tbody tr").off('tr.click').on('tr.click',function(e,data){ var $self = $(this); var id = $(this).find('input[name=recordid]').val(); console.log('tr.click.trigger',data); if(data.flag){ if(id){ //console.log('tr.click._removeRowByHidden',id); // EntityRecordsModel._removeRowByHidden(id); console.log('remove'); } }else{ console.log('add'); // EntityRecordsModel._addRowInHidden(); } }); EntityRecordsModel._changepageChecked(); } //EntityRecordsModel.ajaxTable(); //EntityRecordsModel.datatable.find('tbody>tr').each(function(i, n){ // $(n).bind('dbclick', function(e){alert('abc'); // Xms.Web.SelectingRow(this); // EntityRecordsModel.dialog_return(); // }); //}); EntityRecordsModel._changepageChecked(); }, _changepageChecked:function(){ var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val(); if(checkedData!=''){ checkedData = JSON.parse(decodeURIComponent(checkedData)); } console.log('checkedData',checkedData); if(checkedData && checkedData.length>0){ EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]").each(function (i, n) { var flag = false; $.each(checkedData,function(ii,nn){ if(nn.id == $(n).val()){//如果有重复的就不加进去 flag = true; } }); if(flag==true){ $(this).prop('checked',true); } }); } }, _removeRowByHidden:function(id){ var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val(); var checkedData1= null; if($mutilChecker.val()!=''){ checkedData1 = JSON.parse(decodeURIComponent($mutilChecker.val())); } if(checkedData1){ var delIndex = null; $.each(checkedData1,function(ii,nn){ if(nn.id == id){//如果有重复的就不加进去 delIndex = ii; return false; } }); if(~delIndex){ checkedData1.splice(delIndex,1); console.log('checkedData1',checkedData1); if(checkedData1.length==0){ $mutilChecker.val(''); }else{ $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData1))); } } } }, _addRowInHidden:function(){ var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val(); if(checkedData!=''){ checkedData = JSON.parse(decodeURIComponent(checkedData)); } if(checkedData && checkedData.length>0){ //防止添加重复的数据 var result = []; EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) { var flag = false; $.each(checkedData,function(ii,nn){ if(nn.id == $(n).val()){//如果有重复的就不加进去 flag = true; } }); if(flag==false){ var obj = new Object(); obj.id = $(n).val(); obj.name = $(n).parents('tr:first').find('input[name=recordname]').val(); result.push(obj); } }); checkedData = checkedData.concat(result); }else{ var result = []; EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) { var obj = new Object(); obj.id = $(n).val(); obj.name = $(n).parents('tr:first').find('input[name=recordname]').val(); result.push(obj); }); checkedData = result; } console.log('checkedData',checkedData) $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData))); }, _emptyCheckerValue:function(){ var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val(); $mutilChecker.val(''); }, pag_init : function () { var a = $(EntityRecordsModel.dialogid + ' .page-selection'); var pageSetting = { total: a.attr('data-total') , maxVisible: 5 , page: a.attr('data-page') , leaps: false , prev: '&lsaquo;' , next: '&rsaquo;' , firstLastUse: true , first: '&laquo;' , last: '&raquo;' }; $(EntityRecordsModel.dialogid + ' .page-selection').bootpag(pageSetting).on("page", function (event, /* page number here */ num) { event.preventDefault(); EntityRecordsModel.page = num; console.log('$("#entityRecordsModal .datatable")',$("#entityRecordsModal .datatable").attr('data-pageurl')); EntityRecordsModel.rebind($("#entityRecordsModal .datatable").attr('data-pageurl')); return false; }); }, rebind: function (url,filters) { var url = url || '/entity/RecordsDialog'; url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime(); var model = new Object(); model.EntityId = EntityRecordsModel.entityid; model.QueryId = EntityRecordsModel.queryid; if(EntityRecordsModel.cacheFilters && EntityRecordsModel.cacheFilters.Filters && EntityRecordsModel.cacheFilters.Filters.length>0){ var __filter = new Xms.Fetch.FilterExpression(); __filter.Filters.push(EntityRecordsModel.filters); var filters = EntityRecordsModel.cacheFilters; $.each(filters.Filters,function(key,filter){ if (filter.Conditions[0] && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length && filter.Conditions[0].Values[0].replace("\s", "") != "" || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "") ) { __filter.Filters.push(this); } }); model.Filter = __filter; }else{ model.Filter = filters || EntityRecordsModel.filters; } model.Q = $.getUrlParam("q", url) || EntityRecordsModel.q; model.QField = $.getUrlParam("qfield", url) || EntityRecordsModel.qfield; model.SortBy = $.getUrlParam("sortby", url)|| EntityRecordsModel.sortby; model.SortDirection = $.getUrlParam("sortdirection", url) || EntityRecordsModel.sortdir; model.InputId = $.getUrlParam("inputid", url) || EntityRecordsModel.inputid; model.CallBack = $.getUrlParam("callback", url) || EntityRecordsModel.callback; model.Page = $.getUrlParam("page", url) || EntityRecordsModel.page; model.SingleMode = EntityRecordsModel.singlemode; model.OnlyEnabledRecords = false; console.log('rebind.model',model); //在多选方式下,把之前页面的数据保存起来 if(model.SingleMode==false){ } //在多选方式下,把之前页面的数据保存起来-----end Xms.Web.LoadPage(url, model, function (response) { $(EntityRecordsModel.dialogid + ' #gridview' ).html($(response).find('#gridview').html()); EntityRecordsModel.ajaxgrid_reset(); },null,null,true); }, getNum_String: function(s){ return s.replace(/[^0-9]/ig,"") }, selectedrow: function(id){ EntityRecordsModel.dialog.find('tr[data-id="'+id+'"]').find('.selectBtn').trigger('click'); }, dialog_return : function (obj) { var result = new Array(); if(!obj){ EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) { var obj = new Object(); obj.id = $(n).val(); obj.name = $(n).parents('tr:first').find('input[name=recordname]').val(); result.push(obj); }); }else{//防止多选时,始终是传回第一个已勾选上的值 var partr = $(obj).parents('tr:first'); var partrDom = partr.get(0); var partrobj = { id:partr.find("input[name=recordid]").val(), name:partr.find('input[name=recordname]').val() } result.push(partrobj); EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) { if($(n).parents('tr:first').get(0)==partrDom){return true;} var obj = new Object(); obj.id = $(n).val(); obj.name = $(n).parents('tr:first').find('input[name=recordname]').val(); result.push(obj); }); } if(EntityRecordsModel.singlemode==false){ var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val(); if(checkedData!=''){ checkedData = JSON.parse(decodeURIComponent(checkedData)); result = checkedData; } } if(result.length == 0){ Xms.Web.Alert(false, LOC_NOTSPECIFIED_RECORD); return; } var dialog = $(EntityRecordsModel.dialogid); console.log(result, EntityRecordsModel.inputid, dialog.data().OpenDialogCallback); if (dialog.data().OpenDialogCallback) { dialog.data().OpenDialogCallback(result, EntityRecordsModel.inputid) } else { EntityRecordsModel.callback && EntityRecordsModel.callback(result, EntityRecordsModel.inputid); } if($("#"+EntityRecordsModel.inputid).length>0){ $("#"+EntityRecordsModel.inputid).trigger("dialog.return",result); } //Xms.Web.Event.publish({result:result, inputid: EntityRecordsModel.inputid}); EntityRecordsModel.dialog.modal('hide'); //Xms.Web.CloseDialog('#entityRecordsModal'); }, CreateRecord: function () { var url = '/entity/create?entityid=' + EntityRecordsModel.entityid; Xms.Web.OpenWindow(ORG_SERVERURL+url); } ,enterSearch :function(e){ console.log(e); e = e || window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } EntityRecordsModel.page = 1; EntityRecordsModel.q = $(EntityRecordsModel.dialogid + ' #Q').val(); EntityRecordsModel.qfield = $(EntityRecordsModel.dialogid + ' #QField').val(); EntityRecordsModel.rebind(); } }; $(function () { EntityRecordsModel.ajaxTable(); EntityRecordsModel.ajaxgrid_reset(); // EntityRecordsModel.rebind(EntityRecordsModel.pageUrl); //默认第一列为快速查找字段 //$(EntityRecordsModel.dialogid+' #fieldDropdown').next().find('a:eq(1)').trigger('click'); EntityRecordsModel.dialog.modal({ backdrop:'static' }); EntityRecordsModel.dialog.on('hidden.bs.modal', function () { Xms.Web.CloseDialog(EntityRecordsModel.dialogid); }); $(EntityRecordsModel.dialogid + ' button[name=clearBtn]').off('click').on('click',null,function(e){ $(EntityRecordsModel.dialogid + ' #Q').val(''); EntityRecordsModel.q = ''; EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression(); EntityRecordsModel.rebind(); EntityRecordsModel._emptyCheckerValue(); }); $(EntityRecordsModel.dialogid + ' button[name=searchBtn]').off('click').on('click',null,function(e){ EntityRecordsModel.enterSearch(e); }); $(EntityRecordsModel.dialogid + ' button[name=createBtn]').off('click').on('click',null,function(e){ EntityRecordsModel.CreateRecord(); }); $(EntityRecordsModel.dialogid + ' button[name=deleteBtn]').off('click').on('click',null,function(e){ EntityRecordsModel.DeleteRecord(); }); $(EntityRecordsModel.dialogid + ' .dropdown-menu').on('click','>li>a',function(e){ $(EntityRecordsModel.dialogid + ' #QField').val($(this).attr('data-name')) $(EntityRecordsModel.dialogid + ' #fieldDropdown').find('span:first').text($(this).text()); }); $('body').off('click.selectentitydialog').on('click.selectentitydialog',EntityRecordsModel.dialogid + ' .selectBtn',function(e){ Xms.Web.SelectingRow(this); EntityRecordsModel.dialog_return(this); }); $(EntityRecordsModel.dialogid + " button[name='returnBtn']").click( function() { EntityRecordsModel.dialog_return(); }); $(EntityRecordsModel.dialogid + " #Q").off('keydown.enter').on('keydown.enter', function(e) { e = e || window.event; if(e.keyCode==13){ EntityRecordsModel.enterSearch(e); } }); $('#filterSearcher').tableFiler({ table:$('#entityRecordsModal .datatable') ,styles:"customer-filter-style" ,clear:function(pluger,filters){ EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression(); EntityRecordsModel.rebind(null); } ,confirm:function(pluger,filters){ //if(EntityRecordsModel.filters.conditions.length>1){ // EntityRecordsModel.filters.conditions = EntityRecordsModel.filters.conditions.slice(0,1); // } var _filter = new Xms.Fetch.FilterExpression(); $.each(filters,function(key,filter){ if (filter.Conditions[0] && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length && filter.Conditions[0].Values[0].replace("\s", "") != "" || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "") ) { _filter.Filters.push(this); } }); EntityRecordsModel.cacheFilters = _filter; EntityRecordsModel.rebind(); } }); console.log($('.selectEntityRecords-datagrid')) //$('.selectEntityRecords-datagrid').cDatagrid({ // entityid: EntityRecordsModel.entityid, // queryid: EntityRecordsModel.queryId, // pageModel: { type: "remote", rPP: 10, page: 1, strRpp: "{0}" }, // columnFilter: function (items) { // console.log(items) // $.each(items, function (key, item) { // item.editable = false; // }); // return items; // } //}); }); window["EntityRecordsModel"+MODAL_GUID] = EntityRecordsModel; })(); </script> </div> <div class="modal-footer"> <div class="pull-left"> <button type="button" class="btn btn-link" name="createBtn"> <span class="glyphicon glyphicon-plus-sign"></span> @app.T["add"] </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal"> <span class="glyphicon glyphicon-remove"></span> @app.T["dialog_close"] </button> <button type="button" class="btn btn-primary" name="returnBtn"> <span class="glyphicon glyphicon-ok"></span> @app.T["dialog_ok"] </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
the_stack
@model SearchSideBySideViewModel @{ ViewBag.Title = "Search Side by Side"; ViewBag.ShowSearchInNavbar = false; ViewBag.AutofocusSearch = true; ViewBag.SearchTerm = Model.SearchTerm; } <section role="main" class="main-container page-search-sxs"> <div class="container"> @if (Model.IsDisabled) { <div class="row"> <div class="col-xs-offset-3 col-xs-6 text-center"> @ViewHelpers.AlertWarning( @<text> The side-by-side search page is now <b>closed</b>. <br /><br /> Thank you for trying out the side-by-side preview. The new and improved NuGet search is now <a href="@Url.PackageList()">live</a>! For details about the initial release, check out the <a href="https://devblogs.microsoft.com/nuget/new-and-improved-nuget-search/">blog post</a>. The old search results are no longer available. <br /><br /> Keep an eye on <a href="https://twitter.com/nuget">Twitter</a> to hear about future search improvements that you can try out. </text>) </div> </div> } else { <div class="row"> <div class="col-xs-12"> <h1>Step 1: enter a search query</h1> @ViewHelpers.Section( this, "instructions", @<text>Instructions</text>, @<text></text>, @<text> <p> Enter a search query below. The query will be sent to our existing search service ("old results") as well as to our new search implementation that is based on Azure Search ("new results"). </p> <p> Once you provide a search query, take a look at the results and fill out the form below so that we can understand your thoughts on how the new results can be improved. We're still playing with how the search query is parsed and how relevant packages are ranked so any input you can provide is helpful! </p> <p> If you'd like us to be able to reach out to your concerning some feedback you have left, please leave your email address. We'll read all of your feedback whether it is anonymous or not and would be happy to start a conversation over email if you have more ideas or concerns that don't fit well in the little comment box below. </p> <p> If you're happy with the new results, we'd love to hear that too. </p> <p> A lot of ideas have already been voiced on the <a href="https://github.com/NuGet/NuGetGallery/issues/4124">Improve search on NuGet.org</a> GitHub issue but this side-by-side page is intended to help us gather even more feedback. </p> </text> , expanded: false) <form aria-label="Package search bar" action="@Url.SearchSideBySide()" method="get"> @Html.Partial("_SearchBar") </form> </div> </div> if (!string.IsNullOrWhiteSpace(Model.SearchTerm)) { <div class="row"> <div class="col-xs-12"> <h1>Step 2: examine the search results</h1> </div> </div> <div class="row"> <div class="col-xs-6"> <div class="list-packages" role="list"> <h2 class="text-center">Old results</h2> @{ var oldItemIndex = 0; } @foreach (var package in Model.OldItems) { @Html.Partial( "_ListPackage", package, new ViewDataDictionary { { "eventName", "old-search-selection" }, { "itemIndex", oldItemIndex }, { "showEditButton", false }, }) oldItemIndex++; } @if (!Model.OldSuccess) { <i>The old results could not be loaded.</i> } else if (!Model.OldItems.Any()) { <i>No results.</i> } </div> </div> <div class="col-xs-6"> <div class="list-packages" role="list"> <h2 class="text-center">New results</h2> @{ var newItemIndex = 0; } @foreach (var package in Model.NewItems) { @Html.Partial( "_ListPackage", package, new ViewDataDictionary { { "eventName", "new-search-selection" }, { "itemIndex", newItemIndex }, { "showEditButton", false }, }) newItemIndex++; } @if (!Model.NewSuccess) { <i>The new results could not be loaded.</i> } else if (!Model.NewItems.Any()) { <i>No results.</i> } </div> </div> </div> if (Model.OldSuccess && Model.NewSuccess) { <div class="row"> <div class="col-xs-12"> <h1>Step 3: provide feedback</h1> <p>All fields are optional, but please take some time to tell us your thoughts!</p> @using (Html.BeginForm("SearchSideBySide", "Experiments")) { <fieldset class="form"> @Html.AntiForgeryToken() @Html.HiddenFor(m => m.SearchTerm) @Html.HiddenFor(m => m.OldSuccess) @Html.HiddenFor(m => m.OldHits) @Html.HiddenFor(m => m.NewSuccess) @Html.HiddenFor(m => m.NewHits) <div class="form-group @Html.HasErrorFor(m => m.BetterSide)"> @Html.ShowLabelFor(m => m.BetterSide) <div class="radio"> <label> <input type="radio" name="BetterSide" id="better-side-old" value="Old"> Old results </label> <label> <input type="radio" name="BetterSide" id="better-side-new" value="New"> New results </label> <label> <input type="radio" name="BetterSide" id="better-side-neither" value="Neither"> Neither </label> </div> @Html.ShowValidationMessagesFor(m => m.BetterSide) </div> <div class="hidden form-group @Html.HasErrorFor(m => m.MostRelevantPackage)" id="most-revelant-package"> @Html.ShowLabelFor(m => m.MostRelevantPackage) @Html.ShowTextBoxFor(m => m.MostRelevantPackage, placeholder: "Package ID") @Html.ShowValidationMessagesFor(m => m.MostRelevantPackage) </div> <div class="hidden form-group @Html.HasErrorFor(m => m.ExpectedPackages)" id="expected-packages"> @Html.ShowLabelFor(m => m.ExpectedPackages) @Html.ShowTextBoxFor(m => m.ExpectedPackages, placeholder: "PackageA, PackageB") @Html.ShowValidationMessagesFor(m => m.ExpectedPackages) </div> <div class="form-group @Html.HasErrorFor(m => m.Comments)"> @Html.ShowLabelFor(m => m.Comments) @Html.ShowTextAreaFor(m => m.Comments, 5, 50) @Html.ShowValidationMessagesFor(m => m.Comments) </div> <div class="form-group @Html.HasErrorFor(m => m.EmailAddress)"> @Html.ShowLabelFor(m => m.EmailAddress) @Html.ShowTextBoxFor(m => m.EmailAddress) @Html.ShowValidationMessagesFor(m => m.EmailAddress) </div> <div class="form-group"> <input type="submit" class="btn btn-primary form-control" value="Submit feedback" title="Submit feedback" /> </div> </fieldset> <p> Your data will be respected and protected. Please see the <a href="https://privacy.microsoft.com/">Microsoft Privacy Policy</a> for more information. </p> } </div> </div> } else { @ViewHelpers.AlertDanger(@<text>Some of the search results could not be loaded. Please try again later.</text>) } } } </div> </section> @section bottomScripts { @ViewHelpers.SectionsScript(this) @if (!Model.IsDisabled) { <script type="text/javascript"> @if (!string.IsNullOrWhiteSpace(Model.SearchTerm)) { // Emit an event representing the search page and the page index. This make it easier for the search selection // event to be correlated in Google Analytics. <text> window.nuget.sendAnalyticsEvent('search-page', 'search-sxs-prerel', @Html.Raw(Json.Encode(Model.SearchTerm)), 0); </text> } $(function () { var $betterSideOld = $("#better-side-old"); var $betterSideNew = $("#better-side-new"); var $betterSideNeither = $("#better-side-neither"); var $mostRevelantPackage = $("#most-revelant-package"); var $mostRevelantPackageInput = $mostRevelantPackage.find("input"); var $expectedPackages = $("#expected-packages"); var $expectedPackagesInput = $expectedPackages.find("input"); var $emailAddress = $('#EmailAddress'); // Remember the email address provided the last time they submitted feedback. var storage = window['localStorage']; if (storage) { var key = 'search_sxs_email'; var email = storage.getItem(key); if (email !== null) { $emailAddress.val(email); } $emailAddress.closest('form').submit(function () { storage.setItem(key, $emailAddress.val()); }); } var showHiddenInputs = function () { if ($betterSideOld.prop('checked') || $betterSideNew.prop('checked')) { $mostRevelantPackage.removeClass('hidden'); $expectedPackages.addClass('hidden'); // Reset the input names so only the visible field is submitted. $mostRevelantPackageInput.attr('name', 'MostRelevantPackage'); $expectedPackagesInput.attr('name', ''); } if ($betterSideNeither.prop('checked')) { $mostRevelantPackage.addClass('hidden'); $mostRevelantPackageInput.attr('name', ''); // Reset the input names so only the visible field is submitted. $expectedPackages.removeClass('hidden'); $expectedPackagesInput.attr('name', 'ExpectedPackages'); } } $("input[type=radio]").change(function () { showHiddenInputs(); }); // Run this logic once to catch any form state set by the browser (e.g. on back button press). showHiddenInputs(); }) </script> } }
the_stack
using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Configuration; using System.Text; using System.Threading; using System.Globalization; using System.Collections.Generic; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Newtonsoft.Json; using Newtonsoft.Json.Linq; // Custom Resource Table Entity public class CustomResource : TableEntity { public string Data { get; set; } } /// <summary> /// Entry point for the Azure Function webhook and acts as the service behind a custom resource provider. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <param name="log">The logger.</param> /// <param name="tableStorage">The Azure Storage Account table.</param> /// <returns>The http response for the custom Azure API.</returns> public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log, CloudTable tableStorage) { // Get the unique Azure request path from request headers. var requestPath = req.Headers.GetValues("x-ms-customproviders-requestpath").First(); log.LogInformation($"The Custom Provider Function received a request '{req.Method}' for resource '{requestPath}'."); // Determines if it is a collection level call or action. var isResourceRequest = requestPath.Split('/').Length % 2 == 1; var azureResourceId = isResourceRequest ? ResourceId.FromString(requestPath) : ResourceId.FromString($"{requestPath}/"); // Create the Partition Key and Row Key var partitionKey = $"{azureResourceId.SubscriptionId}:{azureResourceId.ResourceGroupName}:{azureResourceId.Parent.Name}"; var rowKey = $"{azureResourceId.FullResourceType.Replace('/', ':')}:{azureResourceId.Name}"; switch (req.Method) { // Action request for an custom action. case HttpMethod m when m == HttpMethod.Post && !isResourceRequest: return await TriggerCustomAction( requestMessage: req); // Enumerate request for all custom resources. case HttpMethod m when m == HttpMethod.Get && !isResourceRequest: return await EnumerateAllCustomResources( requestMessage: req, tableStorage: tableStorage, partitionKey: partitionKey, resourceType: rowKey); // Retrieve request for a custom resource. case HttpMethod m when m == HttpMethod.Get && isResourceRequest: return await RetrieveCustomResource( requestMessage: req, tableStorage: tableStorage, partitionKey: partitionKey, rowKey: rowKey); // Create request for a custom resource. case HttpMethod m when m == HttpMethod.Put && isResourceRequest: return await CreateCustomResource( requestMessage: req, tableStorage: tableStorage, azureResourceId: azureResourceId, partitionKey: partitionKey, rowKey: rowKey); // Remove request for a custom resource. case HttpMethod m when m == HttpMethod.Delete && isResourceRequest: return await RemoveCustomResource( requestMessage: req, tableStorage: tableStorage, partitionKey: partitionKey, rowKey: rowKey); // Invalid request recieved. default: return req.CreateResponse(HttpStatusCode.BadRequest); } } /// <summary> /// Triggers a custom action with some side effect. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <returns>The http response result of the custom action.</returns> public static async Task<HttpResponseMessage> TriggerCustomAction(HttpRequestMessage requestMessage) { var myCustomActionRequest = await requestMessage.Content.ReadAsStringAsync(); var actionResponse = requestMessage.CreateResponse(HttpStatusCode.OK); actionResponse.Content = myCustomActionRequest != string.Empty ? new StringContent(JObject.Parse(myCustomActionRequest).ToString(), System.Text.Encoding.UTF8, "application/json") : null; return actionResponse; } /// <summary> /// Enumerates all the stored custom resources for a given type. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <param name="tableStorage">The Azure Storage Account table.</param> /// <param name="partitionKey">The partition key for storage. This is the custom resource provider id.</param> /// <param name="resourceType">The resource type of the enumeration.</param> /// <returns>The http response containing a list of resources stored under 'value'.</returns> public static async Task<HttpResponseMessage> EnumerateAllCustomResources(HttpRequestMessage requestMessage, CloudTable tableStorage, string partitionKey, string resourceType) { // Generate upper bound of the query. var rowKeyUpperBound = new StringBuilder(resourceType); rowKeyUpperBound[rowKeyUpperBound.Length - 1]++; // Create the enumeration query. var enumerationQuery = new TableQuery<CustomResource>().Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey), TableOperators.And, TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, resourceType), TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThan, rowKeyUpperBound.ToString())))); var customResources = (await tableStorage.ExecuteQuerySegmentedAsync(enumerationQuery, null)) .ToList().Select(customResource => JToken.Parse(customResource.Data)); var enumerationResponse = requestMessage.CreateResponse(HttpStatusCode.OK); enumerationResponse.Content = new StringContent(new JObject(new JProperty("value", customResources)).ToString(), System.Text.Encoding.UTF8, "application/json"); return enumerationResponse; } /// <summary> /// Retrieves a custom resource. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <param name="tableStorage">The Azure Storage Account table.</param> /// <param name="partitionKey">The partition key for storage. This is the custom resource provider id.</param> /// <param name="rowKey">The row key for storage. This is '{resourceType}:{customResourceName}'.</param> /// <returns>The http response containing the existing custom resource.</returns> public static async Task<HttpResponseMessage> RetrieveCustomResource(HttpRequestMessage requestMessage, CloudTable tableStorage, string partitionKey, string rowKey) { // Attempt to retrieve the Existing Stored Value var tableQuery = TableOperation.Retrieve<CustomResource>(partitionKey, rowKey); var existingCustomResource = (CustomResource)(await tableStorage.ExecuteAsync(tableQuery)).Result; var retrieveResponse = requestMessage.CreateResponse( existingCustomResource != null ? HttpStatusCode.OK : HttpStatusCode.NotFound); retrieveResponse.Content = existingCustomResource != null ? new StringContent(existingCustomResource.Data, System.Text.Encoding.UTF8, "application/json"): null; return retrieveResponse; } /// <summary> /// Creates a custom resource and saves it to table storage. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <param name="tableStorage">The Azure Storage Account table.</param> /// <param name="azureResourceId">The parsed Azure resource Id.</param> /// <param name="partitionKey">The partition key for storage. This is the custom resource provider id.</param> /// <param name="rowKey">The row key for storage. This is '{resourceType}:{customResourceName}'.</param> /// <returns>The http response containing the created custom resource.</returns> public static async Task<HttpResponseMessage> CreateCustomResource(HttpRequestMessage requestMessage, CloudTable tableStorage, ResourceId azureResourceId, string partitionKey, string rowKey) { // Construct the new resource from the request body and adds the Azure Resource Manager fields. var myCustomResource = JObject.Parse(await requestMessage.Content.ReadAsStringAsync()); myCustomResource["name"] = azureResourceId.Name; myCustomResource["type"] = azureResourceId.FullResourceType; myCustomResource["id"] = azureResourceId.Id; // Save the resource into storage. var insertOperation = TableOperation.InsertOrReplace( new CustomResource { PartitionKey = partitionKey, RowKey = rowKey, Data = myCustomResource.ToString(), }); await tableStorage.ExecuteAsync(insertOperation); var createResponse = requestMessage.CreateResponse(HttpStatusCode.OK); createResponse.Content = new StringContent(myCustomResource.ToString(), System.Text.Encoding.UTF8, "application/json"); return createResponse; } /// <summary> /// Removes an existing custom resource. /// </summary> /// <param name="requestMessage">The http request message.</param> /// <param name="tableStorage">The Azure Storage Account table.</param> /// <param name="partitionKey">The partition key for storage. This is the custom resource provider id.</param> /// <param name="rowKey">The row key for storage. This is '{resourceType}:{customResourceName}'.</param> /// <returns>The http response containing the result of the delete.</returns> public static async Task<HttpResponseMessage> RemoveCustomResource(HttpRequestMessage requestMessage, CloudTable tableStorage, string partitionKey, string rowKey) { // Attempt to retrieve the Existing Stored Value var tableQuery = TableOperation.Retrieve<CustomResource>(partitionKey, rowKey); var existingCustomResource = (CustomResource)(await tableStorage.ExecuteAsync(tableQuery)).Result; if (existingCustomResource != null) { var deleteOperation = TableOperation.Delete(existingCustomResource); await tableStorage.ExecuteAsync(deleteOperation); } return requestMessage.CreateResponse( existingCustomResource != null ? HttpStatusCode.OK : HttpStatusCode.NoContent); }
the_stack
@model Xms.Web.Models.AttachmentsModel @{ Layout = null; } @{ DialogModel dialogModel = ViewData["DialogModel"] as DialogModel; } <!-- 附件(Modal) --> <div class="modal fade" id="attachmentModal" tabindex="-1" role="dialog" aria-labelledby="attachmentModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="attachmentModalLabel"> <span class="glyphicon glyphicon-th"></span> 附件 </h4> </div> <div class="modal-body"> <ul id="myTab" class="nav nav-tabs"> <li> <a href="#infoPane" data-toggle="tab"> 添加 </a> </li> <li class="active"><a href="#listPane" data-toggle="tab">列表</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane" id="infoPane"> <div class="container-fluid" style="margin-top:10px;margin-bottom:10px;"> <form class="form-horizontal" action="@("/"+app.OrganizationUniqueName)/file/Create" method="post" enctype="multipart/form-data"> <input type="hidden" name="entityid" value="@Model.EntityId" /> <input type="hidden" name="objectid" value="@Model.ObjectId" /> <div class="form-group col-sm-12"> <label class="col-sm-2 control-label" for="description">附件</label> <div class="col-sm-10"> <input type="file" id="lefile" name="attachments" /> <input type="text" class="form-control input-large " id="viewCover" aria-describedby="basic-addon1" name="attachment" readonly disabled="disabled" /> <span class="input-group-addon glyphicon glyphicon-remove-sign" id="input-file-clear" onclick="inputFileClear();"></span> <span class="input-group-addon glyphicon glyphicon-open" id="basic-addon1" onclick="$('input[id=lefile]').click();"></span> </div> </div> <div class="form-group col-sm-12"> <label class="col-sm-2 control-label" for="description">说明</label> <div class="col-sm-10"> <textarea rows="3" cols="20" class="form-control" name="description" id="description"></textarea> </div> </div> <script type="text/javascript"> $('input[id=lefile]').change(function () { var str; str = $(this).val(); var arr = str.split('\\'); var my = arr[arr.length - 1]; $('#viewCover').val(my); }); function inputFileClear() { $('#lefile').val(''); $('#viewCover').val(''); } </script> <div class="form-group col-sm-10 "> <div class="col-sm-offset-3"> <button type="button" class="btn btn-primary" onclick="AttachmentModel.submit()"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button> </div> </div> </form> </div> </div> <div class="tab-pane in active" id="listPane"> <div class="table-responsive" id="gridview"> <table class="table table-striped table-hover table-condensed" id="datatable" data-ajax="true" data-ajaxcontainer="gridview" data-ajaxcallback="AttachmentModel.rebind('')" data-sortby="@Model.SortBy.ToLower()" data-sortdirection="@Model.SortDirection" data-singlemode="@dialogModel.SingleMode" data-refresh="AttachmentModel.rebind('')"> <thead> <tr> <th width="2%"><input type="checkbox" name="checkall" /></th> <th data-name="name"> @(Model.AttributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual("name")).LocalizedName) </th> <th data-name="cdnpath"> @(Model.AttributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual("cdnpath")).LocalizedName) </th> <th data-name="createdon"> @(Model.AttributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual("createdon")).LocalizedName) </th> <th data-name="createdby"> @(Model.AttributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual("createdby")).LocalizedName) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model.Items) { <tr> <td><input type="checkbox" value="@item["attachmentid"]" name="recordid" /></td> <td>@item["name"]</td> <td> <a href="@("/"+app.OrganizationUniqueName)/file/Download?id=@item["attachmentid"]&sid=@app.CurrentUser.SessionId&preview=true" target="_blank">预览</a> <a href="@("/"+app.OrganizationUniqueName)/file/Download?id=@item["attachmentid"]&sid=@app.CurrentUser.SessionId" target="_blank">下载</a> </td> <td>@item["createdon"]</td> <td><a href="@("/"+app.OrganizationUniqueName)/entity/create?entityname=systemuser&recordid=@item["createdby"]" target="_blank">@item["createdbyname"]</a></td> <td> <a class="btn btn-warning btn-xs" href="javascript:Xms.Web.Del('@item["attachmentid"]','@("/"+app.OrganizationUniqueName)/file/delete?entityid=@Model.EntityId&objectid=@Model.ObjectId',false,AttachmentModel.rebind,null,'确定删除?')"><span class="glyphicon glyphicon-trash"></span> 删除</a> </td> </tr> } </tbody> <tfoot> <tr> <td colspan="8" class="active"> <button type="button" class="btn btn-xs btn-primary" data-action="@("/"+app.OrganizationUniqueName)/file/delete?entityid=@Model.EntityId&objectid=@Model.ObjectId" data-role="delete" data-tooltip="@app.T["delete_confirm"]"><span class="glyphicon glyphicon-trash"></span> @app.T["batch_delete"]</button> </td> </tr> </tfoot> </table> <div class="panel-footer"> <div class="row"> <div class="col-sm-4"> @(app.T["pagination_label"].Replace("{page}", Model.Page.ToString()).Replace("{totalpages}", Model.TotalPages.ToString()).Replace("{totalitems}", Model.TotalItems.ToString())) </div> <div id="page-selection" class="col-sm-8" data-total="@Model.TotalPages" data-page="@Model.Page"></div> </div> </div> <script src="/content/js/jquery.bootpag.min.js?v=@app.PlatformSettings.VersionNumber"></script> <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script> <script> var AttachmentModel = { dialog: $('#attachmentModal'), dialogid: '#attachmentModal', pageUrl : '@app.Url', callback : @dialogModel.CallBack, inputid : '@dialogModel.InputId', entityid : '@(Model.EntityId.ToString())', objectid : '@(Model.ObjectId.ToString())', disabledForm: function () { AttachmentModel.dialog.find('button').prop('disabled', true); }, resetForm: function () { AttachmentModel.dialog.find('button').prop('disabled', false); }, ajaxgrid_reset: function () { AttachmentModel.pag_init(); Xms.Web.DataTable($(AttachmentModel.dialogid + " #datatable")); }, pag_init : function () { $(AttachmentModel.dialogid + ' #page-selection').bootpag({ total: $(AttachmentModel.dialogid + ' #page-selection').attr('data-total') , maxVisible: 5 //最大显示分页个数 , page: $(AttachmentModel.dialogid + ' #page-selection').attr('data-page') , leaps: false , prev: '&lsaquo;' , next: '&rsaquo;' , firstLastUse: true , first: '&laquo;' , last: '&raquo;' }).on("page", function (event, /* page number here */ num) { event.preventDefault(); var url = $.setUrlParam(AttachmentModel.pageUrl, 'page', num); AttachmentModel.rebind(url); return false; }); }, submit: function () { AttachmentModel.disabledForm(); AttachmentModel.dialog.find('form').submit(); }, dialog_return : function () { AttachmentModel.dialog.modal('hide'); //Xms.Web.CloseDialog('#attachmentModal'); }, rebind: function (url) { if (typeof url == 'string') url = url || AttachmentModel.pageUrl; else url = AttachmentModel.pageUrl; $(AttachmentModel.dialogid + " #gridview").ajaxLoad(url, AttachmentModel.dialogid + " #gridview", function (response) { AttachmentModel.ajaxgrid_reset(); }); AttachmentModel.ajaxgrid_reset(); } }; $(function () { if(AttachmentModel.entityid == Xms.Utility.Guid.EmptyGuid.ToString() || AttachmentModel.objectid == Xms.Utility.Guid.EmptyGuid.ToString()){ Xms.Web.Alert(false, LOC_NOTSPECIFIED_RECORD); AttachmentModel.dialog_return(); return; } AttachmentModel.ajaxgrid_reset(); AttachmentModel.dialog.find('form').ajaxForm({ success:function (response) { if (response.IsSuccess) { Xms.Web.Alert(true, response.Content); //AttachmentModel.dialog_return(); AttachmentModel.callback(response.Extra.filepath, AttachmentModel); AttachmentModel.rebind(); AttachmentModel.dialog.find('form').resetForm(); AttachmentModel.resetForm(); return; } Xms.Web.Alert(false, response.Content); AttachmentModel.resetForm(); }, error:function(){ AttachmentModel.dialog.find('form').resetForm(); AttachmentModel.resetForm(); setTimeout(function(){ if($('.jq-toast-wrap').length>0){ $('.jq-toast-wrap').remove(); } },2000); return; } }); $(AttachmentModel.dialogid + " #datatable").ajaxTable(); AttachmentModel.dialog.modal({ backdrop:'static' }) AttachmentModel.dialog.on('hidden.bs.modal', function () { Xms.Web.CloseDialog(AttachmentModel.dialogid); }); //$('#myTab').find('li').click(function(){ // AttachmentModel.ajaxgrid_reset(); //}) }); </script> </div> </div> </div> </div> @*<div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> <span class="glyphicon glyphicon-remove"></span> @app.T["dialog_close"] </button> <button type="button" class="btn btn-primary" onclick="AttachmentModel.dialog_return()"> <span class="glyphicon glyphicon-ok"></span> @app.T["dialog_ok"] </button> </div>*@ </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
the_stack
@model NccCategory @{ Layout = Constants.AdminLayoutName; var mainName = "Category"; var controllerName = "Category"; Title = mainName + " Create"; SubTitle = "Create a new " + mainName.ToLower(); if (Model.Id > 0) { Title = mainName + " Edit"; SubTitle = "Update information of a " + mainName.ToLower(); } } <style> .tabBorderDesign { border-left: 1px solid #ddd; border-right: 1px solid #ddd; border-bottom: 1px solid #ddd; } </style> <div class="row"> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> @SubTitle <div class="pull-right"> @if (Model.Id > 0) { <a asp-controller="@controllerName" asp-action="CreateEdit" asp-route-id="" class="btn btn-outline btn-success btn-xs">New Category</a> } <a asp-controller="@controllerName" asp-action="Manage" class="btn btn-outline btn-primary btn-xs">Manage Category</a> </div> </div> <div class="panel-body"> <div class="row"> <form id="createEditForm" class="form-horizontal" asp-controller="@controllerName" asp-action="CreateEdit" method="post"> <span asp-validation-summary="ValidationSummary.All" class="text-danger"></span> <input type="hidden" asp-for="Id" /> <input type="hidden" asp-for="Status" /> <div class="col-md-12"> <div class=""> @{ var tabBorderDesign = ""; } @if (GlobalContext.WebSite.IsMultiLangual == true) { <ul class="nav nav-tabs" role="tablist"> @foreach (var item in Model.CategoryDetails) { if (GlobalContext.WebSite.Language == item.Language) { <li role="presentation" class="active"> <a href="#@item.Language" aria-controls="@item.Language" role="tab" data-toggle="tab"> (D) @SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).FirstOrDefault().NativeName </a> </li> } else { <li role="presentation" class=""> <a href="#@item.Language" aria-controls="@item.Language" role="tab" data-toggle="tab"> @if (SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).Count() > 0) { <span>@SupportedCultures.Cultures.Where(x => x.TwoLetterISOLanguageName == item.Language).FirstOrDefault().NativeName</span> } else { <span>@item.Language</span> } </a> </li> } } </ul> tabBorderDesign = "tabBorderDesign"; } <!-- Tab panes --> <div class="tab-content @tabBorderDesign"> @{ var activeClass = ""; var i = 0;} @foreach (var item in Model.CategoryDetails) { if (GlobalContext.WebSite.Language == item.Language) { activeClass = "active"; } else { activeClass = ""; } <div role="tabpanel" class="tab-pane row @activeClass" id="@item.Language"> <div class="" style="padding:10px 25px 25px 25px;"> <div class="col-md-12"> <input type="hidden" asp-for="CategoryDetails[i].Id" /> <input type="hidden" asp-for="CategoryDetails[i].Language" /> <input type="hidden" asp-for="CategoryDetails[i].Status" /> <div class="form-group input-group"> <span class="input-group-addon">Name: </span> <input type="text" class="form-control categoryName" asp-for="CategoryDetails[i].Name" placeholder="Enter Name in @item.Language"> <span asp-validation-for="CategoryDetails[i].Name" class="text-danger"></span> </div> <div class="form-group input-group"> <span class="input-group-addon">@ViewBag.DomainName</span> <input type="text" class="form-control categorySlug" asp-for="CategoryDetails[i].Slug" placeholder="Slug in @item.Language"> <span asp-validation-for="CategoryDetails[i].Slug" class="text-danger"></span> </div> <div class="form-group input-group"> <span class="input-group-addon">Browser Title: </span> <input type="text" class="form-control categoryTitle" asp-for="CategoryDetails[i].Title" placeholder="Enter Browser Title in @item.Language"> <span asp-validation-for="CategoryDetails[i].Title" class="text-danger"></span> </div> </div> </div> </div> i++; } </div> </div> </div> <div class="col-md-12"> <div class=""> <br /> <div class="form-group"> <label class="col-md-3 text-right">Parent </label> <div class="col-md-9"> <select class="form-control" asp-for="Parent" name="ParentId" asp-items="@ViewBag.AllCategories"> <option value="0">Select Parent</option> </select> </div> </div> <div class="form-group"> <label class="col-md-3 text-right">Image </label> <div class="col-md-9"> <img src="@Model.CategoryImage" id="CategoryImageView" style="max-width:250px;max-height:70px;padding-bottom:5px;" /><br /> <input type="button" class="btn btn-default" id="LogoSelect" value="Select" onclick="openFFPromotionPopup('/MediaHome/?inputId=CategoryImage')" /> <input type="hidden" class="form-control" asp-for="CategoryImage" placeholder="" value="@Model.CategoryImage" /> </div> </div> <div class="text-center"> <a asp-controller="@controllerName" asp-action="Manage" class="btn btn-default">Back</a> <input type="submit" class="btn btn-primary" name="Save" value="Save" /> @if (Model.Id == 0) { <input type="submit" class="btn btn-success" name="Save" value="Save And New" /> } </div> </div> </div> </form> </div> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> </div> @section Scripts{ <script> $(document).ready(function () { $(".categoryName").change(function () { $(this).parent().parent().find(".categorySlug").val(NccUtil.GetSafeSlug($(this).val())); }); $("#publish").click(function () { var element = document.getElementById('PostStatus'); element.value = "2"; //console.log($("#Slug").val()); //if ($("#Slug").val() == "") { // document.getElementById("Slug").value = NccUtil.GetSafeSlug($("#Title").val()); // console.log($("#Slug").val()); //} document.getElementById("SubmitType").value = "publish"; //$("#SubmitType").value = "publish"; //$('#PostContent').html(CKEDITOR.instances["PostContent"].getData()); document.getElementById("createEditForm").submit(); }); $("#save").click(function () { //if ($("#Slug").val() == "") { // $("#Slug").val(NccUtil.GetSafeSlug($(this).val())); //} $("#SubmitType").val("Save"); //$('#PostContent').html(CKEDITOR.instances["PostContent"].getData()); document.getElementById("createEditForm").submit(); }); }); </script> <script> var windowObjectReference = null; // global variable function openFFPromotionPopup(siteUrl) { if (windowObjectReference == null || windowObjectReference.closed) { windowObjectReference = window.open(siteUrl, "PromoteFirefoxWindowName", "resizable,scrollbars,status"); } else { windowObjectReference.focus(); }; } setInterval(function () { $("#CategoryImageView").attr("src", $("#CategoryImage").val()); //console.log($("#SiteLogoUrl").val()); }, 500); </script> }
the_stack
@******************************************************************************************************* // Index.cshtml - Gbtc // // Copyright © 2016, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 01/15/2016 - J. Ritchie Carroll // Generated original version of source code. // //*****************************************************************************************************@ @using System @using System.IO @using System.Globalization @using System.Threading @using GSF @using GSF.Data @using GSF.Identity @using GSF.IO @using GSF.Security @using GSF.Security.Cryptography @using GSF.Web.Model @using GSF.Web.Shared @using openHistorian.Model @using AssemblyInfo = GSF.Reflection.AssemblyInfo @inherits ExtendedTemplateBase<AppModel> @{ Layout = "Layout.cshtml"; ViewBag.Title = "Home"; Version assemblyVersionInfo = AssemblyInfo.EntryAssembly.Version; string applicationVersion = assemblyVersionInfo.Major + "." + assemblyVersionInfo.Minor + "." + assemblyVersionInfo.Build; string grafanaVersion; string databaseType; string databaseName; string localTimeFormat = Model.Global.DateFormat + " hh:mm:ss.fff"; try { using (AdoDataConnection database = new AdoDataConnection("systemSettings")) { databaseType = database.DatabaseType.ToString(); try { if (database.IsSqlite || database.IsJetEngine) { // Extract database file name from connection string for file centric databases databaseName = FilePath.GetFileName(database.Connection.ConnectionString.ParseKeyValuePairs()["Data Source"]); } else if (database.IsOracle) { // Extract user name from connection string for Oracle databases databaseName = database.Connection.ConnectionString.ParseKeyValuePairs()["User Id"]; } else { databaseName = database.Connection.Database; } } catch { // Fall back on database name if file anything fails databaseName = database.Connection.Database; } } } catch { databaseType = "Not Available"; databaseName = "Not Available"; } try { grafanaVersion = File.ReadAllText("Grafana\\VERSION").Trim(); } catch { grafanaVersion = null; } string requiresAdmin = UserIsAdmin() ? "" : " disabled"; string requiresEditor = UserIsAdminOrEditor() ? "" : " disabled"; string grafanaInstalled = Model.Global.GrafanaServerInstalled ? "" : " disabled"; } @section StyleSheets { <style> /* Auto font resize CSS for system health window - targeting fixed 80 char width without wrap and allowing for responsive screen rearrangement when window is col-**-8 and on the right */ @@media screen { .performance-statistics { font-size: 5.25px; } } @@media screen and (min-width: 430px) { .performance-statistics { font-size: 7px; } } @@media screen and (min-width: 470px) { .performance-statistics { font-size: 8px; } } @@media screen and (min-width: 515px) { .performance-statistics { font-size: 9px; } } @@media screen and (min-width: 550px) { .performance-statistics { font-size: 10px; } } @@media screen and (min-width: 600px) { .performance-statistics { font-size: 11px; } } @@media screen and (min-width: 635px) { .performance-statistics { font-size: 12px; } } @@media screen and (min-width: 685px) { .performance-statistics { font-size: 13px; } } @@media screen and (min-width: 725px) { .performance-statistics { font-size: 14px; } } @@media screen and (min-width: 768px) { .performance-statistics { font-size: 8px; } } @@media screen and (min-width: 992px) { .performance-statistics { font-size: 12px; } } @@media screen and (min-width: 1200px) { .performance-statistics { font-size: 14px; } } .badge-fixed { display: inline-block; width: 175px; padding-top: 5px; padding-bottom: 5px; } .first-column { min-width: 310px; } #userInfoButton { height: 0px; margin-top: -22px; color: inherit; text-decoration: underline; outline-style: none; } </style> } @section Scripts { <script> const LocalTimeFormat = DateFormat + " hh:mm:ss.fff"; function updateTimestamps() { const date = new Date(); $("#meridiem").html(date.getHours() < 12 ? "AM" : "PM"); $('#localTimeUTC').html(date.formatDate()); $('#localTime').html(date.formatDate(LocalTimeFormat, false)); if (hubIsConnected) { serviceHub.getServerTime().done(function (serverTime) { $('#serverTimeUTC').html(serverTime.formatDate()); $('#serverTime').html(serverTime.formatDate(LocalTimeFormat, false)); }); } } function updatePerformanceStatistics() { if (hubIsConnected) serviceHub.getPerformanceStatistics().done(function (statistics) { $("#performanceStatistics").html(statistics); }); } $(window).on("hubConnected", function (event) { updatePerformanceStatistics(); setInterval(updatePerformanceStatistics, 5000); }); $("#restartButton").click(function () { if (hubIsConnected && confirm("Are you sure you want to restart service?")) serviceHub.sendCommand("restart"); }); $(function () { updateTimestamps(); setInterval(updateTimestamps, 1000); }); </script> } @functions { public string GetCurrentUserID() { if (Thread.CurrentPrincipal.Identity == null) return UserInfo.CurrentUserID; return Thread.CurrentPrincipal.Identity.Name; } public bool UserIsAdmin() { SecurityPrincipal securityPrincipal = ViewBag.SecurityPrincipal as SecurityPrincipal; if ((object)securityPrincipal == null) return false; return securityPrincipal.IsInRole("Administrator"); } public bool UserIsAdminOrEditor() { SecurityPrincipal securityPrincipal = ViewBag.SecurityPrincipal as SecurityPrincipal; if ((object)securityPrincipal == null) return false; return securityPrincipal.IsInRole("Administrator,Editor"); } } <div class="row"> <div class="col-lg-4 col-md-4 col-sm-5"> <div class="panel panel-default first-column"> <div class="panel-heading">Quick Links</div> <div class="panel-body"> <div class="btn-group-vertical btn-block"> <a href="Devices.cshtml" role="button" class="btn btn-primary">Browse Devices</a> <a href="AddDevice.cshtml" role="button" class="btn btn-default@(requiresEditor)" @requiresEditor>Add Device / Import Data</a> <a href="TrendMeasurements.cshtml" role="button" class="btn btn-default">Trend / Export Data</a> <a href="grafana" role="button" class="btn btn-default@(grafanaInstalled)" @grafanaInstalled><img src="/Images/Icons/grafana_icon.png" style="vertical-align: text-bottom"> Grafana Visualizations</a> <a href="GraphMeasurements.cshtml" role="button" class="btn btn-default">Real-time Measurements</a> <button type="button" class="btn btn-default@(requiresAdmin)" id="restartButton" @requiresAdmin hub-dependent>Restart Service</button> </div> </div> </div> <div class="list-group first-column"> <div class="list-group-item"> <h5 class="list-group-item-heading" style="text-align: right"><strong>UTC Time</strong></h5> <p class="list-group-item-text"> <hr class="quarter-break" /> <span class="badge badge-fixed" id="serverTimeUTC">@DateTime.UtcNow.ToString(Model.Global.DateTimeFormat)</span>Server&nbsp;Time <hr class="quarter-break" /> <span class="badge badge-fixed" id="localTimeUTC">@DateTime.UtcNow.ToString(Model.Global.DateTimeFormat)</span>Client&nbsp;Time </p> </div> <div class="list-group-item"> <h5 class="list-group-item-heading" style="text-align: right"><strong>Local Time (<span id="meridiem">@DateTime.Now.ToString("tt", CultureInfo.InvariantCulture)</span>)</strong></h5> <p class="list-group-item-text"> <hr class="quarter-break" /> <span class="badge badge-fixed" id="serverTime">@DateTime.Now.ToString(localTimeFormat)</span>Server&nbsp;Time <hr class="quarter-break" /> <span class="badge badge-fixed" id="localTime">@DateTime.Now.ToString(localTimeFormat)</span>Client&nbsp;Time </p> </div> <div class="list-group-item"> <p class="list-group-item-text"> <hr class="quarter-break" /> <span class="badge badge-fixed" id="currentUser"><button type="button" class="btn btn-link" id="userInfoButton" style="margin-left: -5px">@GetCurrentUserID()</button></span> Current User <hr class="quarter-break" /> <span class="badge badge-fixed" id="applicationVersion">@applicationVersion</span>App&nbsp;Version <hr class="quarter-break" /> @if (Model.Global.GrafanaServerInstalled && !string.IsNullOrEmpty(grafanaVersion)) { <text> <span class="badge badge-fixed" id="grafanaVersion">@(grafanaVersion)</span>Grafana&nbsp;Version <hr class="quarter-break" /> </text> } <span class="badge badge-fixed" id="databaseType">DB: @databaseType</span>Config&nbsp;Type <hr class="quarter-break" /> <span class="badge badge-fixed" id="databaseName">@databaseName</span>Config&nbsp;Name </p> </div> </div> <div class="text-info text-center small" style="margin-top: -15px;"> Using @(Cipher.SystemAllowsManagedEncryption ? "managed" : "FIPS compliant") security algorithms<br /> Compiled in @(AssemblyInfo.EntryAssembly.Debuggable ? "debug" : "release") mode<br /> @ViewBag.Request.RequestUri.ToString() </div> <!-- label class="small" id="fontSizeLabel"></label --> </div> <div class="col-lg-8 col-md-8 col-sm-7"> <div class="panel panel-default"> <div class="panel-heading">System Health</div> <div class="panel-body"> <pre class="performance-statistics" id="performanceStatistics">Loading&nbsp;&nbsp;<span class="glyphicon glyphicon-refresh glyphicon-spin"></span></pre> </div> </div> </div> </div> <script> // Pop-up window code derived from "JK Pop up image viewer script" - by JavaScriptKit.com // Visit JavaScript Kit (http://javascriptkit.com) // for free JavaScript tutorials and scripts // This notice must stay intact for use function detectExistence(obj){ return (typeof obj !="undefined"); } var popupWindow; function ShowPopupWindow(popupUrl, width, height) { var leftPosition, topPosition; function getPosition() { leftPosition = (detectExistence(window.screenLeft)) ? screenLeft + document.body.clientWidth / 2 - width / 2 : detectExistence(window.screenX) ? screenX + innerWidth / 2 - width / 2 : 0; topPosition = (detectExistence(window.screenTop)) ? screenTop + document.body.clientHeight / 2 - height / 2 : detectExistence(window.screenY)? screenY + innerHeight / 2 - height / 2 : 0; if (window.opera) { leftPosition -= screenLeft; topPosition -= screenTop; } } getPosition(); const windowAttributes = "width=" + width + ",height=" + height + ",left=" + leftPosition + ",top=" + topPosition + ",directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no"; if (typeof popupWindow == "undefined" || popupWindow.closed) { popupWindow = window.open(popupUrl, "", windowAttributes); } else { getPosition(); popupWindow.moveTo(leftPosition, topPosition); popupWindow.resizeTo(width, height + 30); } popupWindow.focus(); } $("#userInfoButton").click(function() { ShowPopupWindow("@Resources.Root/Shared/Views/UserInfo.cshtml", 600, 275); }); </script>
the_stack
@model Sheng.WeixinConstruction.Client.Shell.Models.LuckyTicketViewModel @{ ViewBag.SubTitle = "活动"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } <style type="text/css"> body { margin-bottom: 0.55rem; } .campaignName { font-size: 0.14rem; font-weight: bold; } .campaignDescription { font-size: 0.13rem; color: #666; } #divMemberInfo { font-size: 0.14rem; line-height: 0.14rem; text-align: center; margin-top: 0.05rem; } #divShareMask { position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; width: 100%; height: 100%; background-color: black; text-align: right; filter: alpha(opacity=80); -moz-opacity: 0.8; -khtml-opacity: 0.8; opacity: 0.8; } .divLuckyTicketItem { text-align: center; font-size: 0.2rem; color: #FF7F00; background-image: url(/Content/Images/bg_star.jpg); background-repeat: repeat; padding-top: 0.05rem; padding-bottom: 0.05rem; margin-bottom: 0.05rem; } #divFooter { position: fixed; bottom: 0px; left: 0px; right: 0px; height: 0.4rem; font-size: 0.14rem; text-align: center; background-color: #F5F5F5; } </style> <script> var _currentPage = 1; var _totalPage = 1; var _status = @((int)Model.CampaignBundle.Campaign.Status); var _campaignId = getQueryString("campaignId"); $(document).ready(function () { $(document).scroll(function () { $("#divShareMask").css("top", document.body.scrollTop); }); var jsApiConfigStr = "@Newtonsoft.Json.JsonConvert.SerializeObject(Model.JsApiConfig)"; jsApiConfigStr = jsApiConfigStr.replace(new RegExp("&quot;", "gm"), "\""); jsApiConfigStr = jsApiConfigStr.replace(new RegExp("\r\n", "gm"), ""); jsApiConfigStr = jsApiConfigStr.replace(new RegExp("\n", "gm"), ""); var jsApiConfig = eval('(' + jsApiConfigStr + ')'); wx.config(jsApiConfig); loadData(); }); wx.ready(function () { wx.onMenuShareTimeline({ title: '@Model.CampaignBundle.Campaign.ShareTimelineTitle', // 分享标题 link: '@Request.Url.Scheme://@Request.Url.Host/Campaign/LuckyTicketShare/@Model.CampaignBundle.Campaign.Domain?campaignId=@Model.CampaignBundle.Campaign.Id&memberId=@ViewBag.Member.Id', // 分享链接 imgUrl: '@Model.CampaignBundle.Campaign.ShareImageUrl', // 分享图标 success: function () { shareSuccess("ShareTimeline"); }, cancel: function () { // 用户取消分享后执行的回调函数 } }); wx.onMenuShareAppMessage({ title: '@Model.CampaignBundle.Campaign.ShareAppMessageTitle', // 分享标题 desc: '@Model.CampaignBundle.Campaign.ShareAppMessageDescription', // 分享描述 link: '@Request.Url.Scheme://@Request.Url.Host/Campaign/LuckyTicketShare/@Model.CampaignBundle.Campaign.Domain?campaignId=@Model.CampaignBundle.Campaign.Id&memberId=@ViewBag.Member.Id', // 分享链接 imgUrl: '@Model.CampaignBundle.Campaign.ShareImageUrl', // 分享图标 type: 'link', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: function () { shareSuccess("ShareAppMessage"); }, cancel: function () { // 用户取消分享后执行的回调函数 } }); }); wx.error(function (res) { alert("error:" + res); }); function shareSuccess(type) { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/" + type + "/@ViewBag.Domain.Id?campaignId=" + _campaignId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { // alert(data); layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; if (resultObj.Point == 0) return; var msg = ""; if (resultObj.Point > 0) { msg += "获得积分:" + resultObj.Point; } if (msg != "") { layerAlertBtn(msg); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function loadData(targetPage) { if (targetPage > _totalPage) return; var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); var args = new Object(); args.Page = targetPage || 1; args.PageSize = 10; args.CampaignId = _campaignId; $.ajax({ url: "/Api/Campaign/GetLuckyTicketLogList/@ViewBag.Domain.Id", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; _currentPage = resultObj.Page; _totalPage = resultObj.TotalPage; if (_currentPage >= _totalPage) { $("#divPagingContainer").html("没有更多了"); } if(_currentPage==1) { document.getElementById('ticketNumberItemContainer').innerHTML = ""; } $("#spanTotalCount").html(resultObj.TotalCount); var gettpl = document.getElementById('ticketNumberItemTemplate').innerHTML; laytpl(gettpl).render(resultObj.ItemList, function (html) { document.getElementById('ticketNumberItemContainer').innerHTML += html; }); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showDrawResult(){ window.location.href= "/Campaign/LuckyTicketDrawResult/@ViewBag.Domain.Id?campaignId=" + _campaignId } function showCampaignDescription() { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/GetCampaignDescription/@ViewBag.Domain.Id?id=" + _campaignId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; var gettpl = document.getElementById('campaignDescription').innerHTML; laytpl(gettpl).render(resultObj, function (html) { var pageii = layer.open({ type: 1, content: html, shadeClose: false, style: 'position:fixed; left:0.1rem; top:0.1rem;right:0.1rem; bottom:0.1rem; border:none;' }); }); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showShareMask() { $("#divShareMask").css("top", document.body.scrollTop); $("#divShareMask").show(); $("#divFooter").hide(); } function hideShareMask() { $("#divShareMask").hide(); $("#divFooter").show(); } </script> <script type="text/html" id="campaignDescription"> <div style="position: fixed; top: 0.1rem; left: 0.1rem; right: 0.1rem; bottom: 0.45rem; overflow: auto;"> {{ d }} </div> <div style="position: fixed; bottom: 0.1rem; left: 0.1rem; right: 0.1rem;"> <div class="divRectangle_Gray" style="margin-top: 0.1rem; " onclick="layer.closeAll()"> 关 闭 </div> </div> </script> <script type="text/html" id="ticketNumberItemTemplate"> {{# for(var i = 0, len = d.length; i < len; i=i+1){ }} <div class="divLuckyTicketItem"> {{ d[i].TicketNumber }} </div> {{# } }} </script> <div id="divImageContainer"> <img src="@Model.CampaignBundle.Campaign.ImageUrl" name="img" id="img" style="width: 100%;"> </div> <div class="divContent"> <div style="margin-top: 0.06rem" class="campaignName"> @Model.CampaignBundle.Campaign.Name </div> <div style="margin-top: 0.06rem" class="campaignDescription"> @Html.Raw(Model.CampaignBundle.Campaign.Introduction) </div> @if (Model.WinLogList != null && Model.WinLogList.Count > 0) { <div style="margin-top:0.15rem;padding-left:0.1rem;padding-right:0.1rem; padding-top:0.1rem;padding-bottom:0.1rem; background-color:#FFE6E6;border: 1px solid #FF4D4D;font-size:0.13rem;"> <div style="font-weight:bold;color:#FF0000"> 恭喜中奖! </div> <div style="margin-top:0.05rem;color:#545454"> 您有 @Model.WinLogList.Count 个号码被抽中: </div> <div style="font-size:0.15rem;"> @foreach (Sheng.WeixinConstruction.Infrastructure.Campaign_LuckyTicketLogEntity item in Model.WinLogList) { <div style="margin-top:0.05rem;"> <div style="float:left;color:#FF4C4C;font-weight:bold"> @item.TicketNumber </div> <div style="float:right;color:#545454;"> @item.WinRemark </div> <div style="clear:both"></div> </div> } </div> </div> } else { <div style="margin-top:0.15rem;padding-left:0.1rem;padding-right:0.1rem; padding-top:0.1rem;padding-bottom:0.1rem; background-color:#FFE6E6;border: 1px solid #FF4D4D;font-size:0.13rem;"> <div style="margin-top:0.05rem;color:#545454"> 如果您的号码中奖,将直接显示在这里。 </div> </div> } <div style="margin-top:0.1rem; margin-bottom:0.1rem;font-size:0.13rem;" onclick="goUrl('/Home/PersonalInfo/@ViewBag.Domain.Id')"> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="width:0.6rem;"><img src="/Content/Images/personalIcon.png" style="width:0.5rem;"></td> <td>点这里完善个人信息<br />以便中奖后工作人员与您联系</td> </tr> </table> </div> <div class="divDotLine" style="margin-top:0.05rem; margin-bottom:0.1rem;"> </div> @*<div style="text-align:center"> <div class="divVote" style="margin-top: 0.1rem;" onclick="showCampaignDescription()"> 查看活动详情 </div> </div>*@ <div style="text-align: center; margin-top: 0.1rem;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="33%" align="center"> 参与人数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.MemberCount</span> </td> <td width="33%" align="center"> 总号码数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.LuckyTicketCount</span> </td> <td width="33%" align="center"> 围观次数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.PageVisitCount</span> </td> </tr> </table> </div> <div class="divDotLine" style="margin-top:0.05rem; margin-bottom:0.1rem;"> </div> <div id="divMemberInfo" onclick="showShareMask()"> <table border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="left" style="width:0.3rem"><img src="/Content/Images/shareTimeLine.jpg" style="width:0.2rem;"></td> <td align="left"><div style="line-height:0.2rem">点击这里分享本页试一试~</div></td> </tr> </table> </div> <div style="text-align: center;margin-top:0.1rem;"> 共有 <span class="font_red_b" id="spanTotalCount">0</span> 个小伙伴为你筹集抽奖号码 </div> <div style="margin-top:0.2rem;" id="ticketNumberItemContainer"> </div> <div id="divPagingContainer" class="divPagingContainer" style="margin-top:0.1rem; text-align:center" onclick="loadData(_currentPage+1)"> 查看更多 </div> </div> <div id="divFooter"> <table align="center" border="0" style="height:100%;width:100%"> <tr> <td valign="middle" align="center" width="50%"> <input name="" type="button" class="button" value="活动说明" style="width:90%" onclick="showCampaignDescription()"> </td> <td valign="middle" align="center" width="50%"> <input name="" type="button" class="button" value="开奖信息" style="width:90%" onclick="showDrawResult()"> </td> </tr> </table> </div> <div id="divShareMask" style="display:none" onclick="hideShareMask()"> <img src="/Content/Images/share.PNG" width="200" height="145"> </div>
the_stack
@using lsc.Model @using lsc.Model.Enume @model List<lsc.Model.EnterCustomer> @{ ViewData["Title"] = "客户管理"; Layout = "~/Pages/_Layout.cshtml"; List<DistrictInfo> ProvinceList = ViewBag.ProvinceList; List<UserRoleJurisdiction> userrolejurlist = ViewData["userrolejurlist"] as List<UserRoleJurisdiction>; List<ModuleInfo> modulelist = ViewData["modulelist"] as List<ModuleInfo>; var module = modulelist.FirstOrDefault(x => x.Name == "客户信息管理"); UserRoleJurisdiction usrrolejur = null; if (module != null) { usrrolejur = userrolejurlist.FirstOrDefault(x => x.ModuleID == module.ID); } List<UserInfo> userlist = ViewBag.userlist; List<EnterCustContacts> eclist = ViewBag.eclist; } <blockquote class="layui-elem-quote"> 在客户管理中展示了自己管理的客户信息,可以对客户进行相关操作 <a class="layui-btn layui-btn-normal" href="/EnterCustom/AddEnterCustom?id=0">添加客户</a> </blockquote> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;"> <legend>客户信息综合查询</legend> </fieldset> <div class="layui-fluid"> <div class="layui-row"> <form class="layui-form" method="post" action="/EnterCustom/AllEnterList" id="queryform"> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">客户名称</label> <div class="layui-input-inline"> <input type="text" class="layui-input" name="EnterName" value="@(!string.IsNullOrEmpty(ViewBag.EnterName)? ViewBag.EnterName:"")" /> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">客户类型</label> <div class="layui-input-inline"> <select class="layui-form-select" name="CustomerType" lay-search> <option value=""></option> <option value="1" @(ViewBag.CustomerType == 1 ? "selected" : "" )>代理经销商</option> <option value="2" @(ViewBag.CustomerType == 2 ? "selected" : "" )>普通客户</option> <option value="3" @(ViewBag.CustomerType == 3 ? "selected" : "" )>集团大客户</option> <option value="4" @(ViewBag.CustomerType == 4 ? "selected" : "" )>业务合作商</option> <option value="5" @(ViewBag.CustomerType == 5 ? "selected" : "" )>怀疑同行</option> <option value="6" @(ViewBag.CustomerType == 6 ? "selected" : "")>高校</option> <option value="7" @(ViewBag.CustomerType == 7 ? "selected" : "")>教委</option> <option value="8" @(ViewBag.CustomerType == 8 ? "selected" : "")>中职</option> <option value="9" @(ViewBag.CustomerType == 9 ? "selected" : "")>中学</option> <option value="10" @(ViewBag.CustomerType == 10 ? "selected" : "")>小学</option> <option value="11" @(ViewBag.CustomerType == 11 ? "selected" : "")>特教</option> <option value="12" @(ViewBag.CustomerType == 12 ? "selected" : "")>监狱</option> <option value="13" @(ViewBag.CustomerType == 13 ? "selected" : "")>戒毒所</option> <option value="14" @(ViewBag.CustomerType == 14 ? "selected" : "")>公检法</option> <option value="15" @(ViewBag.CustomerType == 15 ? "selected" : "")>武警部队</option> <option value="16" @(ViewBag.CustomerType == 16 ? "selected" : "")>医院</option> <option value="17" @(ViewBag.CustomerType == 17 ? "selected" : "")>其他客户</option> </select> </div> </div> <div class=" layui-col-md4 query-from-item"> <label class="layui-form-label">关系等级</label> <div class="layui-input-inline"> <select class="layui-form-select" name="Relationship"> <option value=""></option> <option value="1" @(ViewBag.Relationship == 1 ? "selected" : "" )>密切</option> <option value="2" @(ViewBag.Relationship == 2 ? "selected" : "" )>较好</option> <option value="3" @(ViewBag.Relationship == 3 ? "selected" : "" )>一般</option> <option value="4" @(ViewBag.Relationship == 4 ? "selected" : "" )>较差</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">阶段</label> <div class="layui-input-inline"> <select class="layui-form-select" name="Phase"> <option value=""></option> <option value="1" @(ViewBag.Phase == 1 ? "selected" : "" )>售前跟踪</option> <option value="2" @(ViewBag.Phase == 2 ? "selected" : "" )>需求确定</option> <option value="3" @(ViewBag.Phase == 3 ? "selected" : "" )>售中跟单</option> <option value="4" @(ViewBag.Phase == 4 ? "selected" : "" )>签约洽谈</option> <option value="5" @(ViewBag.Phase == 5 ? "selected" : "" )>成交售后</option> <option value="6" @(ViewBag.Phase == 6 ? "selected" : "" )>跟单失败</option> <option value="7" @(ViewBag.Phase == 7 ? "selected" : "" )>暂且搁置</option> <option value="8" @(ViewBag.Phase == 8 ? "selected" : "" )>其他阶段</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">价值评估</label> <div class="layui-input-inline"> <select class="layui-form-select" name="ValueGrade"> <option value=""></option> <option value="1" @(ViewBag.ValueGrade == 1 ? "selected" : "" )>高</option> <option value="2" @(ViewBag.ValueGrade == 2 ? "selected" : "" )>中</option> <option value="3" @(ViewBag.ValueGrade == 3 ? "selected" : "" )>低</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">客户来源</label> <div class="layui-input-inline"> <select class="layui-form-select" name="Source"> <option value=""></option> <option value="1" @(ViewBag.Source == 1 ? "selected" : "" )>客户来电</option> <option value="2" @(ViewBag.Source == 2 ? "selected" : "" )>主动挖掘</option> <option value="3" @(ViewBag.Source == 3 ? "selected" : "" )>网站咨询</option> <option value="4" @(ViewBag.Source == 4 ? "selected" : "" )>客户介绍</option> <option value="5" @(ViewBag.Source == 5 ? "selected" : "" )>其他来源</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">省份</label> <div class="layui-input-inline"> <select class="layui-form-select" name="Province" lay-filter="Province" lay-search> <option value=""></option> @if (ProvinceList != null) { foreach (var p in ProvinceList) { <option value="@p.Name" data-id="@p.ID" @(ViewBag.Province == p.Name ? "selected" : "" )>@p.Name</option> } } </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">城市</label> <div class="layui-input-inline"> <select class="layui-form-select" name="City" lay-filter="City" lay-search> <option value="@ViewBag.City">@ViewBag.City</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">热点客户</label> <div class="layui-input-inline"> <input type="checkbox" name="IsHeat" lay-skin="switch" @(ViewBag.IsHeat == true ? "checked" : "")> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">热度</label> <div class="layui-input-inline"> <select class="layui-form-select" name="DegreeOfHeat"> <option value=""></option> <option value="1" @(ViewBag.DegreeOfHeat == 1 ? "selected" : "")>高热</option> <option value="2" @(ViewBag.DegreeOfHeat == 2 ? "selected" : "")>中热</option> <option value="3" @(ViewBag.DegreeOfHeat == 3 ? "selected" : "")>低热</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">最近追踪时间</label> <div class="layui-input-inline"> <select class="layui-form-select" name="UpdateTime"> <option value=""></option> <option value="1" @(ViewBag.UpdateTime == 1 ? "selected" : "")>7天未追踪</option> <option value="2" @(ViewBag.UpdateTime == 2 ? "selected" : "")>15天未追踪</option> <option value="3" @(ViewBag.UpdateTime == 3 ? "selected" : "")>30天未追踪</option> <option value="4" @(ViewBag.UpdateTime == 4 ? "selected" : "")>60天未追踪</option> <option value="5" @(ViewBag.UpdateTime == 5 ? "selected" : "")>90天未追踪</option> </select> </div> </div> <div class="layui-col-md4 query-from-item"> <label class="layui-form-label">所属用户</label> <div class="layui-input-inline"> <select class="layui-form-select" name="UserID"> <option value=""></option> @if (userlist != null && userlist.Count > 0) { foreach (var user in userlist) { <option value="@user.ID" @(ViewBag.userid == user.ID ? "selected" : "")>@user.Name</option> } } </select> </div> </div> <div class="layui-col-md4 query-from-item"> <div class="layui-input-block"> <input type="hidden" value="1" name="page" /> <button class="layui-btn" lay-submit lay-filter="*">查询</button> </div> </div> </form> </div> <div class="layui-row" id="content_table"> <table class="layui-table"> <thead> <tr> <th>客户名称</th> <th>种类</th> <th>联系人</th> <th>客户来源</th> <th>阶段</th> <th>是否是热点客户</th> <th>热点分类</th> <th>最后跟踪时间</th> <th>备注</th> <th>所属用户</th> <th>操作</th> </tr> </thead> <tbody> @if (Model != null && Model.Count > 0) { foreach (var ec in Model) { string username = string.Empty; if (ec.UserID>0 && userlist != null && userlist.Count>0) { var user = userlist.FirstOrDefault(x=>x.ID==ec.UserID); if (user!=null) { username = user.Name; } } <tr> <td><a href="/EnterCustom/EnterCustomInfo?id=@(ec.ID)">@ec.EnterName</a></td> <td>@ec.CustomerType.TryToStr()</td> <td> @if (eclist!=null && eclist.Count>0) { var ecc = eclist.FindAll(x => x.EnterCustID == ec.ID); if (ecc!=null) { foreach (var enterCustContactse in ecc) { <p>@(enterCustContactse.Name):@(enterCustContactse.Telephone)|@(enterCustContactse.Landline)|@(enterCustContactse.Email)</p> <hr/> } } } </td> <td>@ec.Source.TryToStr()</td> <td><a href="/EnterCustom/EnterCustPhaseLogList?id=@(ec.ID)">@ec.Phase.TryToStr()</a></td> <td>@(ec.IsHeat ? "是" : "否")</td> <td>@ec.HeatTYPE.TryToStr()</td> <td>@ec.UpdateTime.ToString("yyyy-MM-dd hh:mm:ss")</td> <td>@ec.Rem</td> <td>@username</td> <td> <div class="layui-btn-group"> <a href="javascript:;" class="layui-btn layui-btn-small" onclick="updatephase('@(ec.ID)')">更新阶段</a> <a href="javascript:;" onclick="showcontroller('@(ec.ID)')" class="layui-btn layui-btn-small">查看联系人</a> <a href="/EnterCustom/AddEnterCustContacts?id=0&EnterCustID=@(ec.ID)" class="layui-btn layui-btn-small">添加联系人</a> @if (ec.UserID > 0) { <a href="javascript:;" class="layui-btn layui-btn-small" onclick="entercallback('@(ec.ID)')">放入客户池</a> } @if (usrrolejur != null && usrrolejur.IsEdit) { <a href="/EnterCustom/AddEnterCustom?id=@(ec.ID)" class="layui-btn layui-btn-small">编辑</a> } @if (usrrolejur != null && usrrolejur.IsDelete) { <a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-small" onclick="del('@(ec.ID)')">删除</a> } </div> </td> </tr> } } </tbody> </table> <div id="page"></div> </div> </div> @section Scripts{ <script type="text/javascript"> var layer, form layui.use(['form', 'element', 'layer', 'laypage'], function () { form = layui.form layer = layui.layer var laypage = layui.laypage form.on('submit(*)', function (data) { $("input[name='page']").val(1) $.post('/EnterCustom/AllEnterList', data.field, function (res) { }) //return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。 }); form.on('select(Province)', function (data) { citylist(); }); //分页 laypage.render({ elem: 'page' //分页容器的id , count: @(ViewBag.count) //总页数 ,limit:20 , skin: '#1E9FFF' //自定义选中色值 //,skip: true //开启跳页 ,curr: @(ViewBag.pageIndex) //获取起始页 , jump: function (obj, first) { console.log(obj) if (!first) { $("input[name='page']").val(obj.curr) $("#queryform").submit(); } } , hash: 'fenye' //自定义hash值 }); }) //$(function () { // $.post('/EnterCustom/EnterCustomlist', { page:1 }, function (res) { // $("#content_table").html(res) // }) //}) entercallback = function (id) { layer.confirm('是否放入客户池?', { icon: 3, title: '提示' }, function (index) { $.get('/EnterCustom/EnterCallback?id=' + id, function (res) { if (res.code == 1) { layer.msg('成功', { icon: 6 }); window.location = '/EnterCustom/Index' } else { layer.msg('失败', { icon: 5 }); } }); layer.close(index); }); } del = function (id) { layer.confirm('是否删除?', { icon: 3, title: '删除提示' }, function (index) { $.get('/EnterCustom/DelEnter?id=' + id, function (res) { if (res.code == 1) { layer.msg('成功', { icon: 6 }); window.location = '/EnterCustom/Index' } else { layer.msg('失败', { icon: 5 }); } }) layer.close(index); }); } var showcontroller = function (id) { layer.open({ type: 2, title: '联系人列表', shadeClose: true, shade: 0.8, area: ['1200px', '50%'], content: '/EnterCustom/EnterCustContactsList?EnterCustID=' + id }); } citylist = function () { var pid = $("select[name='Province']").find('option:selected').attr('data-id') $("select[name='City'] option").each(function() { if ($(this).val() != '') { $(this).remove(); } }); if (pid == undefined) { form.render('select'); return; } $.get('/EnterCustom/GetCityList?id=' + pid, function(result) { if (result.code == 1) { for (var i = 0; i < result.citylist.length; i++) { $("select[name='City']").append("<option value='" + result.citylist[i].name + "'>" + result.citylist[i].name + "</option>") } form.render('select'); } }); } updatephase = function(id){ layer.open({ type: 2, title: '更新客户所处的阶段', shadeClose: true, shade: 0.8, area: ['1200px', '70%'], content: '/EnterCustom/AddEnterCustPhaseLog?id=' + id }); } addplan = function (id) { layer.open({ type: 2, title: '添加工作计划', shadeClose: true, shade: 0.8, area: ['400px', '40%'], content: '/EnterCustom/AddWorkPlan?EnterCustID=' + id }); } </script> }
the_stack
 <div class="modal fade" id="registermodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">注册新账号</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> </div> <div class="modal-body"> <form id="registuser_form" class="needs-validation" novalidate> <input id="Id" name="Id" type="hidden" value="" /> <div class="row no-gutters row-grid"> <div class="col-12"> <div class="d-flex flex-column align-items-center justify-content-center pb-4"> <div class="avatars"> <img id="avatar_lg" src="~/img/avatars/@(ViewBag.Avatar)" asp-append-version="true" style="width:129.5px" class="rounded-circle shadow-2 img-thumbnail" alt=""> <div class="overlay"> <div class="text"> <h5 class="mb-0 fw-700 text-center mt-3"> 单击修改照片 </h5> </div> </div> <input type="file" name="upload_avatar" class="image" id="upload_avatar" style="display:none" /> </div> </div> </div> </div> <div class="form-row form-group"> <div class="col-md-6"> <label class="form-label" for="userName">用户名</label> <input type="text" class="form-control" id="userName" name="userName" pattern="^[\u4E00-\u9FA5a-zA-Z0-9_]{2,20}$" required> <div class="invalid-feedback"> 请输入有效的用户名 </div> </div> <div class="col-md-6"> <label class="form-label" for="givenName">昵称</label> <input type="text" class="form-control" id="givenName" name="givenName" pattern="^[\u4E00-\u9FA5a-zA-Z0-9_]{2,20}$" required> <div class="invalid-feedback"> 请输入有效的昵称 </div> </div> </div> <div class="form-row form-group"> <div class="col-md-6"> <label class="form-label" for="password">新密码</label> <input type="password" class="form-control" id="password" name="password" required minlength="4"> <div class="invalid-feedback"> 请输入新密码 </div> </div> <div class="col-md-6"> <label class="form-label" for="passwordConfirm">再输入新密码</label> <input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm" required minlength="4"> <div class="invalid-feedback"> 请输入正确的密码 </div> </div> </div> <div class="form-row form-group"> <div class="col-md-6"> <label class="form-label" for="newemail">邮件地址</label> <input type="email" class="form-control" id="newemail" name="newemail" required> <div class="invalid-feedback"> 请输入邮件地址 </div> </div> <div class="col-md-6"> <label class="form-label" for="phonenumber">联系电话</label> <input type="number" class="form-control" id="phonenumber" name="phonenumber"> </div> </div> <div class="form-row form-group"> <div class="col-md-6"> <label class="form-label" for="tenantid">租户</label> @Html.DropDownList("tenantid", (IEnumerable <SelectListItem>)ViewBag.tenantid, new { @class = "form-control", required = "required" }) <div class="invalid-feedback"> 请选择租户 </div> </div> </div> </form> <script> // Example starter JavaScript for disabling form submissions if there are invalid fields (function () { 'use strict'; window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to var txtPassword = document.getElementById("password"); var txtConfirmPassword = document.getElementById("passwordConfirm"); txtPassword.onchange = ConfirmPassword; txtConfirmPassword.onkeyup = ConfirmPassword; function ConfirmPassword() { txtConfirmPassword.setCustomValidity(""); if (txtPassword.value != txtConfirmPassword.value) { txtConfirmPassword.setCustomValidity("新密码不匹配."); } } }, false); })(); </script> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> 取消 </button> <button type="button" onclick="saveuser()" name="savebutton" class="btn btn-primary"> 注册 </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <div class="modal fade copper-modal-right" tabindex="-1" role="dialog" aria-modal="true" aria-hidden="true"> <div class="modal-dialog modal-dialog-right "> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title h4">修改照片</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"><i class="fal fa-times"></i></span> </button> </div> <div class="modal-body"> <div class="panel-container show"> <div class="panel-content"> <div class="row"> <div class="col-12"> <div class="img-container"> <img id="upload_avatar_image" /> </div> </div> </div> </div> </div> <div class="card mb-g"> <div class="card-body p-3"> <div class="row"> <div class="col-12"> <div class="docs-preview clearfix"> <div class="img-preview preview-lg"></div> <div class="img-preview preview-md"></div> </div> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary waves-effect waves-themed" data-dismiss="modal">Close</button> <button type="button" id="getcoppedbutton" class="btn btn-primary waves-effect waves-themed">确认</button> </div> </div> </div> </div> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function () { let image = document.getElementById('upload_avatar_image'); let avatarimg = document.getElementById('avatar_lg'); let av = document.getElementById('upload_avatar_image'); let $modal = $('.copper-modal-right'); let cropper = null; $('.avatars > .overlay').click(function () { document.getElementById('upload_avatar').click(); }) $(document).on('show.bs.modal', '.modal', function (event) { var zIndex = 1040 + (10 * $('.modal:visible').length); $(this).css('z-index', zIndex); setTimeout(function () { $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'); }, 0); }); $modal.on('shown.bs.modal', function () { cropper = new Cropper(image, { aspectRatio: 1, viewMode: 1, preview: '.img-preview', width: 120, height: 120, }); }).on('hidden.bs.modal', function () { cropper.destroy(); cropper = null; }); $('#upload_avatar').change(function (event) { var files = event.target.files; var done = function (url) { image.src = url; $modal.modal('toggle') }; if (files && files.length > 0) { reader = new FileReader(); reader.onload = function (event) { done(reader.result); }; reader.readAsDataURL(files[0]); } }); $('#getcoppedbutton').click(function () { const imageData = cropper.getImageData(); const base64str = cropper.getCroppedCanvas().toDataURL(); avatarimg.src = base64str; //console.log(imageData, canvasData) }); }); function showregisterform() { $('#registermodal').modal('toggle'); document.getElementById("registuser_form").reset(); $('#registuser_form #userName').prop('readonly', false); $('#registuser_form #password').prop('readonly', false); $('#registuser_form #passwordConfirm').prop('readonly', false); $('#registuser_form #Id').val(''); $("#registuser_form #avatar_lg").attr('src', `/img/avatars/avatar-lg.jpg`); $('button[name="savebutton"]').text('注册') } function showedituserform(user) { $('#registermodal').modal('toggle'); document.getElementById("registuser_form").reset(); $('#registuser_form #password').prop('readonly', true); $('#registuser_form #passwordConfirm').prop('readonly', true); $('#registuser_form #Id').val(user.Id); $('#registuser_form #userName').val(user.UserName); $('#registuser_form #userName').prop('readonly', true); $('#registuser_form #givenName').val(user.GivenName); $('#registuser_form #newemail').val(user.Email); $('#registuser_form #tenantid').val(user.TenantId); $('#registuser_form #phonenumber').val(user.PhoneNumber); $("#registuser_form #avatar_lg").attr('src', `/img/avatars/${user.AvatarUrl}`); $('button[name="savebutton"]').text('更新') } function saveuser() { var form = document.getElementById("registuser_form"); if (form.reportValidity()) { if ($('button[name="savebutton"]').text() == '注册') { var url = "/AccountManage/ReregisterUser" $.post(url, { model: { Username: $('#registuser_form #userName').val(), Email: $('#registuser_form #newemail').val(), TenantId: $('#registuser_form #tenantid').val(), Password: $('#registuser_form #password').val(), PasswordConfirm: $('#registuser_form #passwordConfirm').val(), GivenName: $('#registuser_form #givenName').val(), PhoneNumber: $('#registuser_form #phonenumber').val(), Avatar: getavatarbase64(), } }).done((res) => { if (res.success) { $('#registermodal').modal('toggle'); reloadData(); } else { $.messager.alert('错误', res.err) } }); } else { var url = "/AccountManage/UpdateUser" $.post(url, { model: { Id: $('#registuser_form #Id').val(), Email: $('#registuser_form #newemail').val(), TenantId: $('#registuser_form #tenantid').val(), GivenName: $('#registuser_form #givenName').val(), PhoneNumber: $('#registuser_form #phonenumber').val(), Avatar: getavatarbase64(), } }).done((res) => { if (res.success) { $('#registermodal').modal('toggle'); reloadData(); } else { $.messager.alert('错误', res.err, 'error') } }); } } else { form.classList.add('was-validated'); } } function getavatarbase64() { var canvas = document.createElement('canvas'); var img = document.getElementById('avatar_lg'); canvas.height = img.naturalHeight; canvas.width = img.naturalWidth; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); var base64String = canvas.toDataURL(); return base64String; } </script>
the_stack
@page @using CleanArchitecture.Razor.Application.Constants.Permission @model SmartAdmin.WebUI.Pages.Logs.IndexModel @inject Microsoft.Extensions.Localization.IStringLocalizer<IndexModel> _localizer @inject Microsoft.AspNetCore.Authorization.IAuthorizationService _authorizationService @{ ViewData["Title"] = _localizer["Logs"].Value; ViewData["PageName"] = "logs_index"; ViewData["Category1"] = _localizer["Authorization"].Value; ViewData["Heading"] = _localizer["Logs"].Value; ViewData["PageDescription"] = _localizer["See all available options"].Value; ViewData["PreemptiveClass"] = "Default"; var _canSearch = await _authorizationService.AuthorizeAsync(User, null, Permissions.Logs.Search); var _canExport = await _authorizationService.AuthorizeAsync(User, null, Permissions.Logs.Export); } @section HeadBlock { <link href="~/css/statistics/chartist/chartist.css" rel="stylesheet" /> <link rel="stylesheet" media="screen, print" href="~/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css"> <link rel="stylesheet" media="screen, print" href="~/css/fa-solid.css"> <link rel="stylesheet" media="screen, print" href="~/css/theme-demo.css"> <link rel="stylesheet" media="screen,print" href="~/lib/easyui/themes/insdep/easyui.css"> <style> .approval_dg_datagrid-cell-c1-_action { overflow: visible !important } </style> } <div class="row mb-2"> <div class="col-sm-12 col-md-8" style="position: relative;height:160px"> <canvas id='timebar' style="height: 100%;"></canvas> </div> <div class="col-sm-12 col-md-4" style="position: relative;height:160px"> <canvas id='levelpie' class="m-auto" style="height: 100%;"></canvas> </div> </div> <div id="js-page-content-demopanels" class="card mb-g"> <div class="card-header bg-white d-flex align-items-center"> <h4 class="m-0"> @_localizer["Logs"] <small>@_localizer["See all available options"]</small> </h4> <div class="ml-auto"> @if (_canSearch.Succeeded) { <button class="btn btn-sm btn-outline-primary " id="searchbutton"> <span class="@(Settings.Theme.IconPrefix) fa-search mr-1"></span> @_localizer["Search"] </button> } @if (_canExport.Succeeded) { <button class="btn btn-sm btn-outline-primary " id="exportbutton"> <span class="@(Settings.Theme.IconPrefix) fa-download mr-1"></span> @_localizer["Export Excel"] </button> } </div> </div> <div class="card-body"> <div class="row"> <div class="col-md-12"> <table id="logs_dg"> </table> </div> </div> </div> </div> @section ScriptsBlock { @*<script src="~/js/statistics/chartjs/chartjs.bundle.js"></script>*@ <script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script> @*<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-colorschemes"></script>*@ <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script> <script src="~/js/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js"></script> <script type="text/javascript" src="~/lib/easyui/jquery.easyui.min.js" asp-append-version="true"></script> <script type="text/javascript" src="~/lib/easyui/plugins/datagrid-filter.js" asp-append-version="true"></script> <script type="text/javascript" src="~/lib/easyui/jquery.easyui.component.js" asp-append-version="true"></script> <script src="~/lib/easyui/plugins/datagrid-detailview.js"></script> <script>jQuery.fn.tooltip = bootstrapTooltip;</script> <script src="~/lib/jquery-form/jquery.jsonToForm.js"></script> <script> $(async () => { var piedata = (await axios.get('@Url.Page("/Logs/Index")?handler=LogsLevelData')).data; console.log(piedata) var piechart= new Chart(document.getElementById("levelpie").getContext('2d'), { type: 'doughnut', data: { labels: piedata.map(item => item.level), datasets: [{ label: "log classification", backgroundColor: ["#868e96", "#fe6bb0", "#EE2727", "#2697FF", "#a4cdff","#FFCF26"], data: piedata }] }, options: { hoverBorderColor:'#2ba1ff', hoverBorderWidth:3, maintainAspectRatio: false, responsive: false, parsing: { xAxisKey: 'level', key: 'total' }, plugins: { // colorschemes: { // scheme: 'brewer.Paired12' // }, legend: { position:'left', display: true, } } } }); var linedata = (await axios.get('@Url.Page("/Logs/Index")?handler=LogsTimeLineData')).data; console.log(linedata) console.log(linedata.filter(item => item.level == 'Information').map(item => { return { time: item.time, total: item.total } } )) var ctx = document.getElementById('timebar').getContext('2d'); var delayed = false; var barchart = new Chart(ctx, { type: 'bar', data: { datasets: [{ label: 'Information', data: linedata.filter(item => item.level == 'Information').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#2697FF', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", }, { label: 'Trace', data: linedata.filter(item => item.level == 'Trace').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#a4cdff', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", }, { label: 'Debug', data: linedata.filter(item => item.level == 'Debug').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#868e96', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", }, { label: 'Warning', data: linedata.filter(item => item.level == 'Warning').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#FFCF26', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", }, { label: 'Error', data: linedata.filter(item => item.level == 'Error').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#fe6bb0', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", }, { label: 'Fatal', data: linedata.filter(item => item.level == 'Fatal').map(item => { return { time: item.time, total: item.total } } ), backgroundColor: '#EE2727', //borderColor: "rgba(179,181,198,1)", //pointBorderColor: "#fff", //pointBackgroundColor: "rgba(179,181,198,1)", } ] }, options: { animation: { onComplete: () => { delayed = true; }, delay: (context) => { let delay = 0; if (context.type === 'data' && context.mode === 'default' && !delayed) { delay = context.dataIndex * 200 + context.datasetIndex * 100; } return delay; }, }, legend: { display: false }, maintainAspectRatio: false, responsive: true, indexAxis:'x', title: { display: true, text: '@_localizer["Logs"]', }, parsing: { xAxisKey: 'time', yAxisKey:'total' }, scales: { x: { stacked: true, offset: true, type: "timeseries", time: { displayFormats: { 'hour': 'ah:mm', }, unit: 'hour' }, }, y: { stacked: true, ticks: { beginAtZero: true, } } }, plugins: { tooltip: { mode: 'x', intersect: false }, legend: { display: false, labels: { color: 'rgb(255, 99, 132)' } } } } }); }) </script> <script type="text/javascript"> $('#searchbutton').click(function () { reload(); }); $('#exportbutton').click(function () { onExport(); }); var $dg={}; var initdatagrid = () => { $dg = $('#logs_dg').datagrid({ height: 700, method: 'GET', rownumbers: false, singleSelect: true, selectOnCheck: false, checkOnSelect: false, pagination: true, clientPaging: false, remoteFilter: true, sortName: 'TimeStamp', sortOrder: 'desc', pageSize: 15, pageList: [10, 15, 30, 50, 100, 1000], view: detailview, detailFormatter: function (rowIndex, rowData) { return `<div class="d-flex flex-row mb-1"> <div class="p-2 ">@_localizer["Message"]</div> <div class="p-2 ">${rowData.Message}</div> </div> <div class="d-flex flex-row mb-1"> <div class="p-2 ">@_localizer["Exception"]</div> <div class="p-2 ">${rowData.Exception}</div> </div>`; }, columns: [[ { field: 'TimeStamp', title: '@_localizer["Time Stamp"]', sortable: true, width: 165, formatter: datetimeformatter }, { field: 'Level', title: '@_localizer["Level"]', sortable: true, width: 130 }, { field: 'Message', title: '@_localizer["Message"]', sortable: true, width: 200 }, { field: 'UserName', title: '@_localizer["User Name"]', sortable: true, width: 120 }, { field: 'Exception', title: '@_localizer["Exception"]', sortable: true, width: 200 }, { field: 'Properties', title: '@_localizer["Properties"]', sortable: true, width: 200 }, { field: 'MessageTemplate', title: '@_localizer["Message Template"]', sortable: true, width: 200 }, ]] }) .datagrid('enableFilter', [ { field: 'TimeStamp', type: 'dateRange' }, { field: 'Level', type: 'combobox', options: { panelHeight: 'auto', data: [{ value: null, text: 'ALL' }, @foreach (var val in Enum.GetNames(typeof(Serilog.Events.LogEventLevel))) { <text> { value: '@val', text: '@val' }, </text> } ] } } ]) .datagrid('load', '@Url.Page("/Logs/Index")?handler=Data'); } var reload = () => { $dg.datagrid('load', '@Url.Page("/Logs/Index")?handler=Data'); } $(() => { initdatagrid(); }) var onExport = () => { var options = $dg.datagrid('options'); var data = { filterRules: JSON.stringify(options.filterRules), sort: options.sortName, order: options.sortOrder, } console.log(options, data) var headers = { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() } axios.post('@Url.Page("/Logs/Index")?handler=Export', data, { headers: headers, responseType: "blob" }) .then(response => { const filename = getFileName(response.headers['content-disposition']); const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })); const link = document.createElement('a'); link.href = url; link.setAttribute('download', filename); document.body.appendChild(link); link.click(); toastr["info"](`@_localizer["Export Success"]`); }) } var getFileName = (disposition) => { const utf8FilenameRegex = /filename\*=UTF-8''([\w%\-\.]+)(?:; ?|$)/; const asciiFilenameRegex = /filename=(["']?)(.*?[^\\])\1(?:; ?|$)/; let fileName = ''; if (utf8FilenameRegex.test(disposition)) { fileName = decodeURIComponent(utf8FilenameRegex.exec(disposition)[1]); } else { const matches = asciiFilenameRegex.exec(disposition); if (matches != null && matches[2]) { fileName = matches[2]; } } return fileName; } </script> }
the_stack
@model Xms.Web.Customize.Models.CustomButtonsDialogModel @{ Layout = null; } <!-- (Modal) --> <div class="modal fade" id="RibbonButtonModal" tabindex="-1" role="dialog" aria-labelledby="RibbonButtonModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="RibbonButtonModalLabel"> <span class="glyphicon glyphicon-th"></span> 按钮 </h4> </div> <div class="modal-body"> <div class="container-fluid"> <div class="form-group col-sm-10"> <label class="checkbox-inline"> <input type="radio" name="iscustombutton" value="false" class="required" @(!Model.IsCustomButton ? " checked" : "") /> 所有 </label> <label class="checkbox-inline"> <input type="radio" name="iscustombutton" value="true" class="required" @(Model.IsCustomButton ? " checked" : "") /> 指定 </label> </div> </div> <div class="table-responsive@(Model.IsCustomButton?"":" hide")" id="gridview"> <table class="table table-striped table-hover table-condensed datatable" id="datatable" data-ajax="true" data-ajaxcontainer="gridview" data-ajaxcallback="ajaxgrid_reset()"> <thead> <tr> <th width="2%"><input type="checkbox" name="checkall" /></th> <th data-name="name"> 名称 </th> <th width="10%" data-name="showarea"> 显示区域 </th> <th data-name="description"> 描述 </th> </tr> </thead> <tbody> @foreach (var item in Model.Buttons) { var isChecked = Model.IsCustomButton && Model.CustomButtons.NotEmpty() ? Model.CustomButtons.Exists(n => n.Equals(item.RibbonButtonId)) : false; <tr data-dbclick="RibbonButtonsModel.selectedrow('@item.RibbonButtonId')"> <td><input type="checkbox" value="@item.RibbonButtonId" name="recordid" @(isChecked ? " checked" : "") /></td> <td>@item.Label</td> <td>@item.ShowArea</td> <td>@item.Description</td> </tr> } </tbody> </table> <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script> <script> var RibbonButtonsModel = { dialogid: '#RibbonButtonModal', dialog: $('#RibbonButtonModal'), callback : @Html.Raw(Model.CallBack), datatable: $("#RibbonButtonModal .datatable"), gridview: $("#RibbonButtonModal #gridview"), searchform: $('#RibbonButtonModal #searchForm'), pageUrl : '@app.Url', inputid : '@Html.Raw(Model.InputId)', iscustombutton:@(Model.IsCustomButton?"true":"false"), custombuttons: @Html.Raw(Model.CustomButtons.NotEmpty() ? Model.CustomButtons.SerializeToJson() : "null"), entityid: '@Html.Raw(Model.EntityId)', objectid: '@Html.Raw(Model.ObjectId)', ajaxgrid_reset : function () { Xms.Web.DataTable(RibbonButtonsModel.datatable); }, dialog_return : function () { var result = new Array(); $("#RibbonButtonModal .datatable").find("input[name=recordid]:checked").each(function (i, n) { var obj = new Object(); var $that = $(this); obj.id = $(n).val(); $("#RibbonButtonModal .datatable").find('thead>tr>th[data-name]').each(function(i, nn){ var idx = $(nn).index(); console.log($that.parents('tr:first').find('td:eq('+idx+')')); var value = $that.parents('tr:first').find('td:eq('+idx+')').text(); // eval('obj.' + + '="' + value + '"'); obj[$(nn).attr('data-name')] = value; }); //obj.name = $(n).parents('tr:first').find('td:eq('+idx+')').text(); result.push(obj); }); console.log("result",result); var obj = { objectid: RibbonButtonsModel.objectid, iscustombutton: RibbonButtonsModel.dialog.find('input[name=iscustombutton]:checked').val() == 'true' ? true : false, custombuttons: result }; var dialog = $(RibbonButtonsModel.dialogid); if (dialog.data().OpenDialogCallback) { dialog.data().OpenDialogCallback(obj, RibbonButtonsModel.inputid,RibbonButtonsModel) } else { RibbonButtonsModel.callback(obj,RibbonButtonsModel.inputid); } RibbonButtonsModel.dialog.modal('hide'); } ,selectedrow: function(id){ var result = new Array(); $("#RibbonButtonModal .datatable").find("input[value="+id+"]").each(function (i, n) { var obj = new Object(); obj.id = $(n).val(); $("#RibbonButtonModal .datatable").find('thead>tr>th[data-name]').each(function(i, nn){ var idx = $("#RibbonButtonModal .datatable").find('thead>tr>th').index($(nn)); var value = $(n).parents('tr:first').find('td:eq('+idx+')').text(); eval('obj.' + $(nn).attr('data-name') + '="' + value + '"'); }); //obj.name = $(n).parents('tr:first').find('td:eq('+idx+')').text(); result.push(obj); }); console.log("return",result); RibbonButtonsModel.callback(result,RibbonButtonsModel.inputid); RibbonButtonsModel.dialog.modal('hide'); } ,CreateRecord: function(){ var url = ORG_SERVERURL +'/customize/RibbonButton/createRibbonButton?solutionid=' + (RibbonButtonsModel.solutionid || $.getUrlParam('solutionid')) + '&entityid=' + RibbonButtonsModel.entityid; Xms.Web.OpenWindow(url); } }; $(function () { RibbonButtonsModel.ajaxgrid_reset(); RibbonButtonsModel.searchform.ajaxSearch(RibbonButtonsModel.gridview.prop('id'), RibbonButtonsModel.ajaxgrid_reset); RibbonButtonsModel.datatable.ajaxTable(); RibbonButtonsModel.dialog.modal({ backdrop:'static' }); $("#RibbonButtonModal .datatable").on('hidden.bs.modal', function () { Xms.Web.CloseDialog(RibbonButtonsModel.dialogid); }); RibbonButtonsModel.dialog.on('click','button[name=createBtn]',function(e){ RibbonButtonsModel.CreateRecord(); }); RibbonButtonsModel.dialog.on('click', 'input[name=iscustombutton]', function (e) { var flag = $(this).val(); if (flag == 'true') { RibbonButtonsModel.gridview.removeClass('hide'); RibbonButtonsModel.iscustombutton = true; } else { RibbonButtonsModel.gridview.addClass('hide'); RibbonButtonsModel.iscustombutton = false; } }); }); </script> </div> </div> <div class="modal-footer"> <div class="pull-left"> <button type="button" class="btn btn-link" name="createBtn"> <span class="glyphicon glyphicon-plus-sign"></span> 新建 </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal"> <span class="glyphicon glyphicon-remove"></span> 关闭 </button> <button type="button" class="btn btn-primary" onclick="RibbonButtonsModel.dialog_return()"> <span class="glyphicon glyphicon-ok"></span> 确定 </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
the_stack
@using Tetas.Domain.Entities @using Tetas.Common.ViewModels @{ ViewData["Title"] = "Tetas"; var categoryList2 = ViewBag.Categories2; var postList = new List<Post>(); var groupList = new List<GroupModel>(); } @if (!this.User.Identity.IsAuthenticated) { <div class="text-success"> <p> @ViewBag.Message </p> </div> <div class="text-center"> <h1 class="display-4">Tracking Education For Teachers and Students</h1> <p style="text-align: justify; font-size: large"> Is an open source social networking web application that provides a robust app on which to build all kinds of social environments, from a campus wide social network for your university, school or college or an internal collaborative platform for your organization through to a brand-building communications tool for your company and its clients. But the main goal is communicate teachers and student than need to be connected but don’t want to mix personal and professional environments. If you want to see the introduction of a mini-course that I prepared, check this video: <br /> <br /> <a href="https://www.youtube.com/watch?v=-E-rAqeGKp4&t=69s&list=PLE4SNWIDX7wtQd3fA5Aa6cJExKaruJ19C&index=2"> https://www.youtube.com/watch?v=-E-rAqeGKp4&t=69s&list=PLE4SNWIDX7wtQd3fA5Aa6cJExKaruJ19C&index=2 </a> </p> </div> } else { ViewData["Title"] = "Home"; <div> <h3> Latest Post</h3> <div id="tableHolder"> <partial name="_NewsPartial" model="postList" /> </div> </div> @*<div> <h3> Dernier On Your Groups</h3> <div id="tableHolder"> <partial name="_GroupsPartial" model="groupList" /> </div> </div> <div> <h3> Today Events</h3> <div id="tableHolder"> <partial name="_NewsPartial" model="postList" /> </div> </div> <div> <h3> Dont Forget Those Celebrations</h3> <div id="tableHolder"> <partial name="_NewsPartial" model="postList" /> </div> </div> <div> <h3> Pending Chats</h3> <div id="tableHolder"> <partial name="_NewsPartial" model="postList" /> </div> </div>*@ @*<div> <h5>Icons to implement (done here because i dont want to lose time each time that i want to implement a fontawsome icons)</h5> <i class="fab fa-discourse fa-5x"></i> <i class="far fa-frown-open fa-5x"></i> <i class="fas fa-gift fa-5x"></i> <i class="far fa-meh fa-5x"></i> <i class="fas fa-meh-blank fa-5x"></i> <i class="fas fa-marker fa-5x"></i> <i class="far fa-meh-rolling-eyes fa-5x"></i> <i class="fas fa-praying-hands fa-5x"></i> My Students after fail a test XD <i class="fas fa-pray fa-5x"></i> <i class="fas fa-receipt fa-5x"></i> <i class="fas fa-random fa-5x"></i> <i class="fas fa-reply fa-5x"></i> <i class="fas fa-reply-all fa-5x"></i> <i class="fas fa-retweet fa-5x"></i> <i class="far fa-sad-tear fa-5x"></i> <i class="fas fa-share-alt fa-5x"></i> <i class="far fa-handshake fa-5x"></i> <i class="far fa-hand-peace fa-5x"></i> <i class="fas fa-hand-middle-finger fa-5x"></i> <i class="far fa-grin-tears fa-5x"></i> <i class="far fa-grin-squint-tears fa-5x"></i> <i class="far fa-grin-hearts fa-5x"></i> <i class="fas fa-glasses fa-5x"></i> <i class="fas fa-feather fa-5x"></i> <i class="fas fa-eye fa-5x"></i> <i class="far fa-edit fa-5x"></i> <i class="fab fa-angellist fa-5x"></i> <i class="fas fa-asterisk fa-5x"></i> <i class="fab fa-bity fa-5x"></i> <i class="fab fa-black-tie fa-5x"></i> <i class="fas fa-bolt fa-5x"></i> <i class="fas fa-signature fa-5x"></i> <i class="fas fa-sign-out-alt fa-5x"></i> <i class="fas fa-sign-in-alt fa-5x"></i> <i class="fas fa-sign fa-5x"></i> <i class="fas fa-shipping-fast fa-5x"></i> <i class="far fa-smile-beam fa-5x"></i> <i class="fas fa-spinner fa-5x"></i><i class="fas fa-step-backward fa-5x"></i><i class="far fa-sticky-note fa-5x"></i><i class="fas fa-bomb fa-5x"></i> <i class="fas fa-certificate fa-5x"></i> <i class="fas fa-circle-notch fa-5x"></i> <i class="far fa-atom-alt fa-5x"></i> <i class="fas fa-tasks fa-5x"></i> <i class="fas fa-thumbtack fa-5x"></i> <i class="fas fa-toilet fa-5x"></i> <i class="fas fa-user-md fa-5x"></i><i class="fas fa-users fa-5x"></i><i class="fas fa-user-minus fa-5x"></i><i class="fas fa-user-plus fa-5x"></i><i class="fas fa-user-edit fa-5x"></i> <i class="fas fa-times fa-5x"></i><i class="fas fa-users-cog fa-5x"></i><i class="fas fa-user-friends fa-5x"></i> <i class="fas fa-user-nurse fa-5x"></i> <i class="fas fa-user-cog fa-5x"></i><i class="fas fa-user-alt-slash fa-5x"></i><i class="fas fa-user fa-5x"></i><i class="fas fa-universal-access fa-5x"></i> <i class="far fa-times-circle fa-5x"></i><i class="fas fa-thumbtack fa-5x"></i> <i class="fas fa-tools fa-5x"></i><i class="fas fa-mobile-alt fa-5x"></i> <i class="fas fa-exclamation fa-5x"></i><i class="fas fa-check fa-5x"></i><i class="fas fa-diagnoses fa-5x"></i> <i class="fas fa-donate fa-5x"></i> <i class="fas fa-vote-yea fa-5x"></i> <i class="fas fa-quote-left fa-5x"></i> <i class="fas fa-quote-right fa-5x"></i> <i class="fas fa-exclamation-triangle fa-5x"></i><i class="far fa-dot-circle fa-5x"></i> <i class="fas fa-notes-medical fa-5x"></i><i class="fas fa-book-open fa-5x"></i> <i class="fas fa-hand-holding-usd fa-5x"></i><i class="fas fa-money-check fa-5x"></i><i class="fas fa-dollar-sign fa-5x"></i><i class="fas fa-hand-holding-usd fa-5x"></i> <i class="fas fa-file-invoice-dollar fa-5x"></i><i class="far fa-money-bill-alt fa-5x"></i><i class="fas fa-money-check-alt fa-5x"></i><i class="fas fa-money-bill-wave fa-5x"></i> <i class="fas fa-poop fa-5x"></i><i class="fas fa-poo-storm fa-5x"></i><i class="fas fa-pencil-alt fa-5x"></i><i class="far fa-hand-point-up fa-5x"></i> <i class="far fa-hand-point-down fa-5x"></i><i class="fas fa-hospital-symbol fa-5x"></i><i class="fas fa-hashtag fa-5x"></i> <i class="fas fa-procedures fa-5x"></i><i class="far fa-hand-point-left fa-5x"></i><i class="far fa-comments fa-5x"></i> <i class="far fa-comment-alt fa-5x"></i><i class="fas fa-comment-medical fa-5x"></i> <i class="fas fa-comments-dollar fa-5x"></i> <i class="far fa-comment-dots fa-5x"></i><i class="fas fa-comment-dollar fa-5x"></i><i class="far fa-trash-alt fa-5x"></i> <i class="fas fa-pills fa-5x"></i><i class="fas fa-trophy fa-5x"></i><i class="fas fa-tv fa-5x"></i><i class="fas fa-laptop fa-5x"></i><i class="far fa-database fa-5x"></i><i class="far fa-desktop fa-5x"></i> <i class="fas fa-download fa-5x"></i><i class="far fa-server fa-5x"></i><i class="fal fa-tv-retro fa-5x"></i><i class="fal fa-upload fa-5x"></i><i class="fas fa-brackets-curly fa-5x"></i><i class="fas fa-brackets fa-5x"></i> <i class="far fa-save fa-5x"></i><i class="fas fa-file-alt fa-5x"></i><i class="fal fa-file fa-5x"></i><i class="far fa-file-excel fa-5x"></i><i class="fas fa-file-image fa-5x"></i><i class="far fa-folder fa-5x"></i><i class="far fa-folder-open fa-5x"></i><i class="fal fa-comment-alt-edit fa-5x"></i><i class="fal fa-comment-alt-exclamation fa-5x"></i><i class="far fa-comment-alt-lines fa-5x"></i><i class="far fa-comment-alt-smile fa-5x"></i><i class="far fa-comment-alt-times fa-5x"></i><i class="far fa-comment-edit fa-5x"></i><i class="fas fa-comment-slash fa-5x"></i> <i class="far fa-surprise fa-5x"></i> </div>*@ <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } <script> var url = '@Url.Action("PostFilter", "Home")'; $(document).ready(function () { // $('#BtnSearch').click(function(e) { //opParam: $('input[type=radio]:checked').val(), // param: $('#option0').val() //$(function () { // $('#load').on('click', function () { // $('#grid').load('/ajaxpartial?handler=PostFilter'); // }); //}); //data: {opParam: $("#Insurances option:selected").val(), // category: $("#Categories option:selected").val(), // fromDate: $('#FromDate').val(), // toDate: $('#ToDate').val() $.ajax({ type: "POST", url: url, //call your controller and action data: {}, success: function (data) { if (data != null && (data.errorMessage == null || data.errorMessage === "")) { $('#newsContent').html(data); // Get the file name for download //if (data.fileName != "") //{ // // use window.location.href for redirect to download action for download the file // // window.location.href = url2 + "/?file=" + data.fileName; //} } else { alert("An error ocurred", data.errorMessage); } // enableAllButtons(); }, failure: function() { // enableAllButtons(); console.log("problems retriving post data"); } }); //$.get($(this).attr('href'), // { // }, // function(result) { // // console.log(result); // $('#tableHolder').html(result.Table); // $('#newsTable').DataTable({ // "searching": false // }); // }, // 'json'); //}); @*url = '@Url.Action("GroupsFilter", "Home")'; $.ajax({ type: "POST", url: url, //call your controller and action data: {}, success: function (data) { if (data != null && (data.errorMessage == null || data.errorMessage === "")) { $('#groupsContent').html(data); } else { alert("An error ocurred", data.errorMessage); } }, failure: function() { console.log("problems retriving group data"); } });*@ }); </script> }
the_stack
using Octokit; var isRunningOnGitHubActions = BuildSystem.GitHubActions.IsRunningOnGitHubActions; var target = Argument("target", "Default"); var isPublish = target == "Publish"; var configuration = Argument("configuration", "Release"); var isRunningOnUnix = IsRunningOnUnix(); var isRunningOnWindows = IsRunningOnWindows(); var releaseNotes = ParseReleaseNotes("./CHANGELOG.md"); var version = releaseNotes.Version.ToString(); if (isRunningOnGitHubActions) { var buildNumber = BuildSystem.GitHubActions.Environment.Workflow.RunNumber; if (target == "Default") { version = $"{version}-ci-{buildNumber}"; } else if (target == "PrePublish") { version = $"{version}-alpha-{buildNumber}"; } } var buildDir = Directory("./src/Mages.Core/bin") + Directory(configuration) + Directory("netstandard2.0"); var replDir = Directory("./src/Mages.Repl/bin") + Directory(configuration) + Directory("netcoreapp3.1"); var installerDir = Directory("./src/Mages.Repl.Installer/bin") + Directory(configuration) + Directory("net45"); var buildResultDir = Directory("./bin") + Directory(version); var nugetRoot = buildResultDir + Directory("nuget"); var chocolateyRoot = buildResultDir + Directory("chocolatey"); var squirrelRoot = buildResultDir + Directory("squirrel"); var releaseDir = squirrelRoot + Directory("release"); // Initialization // ---------------------------------------- Setup(context => { Information("Building version {0} of MAGES.", version); Information("For the publish target the following environment variables need to be set:"); Information("* NUGET_API_KEY"); Information("* CHOCOLATEY_API_KEY"); Information("* GITHUB_API_TOKEN"); }); // Tasks // ---------------------------------------- Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildDir, installerDir, buildResultDir, nugetRoot, chocolateyRoot, squirrelRoot }); }); Task("Restore-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./src/Mages.sln"); }); Task("Update-Assembly-Version") .Does(() => { ReplaceRegexInFiles("./src/Directory.Build.props", "(?<=<Version>)(.+?)(?=</Version>)", version); }); Task("Build") .IsDependentOn("Restore-Packages") .IsDependentOn("Update-Assembly-Version") .Does(() => { DotNetCoreBuild($"./src/Mages.sln", new DotNetCoreBuildSettings { Configuration = configuration, }); DotNetCoreBuild($"./src/Mages.Repl/Mages.Repl.csproj", new DotNetCoreBuildSettings { Configuration = configuration, }); DotNetCoreBuild($"./src/Mages.Repl.Installer/Mages.Repl.Installer.csproj", new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration, }; if (isRunningOnGitHubActions) { settings.Loggers.Add("GitHubActions"); } DotNetCoreTest($"./src/Mages.Core.Tests/", settings); DotNetCoreTest($"./src/Mages.Repl.Tests/", settings); }); Task("Copy-Files") .IsDependentOn("Build") .Does(() => { var nugetBin = nugetRoot + Directory("lib") + Directory("netstandard2.0"); var squirrelBin = squirrelRoot + Directory("lib") + Directory("net45"); CreateDirectory(nugetBin); CreateDirectory(squirrelBin); CopyFiles(new FilePath[] { buildDir + File("Mages.Core.dll"), buildDir + File("Mages.Core.xml") }, nugetBin); CopyDirectory(replDir, squirrelBin); CopyDirectory(installerDir, squirrelBin); CopyFile("src/Mages.Nuget.nuspec", nugetRoot + File("Mages.nuspec")); CopyFile("src/Mages.Chocolatey.nuspec", chocolateyRoot + File("Mages.nuspec")); CopyFile("src/Mages.Squirrel.nuspec", squirrelRoot + File("Mages.nuspec")); DeleteFiles(GetFiles(squirrelBin.Path.FullPath + "/*.pdb")); DeleteFiles(GetFiles(squirrelBin.Path.FullPath + "/*.vshost.*")); }); Task("Create-Nuget-Package") .IsDependentOn("Copy-Files") .Does(() => { var nugetExe = GetFiles("./tools/**/nuget.exe").FirstOrDefault(); if (nugetExe == null) { throw new InvalidOperationException("Could not find nuget.exe."); } var nuspec = nugetRoot + File("Mages.nuspec"); NuGetPack(nuspec, new NuGetPackSettings { Version = version, OutputDirectory = nugetRoot, Symbols = false, Properties = new Dictionary<String, String> { { "Configuration", configuration } } }); }); Task("Publish-Nuget-Package") .IsDependentOn("Create-Nuget-Package") .Does(() => { var apiKey = EnvironmentVariable("NUGET_API_KEY"); if (String.IsNullOrEmpty(apiKey)) { throw new InvalidOperationException("Could not resolve the NuGet API key."); } foreach (var nupkg in GetFiles(nugetRoot.Path.FullPath + "/*.nupkg")) { NuGetPush(nupkg, new NuGetPushSettings { Source = "https://nuget.org/api/v2/package", ApiKey = apiKey }); } }); Task("Create-Squirrel-Package") .IsDependentOn("Copy-Files") .WithCriteria(() => isRunningOnWindows) .Does(() => { var nugetExe = GetFiles("./tools/**/nuget.exe").FirstOrDefault(); if (nugetExe == null) { throw new InvalidOperationException("Could not find nuget.exe."); } var spec = squirrelRoot + File("Mages.nuspec"); CreateDirectory(releaseDir); NuGetPack(spec, new NuGetPackSettings { Version = version, BasePath = squirrelRoot, OutputDirectory = squirrelRoot, Symbols = false }); var fileName = "Mages." + version + ".nupkg"; var package = squirrelRoot + File(fileName); Squirrel(package, new SquirrelSettings { Silent = true, NoMsi = true, ReleaseDirectory = releaseDir, SetupIcon = GetFiles("./src/Mages.Repl.Installer/mages.ico").First().FullPath }); }); Task("Create-Chocolatey-Package") .IsDependentOn("Copy-Files") .WithCriteria(() => isRunningOnWindows) .Does(() => { var content = String.Format("$packageName = 'Mages'{1}$installerType = 'exe'{1}$url32 = 'https://github.com/FlorianRappl/Mages/releases/download/v{0}/Mages.exe'{1}$silentArgs = ''{1}{1}Install-ChocolateyPackage \"$packageName\" \"$installerType\" \"$silentArgs\" \"$url32\"", version, Environment.NewLine); var nuspec = chocolateyRoot + File("Mages.nuspec"); var toolsDirectory = chocolateyRoot + Directory("tools"); var scriptFile = toolsDirectory + File("chocolateyInstall.ps1"); CreateDirectory(toolsDirectory); System.IO.File.WriteAllText(scriptFile.Path.FullPath, content); ChocolateyPack(nuspec, new ChocolateyPackSettings { Version = version, OutputDirectory = chocolateyRoot }); }); Task("Publish-Chocolatey-Package") .IsDependentOn("Create-Chocolatey-Package") .WithCriteria(() => isRunningOnWindows) .Does(() => { var apiKey = EnvironmentVariable("CHOCOLATEY_API_KEY"); var fileName = "Mages." + version + ".nupkg"; var package = chocolateyRoot + File(fileName); if (String.IsNullOrEmpty(apiKey)) { throw new InvalidOperationException("Could not resolve the Chocolatey API key."); } ChocolateyPush(package, new ChocolateyPushSettings { Source = "https://chocolatey.org/", ApiKey = apiKey }); }); Task("Publish-GitHub-Release") .IsDependentOn("Publish-Packages") .Does(() => { var githubToken = EnvironmentVariable("GITHUB_API_TOKEN"); if (String.IsNullOrEmpty(githubToken)) { throw new InvalidOperationException("Could not resolve MAGES GitHub token."); } var github = new GitHubClient(new ProductHeaderValue("MagesCakeBuild")) { Credentials = new Credentials(githubToken) }; var newRelease = github.Repository.Release; var release = newRelease.Create("FlorianRappl", "Mages", new NewRelease("v" + version) { Name = version, Body = String.Join(Environment.NewLine, releaseNotes.Notes), Prerelease = !isPublish, TargetCommitish = isPublish ? "main" : "devel" }).Result; var target = nugetRoot + Directory("lib") + Directory("netstandard2.0"); var libPath = target + File("Mages.Core.dll"); var releaseFiles = GetFiles(releaseDir.Path.FullPath + "/*"); using (var libStream = System.IO.File.OpenRead(libPath.Path.FullPath)) { newRelease.UploadAsset(release, new ReleaseAssetUpload("Mages.Core.dll", "application/x-msdownload", libStream, null)).Wait(); } foreach (var file in releaseFiles) { var name = System.IO.Path.GetFileName(file.FullPath); if (name.Equals("Setup.exe")) { name = "Mages.exe"; } using (var fileStream = System.IO.File.OpenRead(file.FullPath)) { newRelease.UploadAsset(release, new ReleaseAssetUpload(name, "application/x-msdownload", fileStream, null)).Wait(); } } }); // Targets // ---------------------------------------- Task("Package") .IsDependentOn("Run-Unit-Tests") .IsDependentOn("Create-Squirrel-Package") .IsDependentOn("Create-Chocolatey-Package") .IsDependentOn("Create-Nuget-Package"); Task("Default") .IsDependentOn("Package"); Task("Publish-Packages") .IsDependentOn("Default") .IsDependentOn("Publish-Nuget-Package") .IsDependentOn("Publish-Chocolatey-Package"); Task("Publish") .IsDependentOn("Publish-Packages") .IsDependentOn("Publish-GitHub-Release"); Task("PrePublish") .IsDependentOn("Publish-Packages") .IsDependentOn("Publish-GitHub-Release"); // Execution // ---------------------------------------- RunTarget(target);
the_stack
@inherits OurUmbraco.Our.Models.OurUmbracoTemplatePage @using System.Configuration @using Examine.Providers @using Examine.SearchCriteria @using OurUmbraco.Community.People @using OurUmbraco.Forum.Extensions @using OurUmbraco.Forum.Services @using OurUmbraco.MarketPlace.NodeListing @using OurUmbraco.Our @using OurUmbraco.Our.Extensions @{ var memberId = Request["id"]; int id = 0; var username = Request.QueryString["username"]; IPublishedContent member = null; if (!string.IsNullOrEmpty(memberId) && int.TryParse(memberId, out id)) { member = Members.GetById(id); } else if (!string.IsNullOrWhiteSpace(username)) { // Get a reference to the member searcher BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection[Constants.Examine.InternalMemberSearcher]; // Initialize new search criteria for the GitHub username ISearchCriteria criteria = searcher.CreateSearchCriteria(); criteria = criteria.RawQuery(String.Format("github:{0}", username)); // Make the search in examine ISearchResults results = searcher.Search(criteria); // Search may reveal partial matches, so we need to do an extra check in C# foreach (SearchResult result in results) { string github; if (result.Fields.TryGetValue("github", out github) && String.Equals(username, github, StringComparison.InvariantCultureIgnoreCase)) { member = Members.GetById(result.Id); break; } } } if (member == null) { <p>Member does not exist</p> return; } var currentMember = MemberData != null ? MemberData.Member : null; var ts = new TopicService(ApplicationContext.DatabaseContext); var topics = ts.GetLatestTopicsForMember(member.Id); var badges = member.GetRoles().GetBadges(); var content = Umbraco.TypedContentAtRoot().First(x => string.Equals(x.DocumentTypeAlias, "community", StringComparison.CurrentCultureIgnoreCase)) .Children.First(x => string.Equals(x.DocumentTypeAlias, "projects", StringComparison.CurrentCultureIgnoreCase)); IEnumerable<IPublishedContent> projects = new List<IPublishedContent>(); var contribProjects = new List<IPublishedContent>(); if (content != null) { projects = content.Descendants().Where(c => c.DocumentTypeAlias == "Project").Where(m => m.GetPropertyValue<int>("owner") == member.Id).Where(p => p.GetPropertyValue<bool>("projectLive")); const string sql = @"SELECT * FROM projectContributors WHERE memberId=@memberId"; var contribPackageIds = ApplicationContext.DatabaseContext.Database.Fetch<int>(sql, new { memberId }); foreach (var contribPackageId in contribPackageIds) { contribProjects.Add(Umbraco.TypedContent(contribPackageId)); } } var reputationCurrent = member.GetPropertyValue<int>("reputationCurrent"); var nodeListingProvider = new NodeListingProvider(); var votedProjects = nodeListingProvider.GetVotedProjectsForMember(member.Id); var rolesForUser = Roles.GetRolesForUser(member.GetPropertyValue<string>("UserName")); var avatarService = new AvatarService(); var avatarPath = avatarService.GetMemberAvatar(member); var img = avatarService.GetImgWithSrcSet(avatarPath, member.Name, 125); <div class="public-member"> <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col-xs-12"> <div class="member-details"> @Html.Raw(img) <div class="text"> <h3>@member.Name</h3> @if (member.HasValue("twitter") || member.HasValue("github")) { <div class="social-links"> @if (member.HasValue("twitter")) { var twitterHandle = member.GetPropertyValue<string>("twitter").Replace("@", string.Empty); <a href="https://twitter.com/@twitterHandle" title="See @member.Name's profile on Twitter" target="_blank" rel="noreferrer noopener"> <i class="icon-twitter" aria-hidden="true"></i> <span>@twitterHandle</span> </a> } @if (member.HasValue("github")) { var githubUsername = member.GetPropertyValue<string>("github").Replace("@", string.Empty); <a href="https://github.com/@githubUsername" title="See @member.Name's profile on GitHub" target="_blank" rel="noreferrer noopener"> <i class="icon-github" aria-hidden="true"></i> <span>@githubUsername</span> </a> } </div> } </div> </div> <!-- .member-details --> </div> </div> <div class="row"> <div class="col-md-12"> <div class="member-details"> @if (badges.Any()) { <span class="roles"> @foreach (var badge in badges) { if (string.IsNullOrWhiteSpace(badge.Link)) { <span class="@badge.CssClass" title="@badge.Title">@badge.Name</span> } else { <span class="@badge.CssClass"><a href="@badge.Link" title="@badge.Title">@badge.Name</a></span> } } </span> } </div> </div> </div> @if (currentMember != null && member != null && member.Id == currentMember.Id) { <div class="row"> <div class="col-md-12"> <div class="member-details"> <p>Your member id: @currentMember.Id</p> </div> </div> </div> } <div class="row"> <div class="col-md-12"> <div class="member-details"> <small> @member.Name @if (member.HasValue("location")) { <span> is from <span>@member.GetPropertyValue("location")</span></span> } @if (member.HasValue("company")) { <span> works at <span>@member.GetPropertyValue("company")</span></span> } and has <em class="posts">@member.GetPropertyValue("forumPosts")</em> @if (member.ForumPosts() == 0 || member.ForumPosts() > 1) {<text>posts</text>} else {<text>post</text>} and <em class="karma-points">@member.GetPropertyValue("reputationCurrent")</em> <span></span> karma points </small> </div> <div class="member-bio"> <p>@member.GetPropertyValue("profileText")</p> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="package-forum-activity"> <h3>Activity</h3> @foreach (var topic in topics) { var cat = Umbraco.TypedContent(topic.ParentId); // if cat == null then it's been hidden/unpublished (example: v5 forum) // if this is the case: don't show forum post in list if (cat != null) { var mem = Members.GetById(topic.LatestReplyAuthor) ?? Members.GetById(topic.MemberId); var memImg = avatarService.GetImgWithSrcSet(mem, mem.Name, 75); <a href="@topic.GetUrl()" class="forum-thread @(topic.Answer != 0 ? "solved" : null)"> <div class="row flex-center"> <div class="col-xs-2"> @Html.Raw(memImg) </div> <div class="col-xs-10"> <div class="forum-thread-text"> <h3>@topic.Title</h3> <p>Reply by @mem.Name @topic.Updated.ConvertToRelativeTime()</p> </div> <div class="category frontend"><span class="cat">@cat.Name</span></div> </div> </div> </a> } } <a class="goto" href="/forum">Go to forum &rarr;</a> </div> </div> </div> @if (projects.Any()) { <div class="row" id="created"> <div class="col-md-12"> <div class="package-forum-activity"> <h3>Packages created</h3> @foreach (var project in projects.Where(x => x.GetPropertyValue<bool>("projectLive")).OrderByDescending(x => x.CreateDate)) { <a href="@project.Url" class="forum-thread"> <div class="row"> <div class="col-xs-2"> @if (string.IsNullOrWhiteSpace(project.GetPropertyValue<string>("defaultScreenshotPath").Trim())) { <i class="icon-Box" style="font-size: 30px; padding-top: 5px; display: inline-block; color: black;"></i> } else { <img src="@Utils.GetScreenshotPath(project.GetPropertyValue<string>("defaultScreenshotPath"))?width=100&height=100&mode=crop" alt="@project.Name"> } </div> <div class="col-xs-10"> <div class="forum-thread-text"> <h3>@project.Name</h3> <p>@Umbraco.StripHtml(Umbraco.Truncate(project.GetPropertyValue<string>("description"), 120))</p> </div> </div> </div> </a> } </div> </div> </div> } @if (contribProjects.Any()) { <div class="row" id="contributed"> <div class="col-md-12"> <div class="package-forum-activity"> <h3>Packages contributed to</h3> @foreach (var project in contribProjects.Where(x => x != null && x.GetPropertyValue<bool>("projectLive")).OrderByDescending(x => x.CreateDate)) { <a href="@project.Url" class="forum-thread"> <div class="row"> <div class="col-xs-2"> @if (string.IsNullOrWhiteSpace(project.GetPropertyValue<string>("defaultScreenshotPath").Trim())) { <i class="icon-Box" style="font-size: 30px; padding-top: 5px; display: inline-block; color: black;"></i> } else { <img src="@Utils.GetScreenshotPath(project.GetPropertyValue<string>("defaultScreenshotPath"))?width=100&height=100&mode=crop" alt="@project.Name"> } </div> <div class="col-xs-10"> <div class="forum-thread-text"> <h3>@project.Name</h3> <p>@Umbraco.StripHtml(Umbraco.Truncate(project.GetPropertyValue<string>("description"), 120))</p> </div> </div> </div> </a> } </div> </div> </div> } @if (votedProjects.Any()) { <div class="row" id="voted"> <div class="col-md-12"> <div class="package-forum-activity"> <h3>Packages voted up</h3> @foreach (var project in votedProjects.Where(x => x.GetPropertyValue<bool>("projectLive")).OrderByDescending(x => x.UpdateDate)) { <a href="@project.Url" class="forum-thread"> <div class="row"> <div class="col-xs-2"> @if (string.IsNullOrWhiteSpace(project.GetPropertyValue<string>("defaultScreenshotPath").Trim())) { <i class="icon-Box" style="font-size: 30px; padding-top: 5px; display: inline-block; color: black;"></i> } else { <img src="@Utils.GetScreenshotPath(project.GetPropertyValue<string>("defaultScreenshotPath"))?width=100&height=100&mode=crop" alt="@project.Name"> } </div> <div class="col-xs-10"> <div class="forum-thread-text"> <h3>@project.Name</h3> <p>@Umbraco.StripHtml(Umbraco.Truncate(project.GetPropertyValue<string>("description"), 120))</p> <p><strong>Updated: </strong>@project.UpdateDate.ToLongDateString()</p> </div> </div> </div> </a> } </div> </div> </div> } </div> </div> </div> <!-- .public-member --> if (MemberData != null && MemberData.IsAdmin) { var allTopics = ts.GetLatestTopicsForMember(member.Id, false, 1000); <div style="border: 1px solid orange; padding: 4px;"> <p>Moderator Tools (also known as "with great power comes great responsibility"):</p><br /> @if (member.GetPropertyValue<bool>("blocked") == false) { <a href="#" class="block-member" style="color: red" rel="@member.Id">Block this member</a><br /> } else { <a href="#" class="unblock-member" style="color: green" rel="@member.Id">Unblock this member</a><br /> <strong class="member-blocked">Member is blocked</strong><br /> } <br /><br /> @if (reputationCurrent < 71 || rolesForUser.Contains("potentialspam") || rolesForUser.Contains("newaccount")) { <a href="#" class="approve-member" style="color: green" rel="@member.Id">Approve member (careful now! if you approve this member, EVERYTHING that they posted and is marked as spam will be marked as ham.. )</a><br /> } <br /><br /> <p><strong>All threads this member was involved in (created or commented)</strong></p> <ul style="margin-left: 20px;"> @foreach (var topic in allTopics) { <li><a href="@topic.GetUrl()" style="@(topic.IsSpam ? "color: orange;" : "")">@(topic.IsSpam ? "IS MARKED AS SPAM: " : "")@topic.Title</a></li> } </ul> </div> } <br /><br /> if (currentMember != null && currentMember.IsHq()) { <div style="border: 1px solid red; padding: 4px;"> <p>HQ Tools (also known as "with great power comes great responsibility"):</p><br /> @{ if (rolesForUser.Contains("potentialspam")) { <span>Member is in role "potentialspam"</span><br /> } if (rolesForUser.Contains("newaccount")) { <span>Member is in role "newaccount"</span><br /> } } <br /><br /> <a href="#" class="delete-member-plus" style="color: red" rel="@member.Id">Delete this member including all their topics and comments</a><br /> </div> } } <script type="text/javascript" src="/scripts/powers/uPowers.js"></script>
the_stack
using System; using Foundation; using AppKit; using CoreGraphics; // ========================================================================== // NOTE: This file contains the backing resources to create the Windows, // View Controllers and View needed to support the Working with Toolbars // Workbook. The implementation of these controllers is not important to // understanding the `NSToolBar` control so they have been moved here. // ========================================================================== /// <summary> /// The LayerBackedView class is used to create a modern View within a /// View Controller that is backed by a Core Graphics Layer. /// </summary> public class LayerBackedView : NSView { #region Private Variables /// <summary> /// The color of the background. /// </summary> private NSColor _backgroundColor = NSColor.White; #endregion #region Computed Properties /// <summary> /// Gets a value indicating whether this <see cref="T:LayerBackedView"/> wants layer. /// </summary> /// <value><c>true</c> if wants layer; otherwise, <c>false</c>.</value> public override bool WantsLayer { get { return true; } } /// <summary> /// Gets a value indicating whether this <see cref="T:LayerBackedView"/> wants to update /// the layer. /// </summary> /// <value><c>true</c> if wants update layer; otherwise, <c>false</c>.</value> public override bool WantsUpdateLayer { get { return true; } } /// <summary> /// Gets or sets the color of the background. /// </summary> /// <value>The color of the background.</value> public NSColor BackgroundColor { get { return _backgroundColor; } set { // Save color _backgroundColor = value; // Force the view to update NeedsDisplay = true; } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:LayerBackedView"/> class. /// </summary> /// <param name="handle">Handle.</param> public LayerBackedView (IntPtr handle) : base (handle) { } /// <summary> /// Initializes a new instance of the <see cref="T:LayerBackedView"/> class. /// </summary> /// <param name="bounds">Bounds.</param> public LayerBackedView (CGRect bounds) : base (bounds) { } #endregion #region Override Methods /// <summary> /// Updates the layer. /// </summary> public override void UpdateLayer () { base.UpdateLayer (); // Add the Core Graphics routines to draw the View's UI Layer.BackgroundColor = _backgroundColor.CGColor; } #endregion } /// <summary> /// Traditional code based window that uses the traditional look and feel /// of an OS X Window. Typically this Window would be created in a Xcode /// Interface Builder `.storyboard` file. For the sake of this workbook, /// the Window is being created in code. /// </summary> public class TraditionalCodeBasedWindow : NSWindow { #region Computed Properties /// <summary> /// Gets or sets the click me label. /// </summary> /// <value>The click me label.</value> public NSTextField ClickMeLabel { get; set; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindow"/> class. /// </summary> /// <param name="handle">Handle.</param> public TraditionalCodeBasedWindow (IntPtr handle) : base (handle) { } /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindow"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public TraditionalCodeBasedWindow (NSCoder coder) : base (coder) { } /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindow"/> class. /// </summary> /// <param name="contentRect">Content rect.</param> /// <param name="aStyle">A style.</param> /// <param name="bufferingType">Buffering type.</param> /// <param name="deferCreation">If set to <c>true</c> defer creation.</param> public TraditionalCodeBasedWindow (CGRect contentRect, NSWindowStyle aStyle, NSBackingStore bufferingType, bool deferCreation) : base (contentRect, aStyle, bufferingType, deferCreation) { // Create a default title for the window Title = "Untitled"; // Create the content view for the window and make it fill the window ContentView = new LayerBackedView (Frame); // _________________________________________________________________ // WARNING! // The modern macOS App UI is currently unavaiable in the Version // 0.99.0.0 of Xamarin Workbooks. This feature will be restored in a // future release. // _________________________________________________________________ // Configure the Window to use Tabs // TabbingMode = NSWindowTabbingMode.Preferred; // TabbingIdentifier = "Traditional"; // Define Window UI ClickMeLabel = new NSTextField (new CGRect (10, Frame.Height - 125, Frame.Width - 20, 20)) { BackgroundColor = NSColor.Clear, TextColor = NSColor.LabelColor, Editable = false, Bezeled = false, AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MinYMargin, StringValue = "Click on a Toolbar item above." }; ContentView.AddSubview (ClickMeLabel); } #endregion #region Override Method /// <summary> /// Awakes from nib. /// </summary> public override void AwakeFromNib () { base.AwakeFromNib (); // Build and configure a new toolbar var toolbar = new MainToolbar ("TraditionalToolbar"); // Wireup toolbar events toolbar.ToolbarDelegate.ToolbarItemClicked += (identifier) => { ClickMeLabel.StringValue = $"You clicked the {identifier} Toolbar Item."; }; // Attach toolbar to window this.Toolbar = toolbar; } #endregion } /// <summary> /// Traditional code based Window Controller instantiats and controls an instance of /// the `TraditionalCodeBasedWindow` defined above. /// </summary> public class TraditionalCodeBasedWindowController : NSWindowController { #region Computed Properties /// <summary> /// Gets the window. /// </summary> /// <value>The window.</value> public new TraditionalCodeBasedWindow Window { get { return base.Window as TraditionalCodeBasedWindow; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindowController"/> class. /// </summary> /// <param name="handle">Handle.</param> public TraditionalCodeBasedWindowController (IntPtr handle) : base (handle) { } /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindowController"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public TraditionalCodeBasedWindowController (NSCoder coder) : base (coder) { } /// <summary> /// Initializes a new instance of the <see cref="T:TraditionalCodeBasedWindowController"/> class. /// </summary> public TraditionalCodeBasedWindowController () : base ("CodeBasedWindow") { // Define the Window's default location and size CGRect contentRect = new CGRect (0, 0, 600, 500); // Create a new instance of the CodeBasedWindow base.Window = new TraditionalCodeBasedWindow (contentRect, (NSWindowStyle.Titled | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Resizable | NSWindowStyle.FullSizeContentView), NSBackingStore.Buffered, false); // Simulate Awaking from Nib Window.AwakeFromNib (); } #endregion #region Override Methods /// <summary> /// Awakes from nib. /// </summary> public override void AwakeFromNib () { base.AwakeFromNib (); } // _________________________________________________________________ // WARNING! // The modern macOS App UI is currently unavaiable in the Version // 0.99.0.0 of Xamarin Workbooks. This feature will be restored in a // future release. // _________________________________________________________________ /// <summary> /// Gets the new window for tab. /// </summary> /// <param name="sender">Sender.</param> // public override void GetNewWindowForTab (NSObject sender) // { // // Create a new window when the Plus button is clicked // ToolbarResources.OpenNewTraditionalWindow (); // } #endregion } /// <summary> /// Modern code based window that uses the modern look and feel /// of a macOS Sierra Window. Typically this Window would be created in a Xcode /// Interface Builder `.storyboard` file. For the sake of this workbook, /// the Window is being created in code. /// </summary> public class ModernCodeBasedWindow : NSWindow { #region Computed Properties /// <summary> /// Gets or sets the click me label. /// </summary> /// <value>The click me label.</value> public NSTextField ClickMeLabel { get; set; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindow"/> class. /// </summary> /// <param name="handle">Handle.</param> public ModernCodeBasedWindow (IntPtr handle) : base (handle) { } /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindow"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public ModernCodeBasedWindow (NSCoder coder) : base (coder) { } /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindow"/> class. /// </summary> /// <param name="contentRect">Content rect.</param> /// <param name="aStyle">A style.</param> /// <param name="bufferingType">Buffering type.</param> /// <param name="deferCreation">If set to <c>true</c> defer creation.</param> public ModernCodeBasedWindow (CGRect contentRect, NSWindowStyle aStyle, NSBackingStore bufferingType, bool deferCreation) : base (contentRect, aStyle, bufferingType, deferCreation) { // Create a default title for the window Title = "Untitled"; // Select the dark appearance Appearance = NSAppearance.GetAppearance (NSAppearance.NameVibrantDark); // Create the content view for the window and make it fill the window ContentView = new LayerBackedView (Frame); // Hide the Title bar for a streamlined UI TitleVisibility = NSWindowTitleVisibility.Hidden; // _________________________________________________________________ // WARNING! // The modern macOS App UI is currently unavaiable in the Version // 0.99.0.0 of Xamarin Workbooks. This feature will be restored in a // future release. // _________________________________________________________________ // Configure the Window to use Tabs // TabbingMode = NSWindowTabbingMode.Preferred; // TabbingIdentifier = "Modern"; // Define Window UI ClickMeLabel = new NSTextField (new CGRect (10, Frame.Height - 125, Frame.Width - 20, 20)) { BackgroundColor = NSColor.Clear, TextColor = NSColor.LabelColor, Editable = false, Bezeled = false, AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MinYMargin, StringValue = "Click on a Toolbar item above." }; ContentView.AddSubview (ClickMeLabel); } #endregion #region Override Method /// <summary> /// Awakes from nib. /// </summary> public override void AwakeFromNib () { base.AwakeFromNib (); // Build and configure a new toolbar var toolbar = new MainToolbar ("ModernToolbar"); // Wireup toolbar events toolbar.ToolbarDelegate.ToolbarItemClicked += (identifier) => { ClickMeLabel.StringValue = $"You clicked the {identifier} Toolbar Item."; }; // Attach toolbar to window this.Toolbar = toolbar; } #endregion } /// <summary> /// Modern code based Window Controller instantiats and controls an instance of /// the `ModernCodeBasedWindow` defined above. /// </summary> public class ModernCodeBasedWindowController : NSWindowController { #region Computed Properties /// <summary> /// Gets the window. /// </summary> /// <value>The window.</value> public new ModernCodeBasedWindow Window { get { return base.Window as ModernCodeBasedWindow; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindowController"/> class. /// </summary> /// <param name="handle">Handle.</param> public ModernCodeBasedWindowController (IntPtr handle) : base (handle) { } /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindowController"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public ModernCodeBasedWindowController (NSCoder coder) : base (coder) { } /// <summary> /// Initializes a new instance of the <see cref="T:ModernCodeBasedWindowController"/> class. /// </summary> public ModernCodeBasedWindowController () : base ("CodeBasedWindow") { // Define the Window's default location and size CGRect contentRect = new CGRect (0, 100, 600, 500); // Create a new instance of the CodeBasedWindow base.Window = new ModernCodeBasedWindow (contentRect, (NSWindowStyle.Titled | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Resizable | NSWindowStyle.FullSizeContentView | NSWindowStyle.UnifiedTitleAndToolbar), NSBackingStore.Buffered, false); // Simulate Awaking from Nib Window.AwakeFromNib (); } #endregion #region Override Methods /// <summary> /// Awakes from nib. /// </summary> public override void AwakeFromNib () { base.AwakeFromNib (); } // _________________________________________________________________ // WARNING! // The modern macOS App UI is currently unavaiable in the Version // 0.99.0.0 of Xamarin Workbooks. This feature will be restored in a // future release. // _________________________________________________________________ /// <summary> /// Gets the new window for tab. /// </summary> /// <param name="sender">Sender.</param> // public override void GetNewWindowForTab (NSObject sender) // { // // Create a new window when the Plus button is clicked // ToolbarResources.OpenNewModernWindow (); // } #endregion } /// <summary> /// Toolbar resources is a static helper class that creates and maintains /// instances of the Windows, View Controllers and Views needed to support /// playing with a `NSToolbar` control in a Workbook. /// </summary> public static class ToolbarResources { #region Computed Properties /// <summary> /// Gets or sets the traditional window count. /// </summary> /// <value>The traditional window count.</value> public static int TraditionalWindowCount { get; set; } = 0; /// <summary> /// Gets or sets the last traditional window controller. /// </summary> /// <value>The last traditional window controller.</value> public static TraditionalCodeBasedWindowController LastTraditionalWindowController { get; set; } = null; /// <summary> /// Gets or sets the modern window count. /// </summary> /// <value>The modern window count.</value> public static int ModernWindowCount { get; set; } = 0; /// <summary> /// Gets or sets the last modern window controller. /// </summary> /// <value>The last modern window controller.</value> public static ModernCodeBasedWindowController LastModernWindowController { get; set; } = null; #endregion #region Controller Factories /// <summary> /// Opens and displays a new traditional window. /// </summary> public static void OpenNewTraditionalWindow () { // Create a new instace of the Traditional Window Controller LastTraditionalWindowController = new TraditionalCodeBasedWindowController (); // Set the title LastTraditionalWindowController.Window.Title = (TraditionalWindowCount++ == 0) ? "Untitled" : $"Untitled {TraditionalWindowCount}"; // Display the Window LastTraditionalWindowController.Window.MakeKeyAndOrderFront ((NSObject)NSApplication.SharedApplication.Delegate); } /// <summary> /// Opens and displays a new modern window. /// </summary> public static void OpenNewModernWindow () { // Create a new instace of the Traditional Window Controller LastModernWindowController = new ModernCodeBasedWindowController (); // Set the title LastModernWindowController.Window.Title = (ModernWindowCount++ == 0) ? "Untitled" : $"Untitled {ModernWindowCount}"; // Display the Window LastModernWindowController.Window.MakeKeyAndOrderFront ((NSObject)NSApplication.SharedApplication.Delegate); } #endregion }
the_stack
@using YL.Utils.Json; @{ Layout = "_LayoutH"; @model YL.Core.Dto.Wms_invmovedetailDto } @section styles{ <link rel="stylesheet" href="~/css/bootstrap-select.min.css" /> } <div id="app" v-cloak> <form class="form-horizontal" onsubmit="return false"> <div class="box-body"> <table class="table table-bordered"> <tr> @*<td> <div class="form-group"> <label class="form-label col-sm-2">源货架</label> <div class="col-sm-10"> <input class="form-control" readonly v-model="Storagerack" type="text"> </div> </div> </td>*@ <td colspan="2"> <div class="form-group"> <label class="col-sm-2 control-label">物料</label> <div class="col-sm-10"> <select size="1" id="MaterialId" v-model="MaterialId" class="show-menu-arrow show-tick selectpicker form-control" data-live-search="true"></select> </div> </div> </td> </tr> <tr> <td> <div class="form-group"> <label class="form-label col-sm-2">库存数量</label> <div class="col-sm-10"> <input class="form-control" readonly v-model="Qty" type="text"> </div> </div> </td> <td> <div class="form-group"> <label class="col-sm-2 control-label">实际数量</label> <div class="col-sm-10"> <input class="form-control" v-model="ActQty" v-focus type="text"> </div> </div> </td> </tr> <tr> <td colspan="2"> <div class="form-group"> <label class="col-sm-2 control-label">备注</label> <div class="col-sm-10"> <textarea v-model="Remark" class="form-control" rows="3" placeholder="备注...100个字符以内"></textarea> <p class="textarea-numberbar"><em class="textarea-length">{{count}}</em>/100</p> </div> </div> </td> </tr> <tr> <td> <input v-on:click="addD" class="btn btn-primary radius" type="submit" v-model="addDe"> </td> <td> <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit"> </td> </tr> <tr> <td colspan="2"> <div class="form-group"> <table class="table table-bordered text-nowrap table-hover" id="bootstraptable"> <thead> <tr> <th data-field="MaterialNo">物料编号</th> <th data-field="MaterialName">物料名称</th> <th data-field="Qty">库存数量</th> <th data-field="ActQty">实际数量</th> <th data-field="Remark">备注</th> <th data-field="InventorymoveId" data-visible="false">InventorymoveId</th> <th data-formatter="operateFormatter" data-events="operateEvents">删除</th> </tr> </thead> </table> </div> </td> </tr> </table> </div> @*<div class="box-footer"> <div class="pull-right box-tools"> <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit"> </div> </div>*@ </form> </div> @section scripts{ <script src="~/js/bootstrap-select.min.js"></script> <script src="~/js/defaults-zh_CN.min.js"></script> <script> $(function () { $('#MaterialId').on('show.bs.select', function (e, clickedIndex, isSelected, previousValue) { var divdom = $("div[class='bs-searchbox']")[0].childNodes[0]; $(divdom).on("input propertychange", function () { var dom = $("li[class='no-results']"); var text = divdom.value; if (dom.length > 0) { app.searchMaterial(text, 2); } if (app.MaterialList.length <= 0) { app.searchMaterial(text, 2); } }); }); $("#bootstraptable").bootstrapTable({ data: app.list }); //$('#MaterialId').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { //}); }); function operateFormatter(value, row, index) { //fa-heart return [ '<a class="remove" href="javascript:void(0)" title="Remove">', '<i class="fa fa-trash">删除</i>', '</a>' ].join('') }; window.operateEvents = { //删除选中行 'click .remove': function (e, value, row, index) { $("#bootstraptable").bootstrapTable('remove', { field: 'MaterialNo', values: [row.MaterialNo] }) } } var app = new Vue({ el: "#app", data: { addDe:'添加明细', submit: "添加", Storagerack: '', SStoragerackId:'@Model.SourceStoragerackId', AStoragerackId:'@Model.AimStoragerackId', MaterialId:"@Model.MaterialId", MaterialNo:"", MaterialName:"", InventorymoveId:"@Model.Pid", MoveDetailId:"@Model.MoveDetailId", Remark: "@Model.Remark", ActQty: "@Model.ActQty", MaterialList: [], StorageRackList: [], updateList:@Html.Raw(Model.Detail.JilToJson()), Qty: "", urlM: '', list: [], }, computed: { count: function () { return this.strLength(this.Remark, false); } }, watch: { MaterialId: function (val) { var _self = this; _self.Qty = ""; _self.qtyL(val); //yui.$axiosget('/StockOut/SearchInventory?id='+val).then(function (res) { // _self.StorageRackList = res.data.rows; // _self.qtyL(_self.SStoragerackId); //}).catch(function (res) { //}); }, updateList: function () { var _self = this; var obj = _self.updateList; if (obj.length > 0) { for (var item in obj) { var a = obj[item]; var data = { "MaterialId": a.MaterialId, "MaterialNo": a.MaterialNo, "MaterialName": a.MaterialName, "Qty": a.Qty, "ActQty": a.ActQty, "Remark": a.Remark, "Status": a.Status, "InventorymoveId": a.InventorymoveId, } _self.list.push(data); } } } }, mounted: function(){ var _self = this; _self.$nextTick(function () { $("#MaterialId").selectpicker({ noneSelectedText: '请选择', }); _self.updateList=@Html.Raw(Model.Detail.JilToJson()); _self.searchMaterial("", 1); $("#bootstraptable").bootstrapTable("prepend", _self.list); }); }, methods: { searchMaterial: function (val,type) { var _self = this; if (type === 1) { //_self.urlM = "/Material/Search"; _self.urlM = "/StockOut/SearchInventory?storagerackId=" + _self.SStoragerackId; } else { _self.urlM = "/StockOut/SearchInventory?id" + val + "&storagerackId="+ _self.SStoragerackId; } yui.$axiosget(_self.urlM).then(function (res) { _self.StorageRackList=_self.MaterialList = res.data.rows; var html = "<option value=''>请选择</option>"; for (var item in _self.MaterialList) { var a = _self.MaterialList[item]; html += "<option value='" + a.MaterialId + "' " + "data-subtext='" + a.MaterialNo + "'>" + a.MaterialName + "</option>" } if (type !== 1) { $("#MaterialId").empty(); } $("#MaterialId").append(html) $('#MaterialId').selectpicker('refresh'); $('#MaterialId').selectpicker('val', _self.MaterialId); }).catch(function (res) { }); }, qtyL: function (val) { var _self = this; for (var item in _self.StorageRackList) { var a = _self.StorageRackList[item]; if (a.MaterialId == val) { _self.Qty = a.Qty; _self.MaterialNo = a.MaterialNo; _self.MaterialName = a.MaterialName; return false; } } }, addD: function () { var _self = this; if (_self.MaterialId.length<=0) { layer.msg("请选择物料", { icon: 2 }); return false; } if (!yui.signlessInteger(_self.ActQty)) { layer.msg("实际数量为正整数", { icon: 2 }); return false; } if (_self.ActQty > _self.Qty) { layer.msg("实际数量不能大于库存数量", { icon: 2 }); return false; } _self.list = $("#bootstraptable").bootstrapTable('getData'); for (var item in _self.list) { var a = _self.list[item]; if (a.MaterialNo == _self.MaterialNo) { layer.msg("不允许重复添加", { icon: 2 }); return false; } } var data = { "MaterialId": _self.MaterialId, "MaterialNo": _self.MaterialNo, "MaterialName": _self.MaterialName, "Qty": _self.Qty, "ActQty": _self.ActQty, "Remark": _self.Remark, "Status": 1, "InventorymoveId": _self.InventorymoveId, } $("#bootstraptable").bootstrapTable("prepend",data); //$("#bootstraptable").bootstrapTable("refsrefresh"); }, addL: function () { var _self = this; _self.list = $("#bootstraptable").bootstrapTable('getData'); if (_self.list.length <= 0) { layer.msg("请添加明细", { icon: 2 }); return false; } var index = layer.load(1, { shade: [0.1, '#fff'] //0.1透明度的白色背景 }); _self.list = $("#bootstraptable").bootstrapTable('getData'); var data = { id: _self.InventorymoveId, //存在修改 list: _self.list, }; yui.$axiospostform('/InventoryMove/AddOrUpdateD', data) .then(function (response) { if (response.data.Item1 === 101) { layer.tips(response.data.Item2, '.layui-layer-setwin', { tips: [1, '#3595CC'], time: 3000 }); layer.close(index); return false; } if (response.data.Item1) { layer.msg(response.data.Item2, { icon: 1, time: 1000 }); setTimeout(function () { yui.layer_close3(); }, 500); } else { layer.msg(response.data.Item2 || errorMsg, { icon: 5 }); } layer.close(index); }) .catch(function (error) { layer.close(index); }); } } }); </script> }
the_stack
 @{ ViewBag.Title = "MemberEdit"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } @Scripts.Render("~/Scripts/editViewCommon.js") <script> var _id = getQueryString("id"); var _mode = "create";//modify var _validator; var _data = null; $(document).ready(function () { $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { save(); } }); _validator = $("#form").validate({ onfocusout: false, onkeyup: false, showErrors: showValidationErrors, rules: { "txt_name": "required", "txt_phone_num": { required: true, number: true, cellphone: true }, "txt_wechat_no": "required", }, messages: { "txt_name": "请输入姓名;", "txt_phone_num": { required: "请输入手机号;", number: "请输入正确的手机号;" }, "txt_wechat_no": "请输入微信号;", } }); load(); }); function load() { if (_id == undefined || _id == "") { return; } _mode = "modify"; $("#btnRemove").show(); $("#btnResetPassword").show(); var url = "/Api/Member/GetMember/" + _id; __requestLoadDataApi(url,function(data){ _data = data.Data; __setDto("form", _data); if (_data.superior_agent_phone_num != null && _data.superior_agent_phone_num != "") { $("#divMemberContainer").html(_data.superior_agent_name + "(" + _data.superior_agent_phone_num + ")"); } if (_data.status == 1) { $("#btnChangeStatus2").show(); $("#btnChangeStatus3").show(); } }); } function save() { if (_validator.form() == false) { return; } var url = "/Api/Member/CreateMember"; if (_mode == "modify") { url = "/Api/Member/UpdateMember"; } if (_data == undefined || _data == null) { _data = new Object(); } __getDto("form", _data); //_data.reg_time = null; //_data.update_time = null; __requestSaveDataApi(url, _data, _mode); } function removeData() { __requestRemoveDataApi("/Api/Member/RemoveMember/" + _id); } function resetPassword() { __requestApi({ msg: "是否将会员的密码重置为手机号?", apiUrl: "/Api/Member/ResetPassword/" + _id, callback: function (data) { layerAlert("重置成功。"); } }); } function changeStatus(status) { var args = new Object(); args.MemberId = _id; args.Status = status; __requestApi({ msg: "是否确认更新会员状态?", data: args, apiUrl: "/Api/Member/ChangeStatus", callback: function (data) { //console.log(JSON.stringify(data)); var index = parent.layer.getFrameIndex(window.name); parent.__loadDataOnPageAndCloseLayer(index); } }); } //选择会员 function selectMember(target) { ///_chooseUserForRoleLayerIndex = layer.open({ type: 2, area: ['600px', '80%'], //宽高 closeBtn: false, title: "", shift: _layerShift, content: '/Member/MemberSelector?target=' + target }); } function selectMemberCallback(layerIndex, target, id, name, phone_num) { layer.close(layerIndex); $("#txt_superior_agent_id").val(id); $("#divMemberContainer").html(name + "(" + phone_num + ")"); } function clearSelectedMember(target) { $("#txt_superior_agent_id").val(""); $("#divMemberContainer").html(""); } </script> <div class="PopupWindowTitle"> <span id="spanTitle">会员</span> </div> <div style="position:absolute; overflow:auto ;margin-top:5px;left:30px; right:30px; bottom:60px; top:50px; "> <form id="form" onsubmit="return false"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="110" height="36">姓名:</td> <td><input id="txt_name" name="txt_name" type="text" class="input_16" style="width:96%; " keyenter dtoproperty="name" maxlength="50"/></td> </tr> <tr> <td width="110" height="36">手机:</td> <td><input id="txt_phone_num" name="txt_phone_num" type="text" class="input_16" style="width:96%; " keyenter dtoproperty="phone_num" maxlength="20" /></td> </tr> <tr> <td width="110" height="36">微信:</td> <td><input id="txt_wechat_no" name="txt_wechat_no" type="text" class="input_16" style="width:96%; " keyenter dtoproperty="wechat_no" maxlength="50" /></td> </tr> <tr> <td width="110" height="36">会员类型:</td> <td> <select style="width:96%;" class="input_16" keyenter dtoproperty="type"> <option value="1" selected>一级代理</option> <option value="2">二级代理</option> <option value="3">会员</option> </select> </td> </tr> <tr> <td width="110" height="36">累计消费:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="total_amount" /> </td> </tr> <tr> <td width="110" height="36">上级代理:</td> <td> <div class="divBorder_gray" style="margin-bottom:5px;width:96%; box-sizing:border-box;float:left "> <div style="padding:3px 5px 3px 5px"> <div id="divMemberContainer" style="float:left"> </div> <div style="float:right"> <a href="javascript:void(0)" onclick="selectMember()">选择</a> <a href="javascript:void(0)" onclick="clearSelectedMember()">清除</a> </div> <div style="clear:both"></div> </div> <input id="txt_superior_agent_id" name="txt_superior_agent_id" type="hidden" dtoproperty="superior_agent_id" /> </div> </td> </tr> <tr> <td width="110" height="36">持卡人姓名:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="card_holder" maxlength="50" /> </td> </tr> <tr> <td width="110" height="36">银行卡号:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="card_no" maxlength="50" /> </td> </tr> <tr> <td width="110" height="36">一级开户行:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="deposit_bank" maxlength="50" /> </td> </tr> <tr> <td width="110" height="36">二级开户行:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="deposit_branch_bank" maxlength="50" /> </td> </tr> <tr> <td width="110" height="36">积分:</td> <td> <input type="text" class="input_16" style="width:96%; " keyenter dtoproperty="total_point" /> </td> </tr> <tr> <td width="110" height="36">会员隐私状态:</td> <td> <select style="width:96%;" class="input_16" keyenter dtoproperty="secret_status"> <option value="0" selected>关闭</option> <option value="1">开启</option> </select> </td> </tr> <tr> <td width="110" height="36">会员头像:</td> <td></td> </tr> <tr> <td width="110" height="36">会员状态:</td> <td> <select style="width:96%;" class="input_readonly" keyenter dtoproperty="status" disabled> <option value="1" selected>新建待审核</option> <option value="2">审核通过</option> <option value="3">审核不通过</option> <option value="5">注销</option> </select> </td> </tr> @*<tr> <td width="110" height="36">注册时间:</td> <td> <input type="text" class="input_readonly" style="width:96%; " keyenter dtoproperty="reg_time" readonly/> </td> </tr> <tr> <td width="110" height="36">更新时间:</td> <td> <input type="text" class="input_readonly" style="width:96%; " keyenter dtoproperty="update_time" readonly/> </td> </tr>*@ </table> </form> </div> <div style="background-color:#ccc; position:absolute; bottom:55px; left:20px;right:20px; height:1px;"> </div> <div style="position:absolute; bottom:15px; left:20px;right:20px;"> <div style="float:left;"> <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" style="display:none" onclick="removeData()" /> </div> <div style="float:right"> <input id="btnChangeStatus2" type="button" class="btn_green" value="审核通过" onclick="changeStatus(2)" style="display:none" /> <input id="btnChangeStatus3" type="button" class="btn_green" value="审核不通过" onclick="changeStatus(3)" style="display:none"/> <input name="btnResetPassword" type="button" class="btn_aque" id="btnResetPassword" value="重置密码" style="display:none" onclick="resetPassword()" /> <input name="btnSave" type="button" class="btn_aque" id="btnSave" value="保 存" onclick="save()" /> <input name="btnCancel" type="button" class="btn_aque" id="btnCancel" value="取 消" onclick="__closePopupFrameLayer()" /> </div> <div style="clear:both"> </div> </div>
the_stack
@using OCM.API.Common.Model; @model OCM.API.Common.Model.ChargePoint @using Microsoft.AspNetCore.Http; @using Microsoft.AspNetCore.Html; @{ ViewBag.Title = ViewBag.FullTitle; int? userId = Context.Session.GetInt32("UserID"); if (ViewBag.EnableEditView == false) { ViewBag.Title = "Add Charging Location"; <h2 data-localize="ocm.general.addLocation">Add a Charging Location</h2> <script>var enableEditMode = false; var poiId = 0;</script> } else { ViewBag.Title = "Edit Charging Location"; <script>var enableEditMode = true; var poiId = @(Model.ID)</script> } if (ViewBag.IsReadOnlyMode != null && ViewBag.IsReadOnlyMode == true) { <p class="alert alert-danger"> This service is currently Read-Only and submission or edits are not currently being accepted. </p> } } @using (Html.BeginForm("Edit", "POI", FormMethod.Post, new { @class = "form", id = "editor" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @Html.HiddenFor(model => model.ID) @Html.HiddenFor(model => model.UUID) if (ViewBag.EnablePreviewMode == true) { //setup flags to signal to details view that we're doing a preview ViewBag.EnableSimpleView = true; <!--begin preview dialog--> <div class="modal fade" id="modalpreview" tabindex="-1" role="dialog" aria-labelledby="modalpreviewtitle" aria-hidden="true"> <div class="modal-dialog modal-lg " role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modaltitle">Preview Submission</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div> <input type="button" class="btn btn-primary" value="Edit" id="preview-edit" /> <button type="submit" class="btn btn-success">Submit changes</button> </div> @Html.Partial("_TermsLink") @Html.Partial("Details", new OCM.MVC.Models.POIViewModel() { POI = Model }) </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!--end preview dialog--> <h3 id="editheading">Edit Submission:</h3> <div class="checkbox" style="display:none;"> <label> <input type="checkbox" value="" id="editExtendedMode"> Use Advanced Editor </label> </div> <p class="text-info">Select a section below to make changes:</p> } else { <text> <div class="text-info"> @if (userId==null) { <div class="text text-warning">You are not signed in. You can proceed with your submission but certain features may be unavailable.</div> @Html.ActionLink("Sign In", "SignIn", "Profile", new { redirectUrl = Url.Action("Edit", "POI", new { id = Model.ID }) }, new { @class = "btn btn-sm btn-success" }) } </div> </text> } @Html.Partial("_POIListingStatus", Model) @Html.ValidationSummary() <div class="accordion" id="wizardsteps"> @if (ViewBag.HideAdvancedInfo != null && ViewBag.HideAdvancedInfo == false) { <div class="card bg-secondary"> <div class="card-header"> <a data-toggle="collapse" data-parent="#wizardsteps" href="#step-approver"> <i class="fa fa-edit"></i> Approver Options </a> </div> <div id="step-approver" class="collapse show"> <div class="card-body"> <p class="text-info">To make a new listing public it's Submission Status must be set to <strong>Submission Published</strong>.</p> <div class="form-group col-sm-4"> <div class="editor-label" data-localize="ocm.details.submissionStatus"> @Html.LabelFor(model => model.SubmissionStatus) </div> <div class="editor-field col-sm-8"> @Html.DropDownListFor(model => model.SubmissionStatus.ID, (SelectList)ViewBag.ReferenceData.SubmissionTypeList) @Html.ValidationMessageFor(model => model.SubmissionStatus) </div> </div> <input type="submit" value="Save Changes" class="btn btn-success" /> </div> </div> </div> } <!--step 1--> <div class="card"> <div class="card-header"> <h4> <a data-toggle="collapse" data-parent="#wizardsteps" href="#step1"> <i class="fa fa-map-marker"></i> Step 1 - <span data-localize="ocm.details.location.sectionTitle">Location Details</span> </a> </h4> </div> <div id="step1" class="collapse collapse show"> <div class="card-body"> <p> <strong>Thanks for taking the time to contribute. Please provide as much detail as you can about this charging location. Please <strong>do not</strong> submit private residences (such as your home). Listings without basic charging equipment information will be rejected without notice, so please provide as much information as you can.</strong> </p> <!--begin location editor--> @Html.EditorFor(model => model.AddressInfo) <!--end location editor--> </div> </div> </div> <!--step 2--> <div class="card"> <div class="card-header"> <h4 class="card-title"> <a data-toggle="collapse" data-parent="#wizardsteps" href="#step2"> <i class="fa fa-info-circle"></i> Step 2 - Basic Charging Details </a> </h4> </div> <div id="step2" class="collapse"> <div class="card-body"> <!--begin basic detail editor--> @Html.Partial("_EditPOIBasicDetails", Model) <!--end basic details editor--> </div> </div> </div> <!--step 3--> <div class="card"> <div class="card-header"> <h4 class="card-title"> <a data-toggle="collapse" data-parent="#wizardsteps" href="#step3"> <i class="fa fa-flash"></i> Step 3 - <span data-localize="ocm.details.equipment.sectionTitle">Equipment Details</span> </a> </h4> </div> <div id="step3" class="collapse"> <div class="card-body"> <!--begin basic detail editor--> <div id="tab-equipment"> <p>This section details the exact type and power level of connections available at this site. Please provide as much info as possible. Listings with no equipment information will be rejected.</p> @if (Model.Connections != null) { for (int i = 0; i < Model.Connections.Count; i++) { var connectionItem = Model.Connections[i]; <h4> Equipment Item @(i + 1) : @if (connectionItem.Reference == null) { if (connectionItem.ID > 0) { @:OCM-CN-@connectionItem.ID } } <input type="button" id="remove-equipment-@(i + "-" + connectionItem.ID)" value="Remove" class="btn btn-danger" /> </h4> @Html.EditorFor(m => Model.Connections[i]) } } <input type="button" id="additional-equipment" value="Add Additional Equipment" class="btn btn-info" /> <input type="hidden" id="editoption" name="editoption" /> </div> <!--end basic details editor--> </div> </div> </div> @if (ViewBag.HideAdvancedInfo != null && ViewBag.HideAdvancedInfo == false) { <div class="card"> <div class="card-header"> <h4 class="card-title"> <a data-toggle="collapse" data-parent="#wizardsteps" href="#step-approver-adv"> <i class="fa fa-wrench"></i> Advanced Options </a> </h4> </div> <div id="step-approver-adv" class="collapse"> <div class="card-body"> <p class="text-info">This section contains options which are not usually changed or are deprecated.</p> @Html.HiddenFor(model => model.DataProviderID) <div class="form-group"> <div class="editor-label" data-localize="ocm.details.dataProvider.providersReference"> @Html.LabelFor(model => model.DataProvidersReference) </div> <div class="editor-field"> @Html.EditorFor(model => model.DataProvidersReference) @Html.ValidationMessageFor(model => model.DataProvidersReference) </div> </div> <div class="form-group"> <div class="editor-label" data-localize="ocm.details.operator.operatorsReference"> @Html.LabelFor(model => model.OperatorsReference) </div> <div class="editor-field"> @Html.EditorFor(model => model.OperatorsReference) @Html.ValidationMessageFor(model => model.OperatorsReference) </div> </div> <div class="form-group"> <div class="editor-label" data-localize="ocm.details.datePlanned"> @Html.LabelFor(model => model.DatePlanned) </div> <div class="editor-field"> @Html.EditorFor(model => model.DatePlanned) @Html.ValidationMessageFor(model => model.DatePlanned) </div> </div> <div class="form-group"> <div class="editor-label" data-localize="ocm.details.dateLastConfirmed"> @Html.LabelFor(model => model.DateLastConfirmed) </div> <div class="editor-field"> @Html.EditorFor(model => model.DateLastConfirmed) @Html.ValidationMessageFor(model => model.DateLastConfirmed) </div> </div> @Html.HiddenFor(model => model.DataQualityLevel) </div> </div> </div> } else { @Html.HiddenFor(model => model.DataProvidersReference) @Html.HiddenFor(model => model.DataQualityLevel) @Html.HiddenFor(model => model.DatePlanned) @Html.HiddenFor(model => model.DateLastConfirmed) @Html.HiddenFor(model => model.OperatorsReference) @Html.HiddenFor(model => model.SubmissionStatusTypeID) @Html.HiddenFor(model => model.DataProviderID) } </div> <div class="form-actions"> @Html.Partial("_TermsLink") @if (Model.ID > 0) { <a href="@Url.Action("Details", "POI", new { id = Model.ID })" class="btn btn-info">Cancel</a> } else { <a href="@Url.Action("Index", "POI")" class="btn btn-info">Cancel</a> } <input type="button" value="Preview" class="btn btn-success" id="preview" /> @if (ViewBag.EnablePreviewMode == true) { <input type="submit" value="Submit" class="btn btn-primary" /> } </div> } @* @section Scripts { @Scripts.Render("~/bundles/jqueryval") } *@ <script src="@Url.Content("~/js/OCM/SharedLibs/OCM_Base.js")"></script> <script src="@Url.Content("~/js/OCM/SharedLibs/OCM_Base.js")"></script> <script src="@Url.Content("~/js/OCM/SharedLibs/OCM_Data.js")"></script> <script src="@Url.Content("~/js/OCM/SharedLibs/OCM_Geolocation.js")"></script> <script> $(document).ready(function () { $("#editExtendedMode").change(function () { refreshEditorMode(); }); //FIXME: use bootstrap styles for form controls $(".text-box, select, textarea").addClass("form-control"); refreshEditorMode(); $("#additional-equipment").click(function () { //submit form and request additional equipment $("#editoption").val("addconnection"); $("#editor").submit(); }); $('[id^="remove-equipment"]').click( function () { //submit form and request equipment removal $("#editoption").val(this.id); $("#editor").submit(); } ); $("#preview").click(function () { //submit form and request additional equipment $("#editoption").val("preview"); $("#editor").submit(); }); $("#preview-edit").click(function () { //hide preview and expand edit $("#modalpreview").modal("hide"); $('#step1').collapse('show'); }); if (enableEditMode == true) { //show preview (if enabled) $('#modalpreview').modal('show'); //collapse all edit sections //$('#step1').collapse('hide'); //$('#step2').collapse('hide'); //$('#step3').collapse('hide'); locationEditor.refreshMap(); //refresh map view when collapsed region is opened $('#step1').on('shown.bs.collapse', function (e) { locationEditor.refreshMap(); }) } }); function refreshEditorMode() { var extendedMode = false; if (document.getElementById('editExtendedMode') != null) { extendedMode = document.getElementById('editExtendedMode').checked; } if (extendedMode === true) { $("[data-editormode='extended']").show(); } else { $("[data-editormode='extended']").hide(); $("[data-editormode='advanced']").hide(); } //TODO: advanced mode } </script>
the_stack
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width" /> <title>升讯威微信营销系统</title> @Scripts.Render("~/Scripts/UserAgent.js") <script type="text/javascript"> var _userAgent = new userAgentObj(navigator.userAgent); if (_userAgent.device != __device_PC) { window.location.href = "/M/Home/Login"; } </script> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/common") @Scripts.Render("~/Scripts/jquery-1.10.2.min.js") @Scripts.Render("~/Scripts/validate/jquery.validate.min.js") @Scripts.Render("~/Scripts/layer/layer.js") @Scripts.Render("~/bundles/md5") <style type="text/css"> body { font-size: 15px; } input.watermark { color: #999; } .input_login { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -o-box-sizing: border-box; font-size: 15px; padding: 8px; width: 100%; border: 1px solid #D7D7D7; } .btn_login { font-size: 16px; color: #FFF; background-color: #36B5F8; /*padding-right: 20px; padding-left: 20px;*/ border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; padding-top: 8px; padding-bottom: 8px; width: 100%; cursor:pointer; } .btn_login:hover, .btn_login:focus { text-decoration: none; background-color: #09A4F7; } .btn_login:active, .btn_login.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn_login:disabled { text-decoration: none; background-color: #CCCCCC; } .btn_register { color: #F16777; font-size: 16px; background-color: white; border: 1px solid #F16777; padding-top: 8px; padding-bottom: 8px; width: 100%; cursor:pointer; } .btn_register:hover, .btn_register:focus { color: white; text-decoration: none; background-color: #F16777; } .btn_register:active, .btn_register.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn_register:disabled { text-decoration: none; background-color: #CCCCCC; } #divLogin { position: absolute; height: 40px; top: 45%; margin-top: -210px; left: 150px; } #divNewsBackground { background-color: #FFF; height: 285px; width: 320px; position: absolute; top: 45%; margin-top: -150px; left: 770px; /*filter: alpha(opacity=70); -moz-opacity: 0.7; -khtml-opacity: 0.7; opacity: 0.7;*/ z-index: 12; padding: 20px; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -o-box-sizing: border-box; } #divLoginAreaBackground { background-color: #FFF; height: 285px; width: 600px; position: absolute; top: 45%; margin-top: -150px; left: 150px; /*filter: alpha(opacity=20); -moz-opacity: 0.2; -khtml-opacity: 0.2; opacity: 0.2;*/ z-index: 12; } #divLoginArea { /*color: white;*/ height: 285px; width: 600px; position: absolute; top: 45%; margin-top: -150px; left: 150px; z-index: 13; } #divLoginContent { bottom: 0px; top: 0px; left: 0px; right: 0px; position: absolute; /*background-image: url(Images/139-15030G00I0.jpg);*/ background-image: url(/Content/Images/login_bg2.jpg); /*background-repeat: no-repeat;*/ background-position: left center; background-color: #808080; } #divLoginAreaMask { height: 285px; width: 600px; position: absolute; top: 45%; margin-top: -150px; left: 150px; z-index: 14; background-color: #fff; filter: alpha(opacity=20); -moz-opacity: 0.2; -khtml-opacity: 0.2; opacity: 0.2; } #divLoginAreaMaskContent { height: 285px; width: 600px; position: absolute; top: 45%; margin-top: -140px; left: 150px; right: 150px; z-index: 15; } /*#divLoginAreaMaskContent { background-color: #69F; height: 24px; line-height: 24px; width: 330px; position: absolute; top: 476px; left: 100px; z-index: 15; font-size: 14px; color: #FFF; }*/ #divLoginFooter { color: #D7D7D7; font-size: 13px; position: absolute; height: 100px; left: 150px; top: 45%; margin-top: 140px; } </style> <script type="text/javascript"> $(document).ready(function () { watermark(); var account = getCookie("account"); if (account != undefined && account != "") { $("#txtAccount").val(account); $("#chkRememberAccount").attr("checked", "checked"); } $("[keyenter]").keypress(function (e) { if (e.keyCode == 13) { login(); } }); }); function watermark() { var accountWatermark = '账户'; $('#txtAccount').val(accountWatermark).addClass('watermark'); $('#txtAccount').blur(function () { if ($(this).val().length == 0) { $(this).val(accountWatermark).addClass('watermark'); } }); $('#txtAccount').focus(function () { if ($(this).val() == accountWatermark) { $(this).val('').removeClass('watermark'); } }); var passwordWatermark = '密码'; $('#txtPassword').val(passwordWatermark).addClass('watermark'); $('#txtPassword').blur(function () { if ($(this).val().length == 0) { $(this).val(passwordWatermark).addClass('watermark').attr("type", "text"); } }); $('#txtPassword').focus(function () { if ($(this).val() == passwordWatermark) { $(this).val('').removeClass('watermark').attr("type", "password"); } }); } function login() { if ($("#form").validate({ rules: { "txtAccount": "required", "txtPassword": "required" }, messages: { "txtAccount": "!", "txtPassword": "!" } }).form() == false) return; var args = new Object(); args.Account = $("#txtAccount").val(); args.Password = hex_md5($("#txtPassword").val()).toUpperCase(); showMask(); $.ajax({ url: "/Api/UserContext/Login", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { if (data.Success) { if ($("#chkRememberAccount").is(":checked")) { setCookie("account", args.Account); } else { removeCookie("account"); } window.location.href = "/Portal/Dashboard"; } else { hideMask(); layerAlert(data.Message, function () { $("#txtPassword").focus(); }); } }, error: function (xmlHttpRequest) { hideMask(); alert("Error: " + xmlHttpRequest.status); } }); } function showMask() { $("#divLoginAreaMask").show(); $("#divLoginAreaMaskContent").show(); } function hideMask() { $("#divLoginAreaMask").hide(); $("#divLoginAreaMaskContent").hide(); } </script> </head> <body> <div id="divLoginContent"> <div id="divLoginAreaBackground"> </div> <div id="divLoginArea"> <form id="form"> <table width="100%" height="285" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td valign="top"> <div style="margin-left:30px;margin-top:30px; margin-right:30px;"> <div style="color:#36B5F8;font-size:17px;">登录</div> <div style="margin-top:20px;"> <input name="txtAccount" type="text" class="input_login" id="txtAccount" keyenter=keyenter /> </div> <div style="margin-top:10px;"> <input name="txtPassword" type="text" class="input_login" id="txtPassword" keyenter=keyenter /> </div> <div style="margin-top:10px;"> <div style="float:left"> <input name="" id="chkRememberAccount" type="checkbox" value="" /> <label for="chkRememberAccount">记住帐户</label> </div> <div style="float:left; margin-left:30px;"> <a href="/Home/ResetPassword" style="color:black">找回密码</a> </div> <div style="clear:both"></div> </div> <div style="margin-top:20px;"> <input name="btnLogin" type="button" class="btn_login" id="btnLogin" value="登 录" onclick="login()" /> </div> </div> </td> <td valign="top" width="250" bgcolor="#F8F8F8"> <div style="margin-left:30px;margin-top:30px; margin-right:30px;"> <div> <input name="btnRegister" type="button" class="btn_register" id="btnRegister" value="免费注册" onclick="goUrl('@Url.Action("Register")')" /> </div> <div style="margin-top:15px;"> <span> <a href="http://docs.shengxunwei.com/Home/Browser/wxcm" target="_blank" style="color:#F16777">操作手册 ></a> </span> <span style="margin-left:20px;"> <a href="http://wx.shengxunwei.com" target="_blank" style="color:#F16777">官方网站 ></a> </span> </div> <div style="margin-top:15px;font-size:12px;"> QQ群:591928344 </div> <div style="margin-top:10px;"> <img src="/Content/Images/QQGroup2.jpg" style="width:100px;" /> </div> </div> </td> </tr> </table> </form> </div> <div id="divLoginAreaMask" style="display:none"> </div> <div id="divLoginAreaMaskContent" style="display:none"> <div style="bottom:0px; left:0px;right:0px; position:absolute; background-color:#efefef; color:black; padding-left:15px; padding-top:3px;padding-bottom:3px;font-size:14px;"> <span>正在登录,请稍候..</span> </div> </div> <div id="divNewsBackground"> <div style="font-weight:bold"> 最新动态: </div> <div style="font-size:14px;"> <ul> <li><a href="http://wx.shengxunwei.com/Home/Question/7136f0cc-7149-4d0d-a977-915c042b771b" target="_blank" style="color:black">订阅号与服务号有什么区别?</a></li> </ul> </div> </div> </div> <div id="divLogin"> <img src="/Content/Images/login_logo2.png" alt="升讯威微信营销系统" /> </div> <div id="divLoginFooter"> <!--<div style="background-color:#69E5BB; height:2px;"> </div>--> <table height="100%" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left"> © Copyright 2016 All Rights Reserved 滁州市升讯威软件技术有限公司<br /> 电话:0550-3926191 / 18114009195 QQ:279060597<br /> <a href="http://wx.shengxunwei.com" target="_blank" style="color:#D7D7D7;text-decoration:underline">http://wx.shengxunwei.com</a> 皖ICP备14020687号 </td> </tr> </table> </div> </body> </html>
the_stack
@model NB.Apps.EFMigrationsManager.Models.EFMigrationDetails @{ ViewBag.Title = Model.IsRollback ? "Restore Migration(s)" : "Update Database"; var statusMessage = TempData["StatusMessage"] as string; var disclaimerMessage = Model.IsRollback ? "Disclaimer: Restoring to previous Target Migration may break the application." : "Disclaimer: The latest Target Migration must be applied to continue using this application."; var noAvailableTargetMigrationsMessage = Model.IsRollback ? "No migration(s) available to restore." : "Latest migration was applied."; } <!-- MAIN CONTENT --> <div id="content"> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-list-alt fa-fw "></i> 系统管理 <span> > 更新数据库 </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> </div> </div> <!-- widget grid --> <section id="widget-grid" class=""> <div class="row"> <div class="col-md-12 col-sm-12"> @if (!string.IsNullOrEmpty(statusMessage)) { <div class="alert alert-success alert-dismissable"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> @statusMessage </div> } else { if (!Model.HasTargetMigrationExists) { <div class="alert alert-success alert-dismissable"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> @noAvailableTargetMigrationsMessage </div> } else { <div class="alert alert-warning alert-dismissable"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> @disclaimerMessage </div> } } <div class="container-fluid well"> @using (Html.BeginForm("Publish", "EFMigrationsManager", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "efmigrationsmanager", role = "form" })) { @Html.AntiForgeryToken() <div class="form-horizontal formContainer"> @Html.HiddenFor(model => model.IsRollback) @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.CurrentMigrationDisplayValue, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.CurrentMigrationDisplayValue, new { @class = "form-control", disabled = "disabled" }) </div> </div> <div class="form-group form-inline"> @Html.LabelFor(model => model.TargetMigration, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(model => model.TargetMigration, Model.Migrations, new { @class = "form-control selectTargetMigration" }) @if (Model.IsRollback) { @Html.ActionLink("Show Pending Migration(s)", "Publish", null, new { @class = "btn btn-raised btn-default btn-primary" }) } else { @Html.ActionLink("Show Previous Migration(s)", "Publish", new { isRollback = true }, new { @class = "btn btn-raised btn-default btn-primary" }) } </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button class="btn btn-raised btn-primary btn-default btnUpdateDatabase @(!Model.HasTargetMigrationExists ? "disabled" : "")" title="Update Database" type="button"> Apply Migration(s) <div class="ripple-container"></div> </button> <div class="loader"></div> </div> </div> </div> <div id="confirmationDailogContainer" style="display:none"> <div class="row message dialogHeader"> @if (Model.IsRollback) { <div class="dataLossWarning">Data loss can occur when restoring previous migration(s)</div> } <h4>The following migration(s) will be @(Model.IsRollback ? "restored" : "applied"):</h4> </div> <div class="dialogBody"> <ul class="migrationsToApply"></ul> </div> <div class="dialogFooter"> <div class="row message"> Are you sure you want to continue? </div> <div class="row message"> <button class="btn btn-raised btn-primary btn-default btnYes" type="button"> <span class="glyphicon glyphicon-ok"></span> Yes </button> <button class="btn btn-raised btn-primary btn-default btnNo" type="button"> <span class="glyphicon glyphicon-remove"></span> No </button> </div> </div> </div> } </div> </div> </div> </section> </div> @section Scripts { <script type="text/javascript"> function doConfirm(yesFn, noFn) { var confirmationDailogContainerElement = $("#confirmationDailogContainer"); var formContainer = $(".formContainer"); var migrationsToApplyElement = $('.migrationsToApply', confirmationDailogContainerElement); migrationsToApplyElement.empty(); $.each($( "#TargetMigration option"), function () { migrationsToApplyElement.append('<li class="message">' + this.text.trim() + '</li>'); if (this.selected) { return false; } }); if ('@Model.IsRollback' == 'True') { migrationsToApplyElement.prepend('<li class="message">' + '@Model.CurrentMigrationDisplayValue' + '</li>'); $('li:last-child', migrationsToApplyElement).remove(); } var modalDialogClassName = 'dialogVisible' confirmationDailogContainerElement.find(".btnYes,.btnNo").unbind().click(function () { formContainer.removeClass(modalDialogClassName); confirmationDailogContainerElement.hide(); }); confirmationDailogContainerElement.find(".btnYes").click(yesFn); confirmationDailogContainerElement.find(".btnNo").click(noFn); formContainer.addClass(modalDialogClassName); confirmationDailogContainerElement.show(); return false; } function bindUpdateDatabaseClickEvent() { $(".btnUpdateDatabase").click(function () { if ('@Model.HasTargetMigrationExists' === 'True') { doConfirm(function yes() { $('.loader').show(); console.log(document.forms); $('#efmigrationsmanager').submit(); }, function no() { }); } }); } //$(document).ready(bindUpdateDatabaseClickEvent); // Use this line and comment below one. Jquery should be loaded by this time. setTimeout(function () { var removeAllMigrationsItem = document.querySelector('#TargetMigration option[value="0"]'); if (removeAllMigrationsItem){ removeAllMigrationsItem.style.backgroundColor = "#fcf8e3"; } bindUpdateDatabaseClickEvent(); }, 500); </script> } <style> .selectTargetMigration { min-width: 250px; } .dialogVisible { opacity: 0.4; pointer-events: none; } #confirmationDailogContainer .dialogBody { height: 100%; max-height: 150px; overflow-y: auto; } #confirmationDailogContainer { display: none; background-color: #eee; border-radius: 5px; border: 1px solid #aaa; padding: 6px 8px 8px; box-sizing: border-box; text-align: center; z-index: 999999999999; } .message { text-align: left; margin-bottom: 8px; margin-left: 8px; } .dataLossWarning { color: #b94a48; } #confirmationDailogContainer, .centerPosition { position: fixed; width: 450px; left: 40%; top: 40%; margin-left: -150px; margin-top: -150px; } .loader { margin-left: 150px; margin-top: -50px; position: fixed; display: none; border: 8px solid #f3f3f3; border-radius: 50%; border-top: 8px solid blue; border-bottom: 8px solid blue; width: 80px; height: 80px; -webkit-animation: spin 2s linear infinite; animation: spin 2s linear infinite; } @@-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style>
the_stack
@model WalkingTec.Mvvm.Core.BaseVM <style> a { color: #01aaed } </style> <p>BaseTemplateVM and BaseImportVM are the VMs responsible for importing in the framework. TemplateVM is used to define Excel templates.ImportVM uses the templates defined by TemplateVM for import operations</p> <wt:fieldset field-set-style="Simple" title="Build a baseimportvm"> <p>Since ImportVM needs to use the template defined in TemplateVM, there are two steps to establish ImportVM:</p> <p>1. Create a TemplateVM and define the fields to be imported</p> <p>2. Create an ImportVM and pass in the TemplateVM created in the first step as a generic variable</p> <p>Take the ‘school’ model as an example to demonstrate how to build an ImportVM to import school information. The definition of school model can refer to<a href="/#/QuickStart/FirstModule">the first module</a></p> <wt:code title="SchoolImportVM.cs"> public class SchoolTemplateVM : BaseTemplateVM { [Display(Name = "School code")] public ExcelPropety SchoolCode_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolCode); [Display(Name = "School name")] public ExcelPropety SchoolName_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolName); [Display(Name = "School type")] public ExcelPropety SchoolType_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolType); [Display(Name = "Remark")] public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.Remark); } public class SchoolImportVM : BaseImportVM&ltSchoolTemplateVM, School&gt { } </wt:code> <p>For simple import tasks, the above code is enough. Just inherit the base class and define the fields to be imported, the framework will complete the rest.</p> <wt:quote> ExcelPropetyis a class that defines the columns to be imported, provided by framework. </wt:quote> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="Using BaseImportVM"> <p>The steps of using BaseImportVM in Controller are also clear at a glance. Please see the following example:</p> <wt:code title="SchoolController.cs"> #region Import [ActionDescription("Import")] public ActionResult Import() { var vm = CreateVM&ltSchoolImportVM&gt(); return PartialView(vm); } [HttpPost] [ActionDescription("Import")] public ActionResult Import(SchoolImportVM vm, IFormCollection nouse) { if (vm.ErrorListVM.EntityList.Count &gt 0 || !vm.BatchSaveData()) { return PartialView(vm); } else { return FFResult() .RefreshGrid() .CloseDialog() .Alert(vm.EntityList.Count.ToString() + " records have been imported"); } } #endregion </wt:code> <wt:quote> <p>BatchSaveDatais a function defined in the ImportVM, which will perform the final operation of importing the database.</p> <p>You must use the CreateVM function to create the ViewModel, not just new. The CreateVM function will pass the Session, ModelState and other information of the current Controller to the VM, and perform some operations within the framework.</p> <p>FFResult is an auxiliary class provided by the framework, which is mainly used to facilitate developers to return to common JS, such as closing the current window, refreshing the grid, etc.</p> </wt:quote> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="Customized validation"> <p>ImportVMwill find its corresponding BaseCRUDVM according to the associated Model. If it can be found, it will call the Validate and SetDuplicatedCheck methods in BaseCRUDVM for logical verification and data repeatability verification.</p> <p>At the same time, the ImportVM itself can override the SetDuplicatedCheck method. Finally, the framework will merge the data repeatability verification in the ImportVM and BaseCRUDVM.</p> <p>Please refer to the corresponding chapter in BaseCRUDVM for the description of SetDuplicatedCheck.</p> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="Complex import templates"> <p>The framework will automatically generate Excel templates according to the bound field types, for example, it will automatically generate pull-down menus for enumeration columns.</p> <p>The framework also supports manual setting of complex templates. For example, when importing, you need to use the drop-down menu to select associated table data.</p> <p>Like the previous school example, if the school name has to be selected from the drop-down menu, we can make it happen by doing this:</p> <wt:code title="SchoolImportVM.cs"> public class SchoolTemplateVM : BaseTemplateVM { [Display(Name = "School code")] public ExcelPropety SchoolCode_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolCode); [Display(Name = "School name")] public ExcelPropety SchoolName_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolName); [Display(Name = "School type")] public ExcelPropety SchoolType_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolType); [Display(Name = "Remark")] public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.Remark); protected override void InitVM() { SchoolName_Excel.DataType = ColumnDataType.ComboBox; SchoolName_Excel.ListItems = new List&ltComboSelectListItem&gt { new ComboSelectListItem{ Text="aaa", Value="aaa"}, new ComboSelectListItem{ Text="bbb", Value="bbb"}, new ComboSelectListItem{ Text="ccc", Value="ccc"}, new ComboSelectListItem{ Text="ddd", Value="ddd"}, }; } } public class SchoolImportVM : BaseImportVM&ltSchoolTemplateVM, School&gt { } </wt:code> <p>As shown above, we can set the DataType of the SchoolName column to ComboBox and set its ListItems. The framework will automatically generate a drop-down menu in Excel when generating a template.</p> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="Customized import"> <p>Sometimes the default process provided by the framework does not fully meet the needs.</p> <p>For example, you need to process the data in Excel first, and then save it to the database.</p> <p>The following code demonstrates modifying the data in excel before importing, by overriding the BatchSaveDatamethod.</p> <wt:code title="SchoolImportVM.cs"> public class SchoolTemplateVM : BaseTemplateVM { [Display(Name = "School code")] public ExcelPropety SchoolCode_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolCode); [Display(Name = "School name")] public ExcelPropety SchoolName_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolName); [Display(Name = "School type")] public ExcelPropety SchoolType_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.SchoolType); [Display(Name = "Remark")] public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty&ltSchool&gt(x =&gt x.Remark); } public class SchoolImportVM : BaseImportVM&ltSchoolTemplateVM, School&gt { public override bool BatchSaveData() { //Get records from excel file and save it in to EntityList SetEntityList(); //Loop the EntityList, add a 'X' at the end foreach (var item in EntityList) { item.SchoolName += "X"; } //Call the BatchSaveData from base to save to the database. If there are special requirements, you can operate the DC by yourself to save the data return base.BatchSaveData(); } } </wt:code> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="primary and secondary tables import"> <p>The framework supports simultaneous import of primary and secondary tables.</p> <p>The following code demonstrates the import of the ‘school’ and the ‘majors’ under the school at the same time:</p> <wt:code title="SchoolImportVM.cs"> public class SchoolTemplateVM : BaseTemplateVM { [Display(Name = "School code")] public ExcelPropety SchoolCode_Excel = ExcelPropety.CreateProperty&ltSchool&gt( x =&gt x.SchoolCode); [Display(Name = "School name")] public ExcelPropety SchoolName_Excel = ExcelPropety.CreateProperty&ltSchool&gt( x =&gt x.SchoolName); [Display(Name = "School type")] public ExcelPropety SchoolType_Excel = ExcelPropety.CreateProperty&ltSchool&gt( x =&gt x.SchoolType); [Display(Name = "Remark")] public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty&ltSchool&gt( x =&gt x.Remark); [Display(Name = "Major code")] public ExcelPropety MajorCode_Excel = ExcelPropety.CreateProperty<School>( x =&gt x.Majors[0].MajorCode); [Display(Name = "Major name")] public ExcelPropety MajorName_Excel = ExcelPropety.CreateProperty<School>( x =&gt x.Majors[0].MajorName); [Display(Name = "Major type")] public ExcelPropety MajorType_Excel = ExcelPropety.CreateProperty<School>( x =&gt x.Majors[0].MajorType); } public class SchoolImportVM : BaseImportVM&ltSchoolTemplateVM, School&gt { } </wt:code> <p>As shown above, when we define a field, we can use x.Majors[0].MajorCode to set secondary table field</p> <p>When importing primary and secondary tables import, fill in the template in the form shown below:</p><br /> <img src="~/imgs/Importen.png" /><br /><br /> </wt:fieldset> <wt:fieldset field-set-style="Simple" title="Main functions"> </wt:fieldset> <table lay-filter="parse-table-demo"> <thead> <tr> <th lay-data="{field:'username', width:200}">Function</th> <th lay-data="{field:'joinTime', width:400}">Description</th> </tr> </thead> <tbody> <tr> <td>GenerateTemplate()</td> <td>Template generation</td> </tr> <tr> <td>SetEntityList</td> <td>Save the template data to the local class.If the default logic does not support the requirements, you can override this function in the subclass.</td> </tr> <tr> <td>BatchSaveData</td> <td>Perform the final database write operation. If the default logic does not support the requirements, you can override this function in the subclass</td> </tr> </tbody> </table> <script> layui.use('code',function(){layui.code({ about: false })}) </script> <script> layui.table.init('parse-table-demo', { limit: 100, page: false }); </script> <script> $("#@Model.ViewDivId").parent().css("height", "auto"); </script>
the_stack
<link rel="stylesheet" href="../../assets/vendor/fontawesome/css/all.min.css"> <div class="position-relative overflow-hidden bg-light z-index-2"> <div class="container space-top-3 position-relative"> <figure class="position-absolute z-index-n1" style="top: -35rem; left: 55rem; width: 55rem; height: 55rem;"> <svg preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 260 260"> <circle fill="#e7eaf3" opacity=".7" cx="130" cy="130" r="130" /> </svg> </figure> <figure class="position-absolute z-index-n1" style="top: 15rem; left: 75rem; width: 20rem; height: 20rem;"> <img class="img-fluid" src="../../assets/svg/components/circled-stripe.svg" alt="Image Description"> </figure> <figure class="position-absolute z-index-n1" style="bottom: 7rem; left: -20rem; width: 15rem; height: 15rem;"> <img class="img-fluid" src="../../assets/svg/components/dots-3.svg" alt="Image Description"> </figure> <!-- Title --> <div class="w-md-80 w-lg-60 text-center mx-md-auto"> <span class="d-block small font-weight-bold text-cap mb-2">Has your email been flagged as malicious?</span> <h2>Step 1: Filter Priming (Non-Malicious Mail)</h2> </div> <!-- Dropzone --> <div id="phishiousDropZone" class="js-dropzone dz-dropzone dz-dropzone-boxed gradient-overlay-half-primary-v4"> <div class="dz-message py-6"> <figure class="max-w-10rem mx-auto mb-3"> <img class="img-fluid" src="../../assets/svg/illustrations/drag-n-drop.svg" alt="Image Description"> </figure> <span class="d-block" style="font-size:large">Drag files here to upload</span> </div> </div> <div class="col-sm-auto p-2"> <button id="phishious-submit" type="submit" class="btn btn-block btn-primary px-5" onclick="return DisplayProgressMessage(this, 'Priming Filters...');" disabled>Prime Filters</button> </div> <!-- End Dropzone --> </div> <!-- Features Section --> <div> <div class="container-lg space-2"> <!-- Title --> <div class="w-md-80 w-lg-50 text-center mx-md-auto mb-5 mb-md-9"> <h2>What email spam and malware filters can phishious analyse?</h2> </div> <!-- End Title --> <div class="w-md-80 mx-md-auto"> <div class="row justify-content-lg-center align-items-md-center"> <div class="col-md-4 mb-7 mb-md-0"> <!-- Features --> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Cisco IronPort </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Sophos PureMessage </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Sophos ESA </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Trustwave SEG </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> McAfee AV </div> </div> <a class="media" href="#"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Exchange Online Protection </div> </a> <!-- End Features --> </div> <div class="col-md-4 mb-7 mb-md-0"> <!-- Features --> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Proofpoint SEG </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> FireEye MX </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> FireEye ETP Cloud </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Forcepoint SEG </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Forcepoint Cloud </div> </div> <a class="media" href="#"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Trend Micro HES </div> </a> <!-- End Features --> </div> <div class="col-md-4 mb-7 mb-md-0"> <!-- Features --> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Symantec MessageLabs </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Mimecast SEG </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Clearswift SEG </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Sophos AV </div> </div> <div class="media mb-4"> <span class="icon icon-xs icon-soft-primary icon-circle mr-3"> <i class="fas fa-check"></i> </span> <div class="media-body text-dark"> Barracuda Email Security </div> </div> <a class="media" href="#"> <span class="icon icon-xs icon-soft-light icon-circle mr-3"> @*<i class="fas fa-check"></i>*@ </span> <div class="media-body text-dark"> @*Barracuda Email Security*@ </div> </a> <!-- End Features --> </div> </div> </div> </div> <div id="step2Seperator" class="container"><hr /></div> </div> <!-- End Features Section --> @*<style> .col-lg-2{ padding-left:5px; padding-right:5px; } </style>*@ <div id="detonateContainer" class="container space-2" style="display:none"> <div class="w-md-80 w-lg-60 text-center mx-md-auto"> <h2>Step 2: Filter Detonation (Malicious Mail)</h2> </div> <!-- Dropzone --> <div id="detonateDropZone" class="js-dropzone dz-dropzone dz-dropzone-boxed gradient-overlay-half-primary-v4"> <div class="dz-message py-6"> <figure class="max-w-10rem mx-auto mb-3"> <img class="img-fluid" src="../../assets/svg/illustrations/drag-n-drop.svg" alt="Image Description"> </figure> <span class="d-block" style="font-size:large">Drag files here to upload</span> </div> </div> <div class="col-sm-auto p-2"> <button id="detonate-submit" type="submit" class="btn btn-block btn-primary px-5" onclick="return DisplayProgressMessage(this, 'Detonating Filters...');">Detonate Filters</button> </div> <!-- End Dropzone --> </div> <div id="analysisDiv" class="container space" style="display:none"> <!-- Card --> <div class="card"> <!-- Header --> <div class="card-header bg-light"> <h2 class="card-header-title" style="margin:auto">Step 3. Phishious Result Analysis</h2> </div> <!-- End Header --> <!-- Table --> <div class="table-responsive"> <table class="table table-borderless table-thead-bordered table-nowrap table-align-middle"> <thead style="background-color:#efefef; color:black"> <tr> <th>Email Filter</th> <th>Status</th> <th style="width: 5%;"></th> <th>Email Filter</th> <th>Status</th> <th style="width: 5%;"></th> </tr> </thead> <tbody> <tr> <td>Cisco IronPort</td> <td id="ciscoIronPortStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="ciscoIronPortView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Cisco IronPort');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Sophos AV</td> <td id="sophosAVStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="sophosAVView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Sophos AV');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>McAfee AV</td> <td id="mcafeeAVStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="mcafeeAVView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('McAfee AV');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Sophos ESA</td> <td id="sophosESAStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="sophosESAView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Sophos ESA');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Sophos PureMessage</td> <td id="sophosPureMessageStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="sophosPureMessageView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Sophos PureMessage');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Trustwave SEG</td> <td id="trustwaveSEGStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="trustwaveSEGView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Trustwave SEG');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Exchange Online Protection</td> <td id="eopStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="eopView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Exchange Online Protection');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Proofpoint SEG</td> <td id="proofpointSEGStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="proofpointSEGView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Proofpoint SEG');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>FireEye MX</td> <td id="fireEyeMXStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="fireEyeMXView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('FireEye MX');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>FireEye ETP Cloud</td> <td id="fireEyeETPStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="fireEyeETPView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('FireEye ETP Cloud');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Forcepoint ESG</td> <td id="forcepointESGStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="forcepointESGView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Forcepoint ESG');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Trend Micro HES</td> <td id="trendMicroHESStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="trendMicroHESView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Trend Micro HES');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Symantec MessageLabs</td> <td id="symantecMessageLabsStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="symantecMessageLabsView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Symantec MessageLabs');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Mimecast SEG</td> <td id="mimecastSEGStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="mimecastSEGView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Mimecast SEG');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Forcepoint Cloud</td> <td id="forcepointCloudStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="forcepointCloudView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Forcepoint Cloud');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> <td>Clearswift SEG</td> <td id="clearswiftSEGStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="clearswiftSEGView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Clearswift SEG');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> <tr> <td>Barracuda Email Security</td> <td id="barracudaESStatus"><span class="badge badge-soft-secondary"><i class="fas fa-eye-slash mr-1"></i>Not primed</span></td> <td><a id="barracudaESView" class="btn btn-xs btn-white disabled" href="#" onclick="viewFilterDetail('Barracuda Email Security');" data-toggle="modal" data-target="#detailModal"><i class="fas fa-eye mr-1"></i> View detail</a></td> </tr> </tbody> </table> </div> <!-- End Table --> </div> <!-- End Card --> </div> </div> <!-- Invoice Modal --> <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document" style="max-width:1000px"> <div class="modal-content"> <!-- Body --> <div class="modal-body pt-3 pb-sm-5 px-sm-5"> <div class="text-center mb-5"> <h3 class="mb-1" id="fNameDetail">Unspecified</h3> <span class="d-block" id="statusDetail">Unspecified</span> </div> <small class="text-cap mb-2">Summary</small> <div id="filterDetailSummary" class=" m-t-20"> </div> <hr class="my-5"> <p class="modal-footer-text">If you have any questions, please contact us at <a href="mailto:admin@caniphish.com">admin@caniphish.com</a>.</p> </div> <!-- End Body --> </div> </div> </div> <!-- End Invoice Modal --> <figure> <svg preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="64px" viewBox="0 0 1921 273" style="margin-bottom: -8px; enable-background:new 0 0 1921 273;" xml:space="preserve"> <polygon fill="#f9fbff" points="1921,0 0,0 0,273 " /> </svg> </figure> <script src="../../assets/vendor/jquery/dist/jquery.min.js"></script> <script src="../../assets/vendor/dropzone/dist/min/dropzone.min.js"></script> <script src="../assets/vendor/jquery-migrate/dist/jquery-migrate.min.js"></script> <script> // INITIALIZATION OF DROPZONE // ======================================================= Dropzone.autoDiscover = false; var filePreview = `<div class="dz-preview dz-file-preview"> <div class="dz-details" > <div class="dz-filename"><span data-dz-name></span></div> <div class="dz-size" data-dz-size></div> <img data-dz-thumbnail /> </div > <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div> <div class="dz-error-message"><span data-dz-errormessage></span></div> </div >`; var arr_from_json; var dropzoneOptions = { dictDefaultMessage: 'Drop Here!', autoProcessQueue: false, parallelUploads: 1100, uploadMultiple: true, url: "/Home/PhishiousResult", paramName: "file", maxFilesize: 1, // MB previewTemplate: filePreview, addRemoveLinks: true, init: function () { this.on("successmultiple", function (file, response) { console.log("successmultiple > " + file.name); if (response != "No Filters Found") { arr_from_json = JSON.parse(response); } console.log(arr_from_json); for (var i in arr_from_json) { primeFilter(arr_from_json[i]); } $("#detonateContainer").show(); $("#analysisDiv").show(); $([document.documentElement, document.body]).animate({ scrollTop: $("#step2Seperator").offset().top }, 1000); $("#phishious-submit").css("background", "#00c9a7"); $("#phishious-submit").css("border-color", "#00c9a7"); $("#phishious-submit").html("Filters Primed"); $('#phishious-submit').prop('disabled', true); }); } }; var myDropzone = new Dropzone("div#phishiousDropZone", dropzoneOptions); var fileString = []; var fileArray = []; myDropzone.on("addedfile", function (file) { console.log('Primer file added!!!'); $('#phishious-submit').prop('disabled', false); $("#phishious-submit").html("Prime Filters"); $("#phishious-submit").css("background", "#377dff"); $("#phishious-submit").css("border-color", "#377dff"); //fileArray.push(file); //const reader = new FileReader(); //reader.onload = () => { // const fileAsBinaryString = reader.result; // console.log(fileAsBinaryString); // fileString.push(fileAsBinaryString); // // do whatever you want with the file content //}; //reader.onabort = () => console.log('file reading was aborted'); //reader.onerror = () => console.log('file reading has failed'); //reader.readAsBinaryString(file); }); $("#phishious-submit").click(function (e) { e.preventDefault(); myDropzone.processQueue(); }); </script> <script> var detonateFileString = []; var detonateFileArray = []; var dfilter_array; var dropzoneDetonateOptions = { dictDefaultMessage: 'Drop Here!', autoProcessQueue: false, parallelUploads: 1100, uploadMultiple: true, url: "/Home/PhishiousDetonate", paramName: "file", maxFilesize: 1, // MB previewTemplate: filePreview, addRemoveLinks: true, init: function () { this.on("successmultiple", function (file, response) { console.log("successmultiple > " + file.name); if (response != "No Filters Found") { dfilter_array = JSON.parse(response); } console.log(dfilter_array); detonateFilter(dfilter_array); //for (var i in arr_from_json) { // primeFilter(arr_from_json[i]); //} $([document.documentElement, document.body]).animate({ scrollTop: $("#detonate-submit").offset().top }, 1000); $("#detonate-submit").css("background", "#ed4c78"); $("#detonate-submit").css("border-color", "#ed4c78"); $("#detonate-submit").html("Filters Detonated"); $('#detonate-submit').prop('disabled', true); detonateFileArray = []; }); } }; var myDetonateDropzone = new Dropzone("div#detonateDropZone", dropzoneDetonateOptions); myDetonateDropzone.on("addedfile", function (file) { detonateFileArray.push(file); console.log('Detonation file added!!!'); $("#detonate-submit").html("Detonate Filters"); $("#detonate-submit").css("background", "#377dff"); $("#detonate-submit").css("border-color", "#377dff"); }); $("#detonate-submit").click(function (e) { e.preventDefault(); console.log(detonateFileArray.length); if (detonateFileArray.length == 0) { detonateFilter(detonateFileArray); $("#detonate-submit").css("background", "#ed4c78"); $("#detonate-submit").css("border-color", "#ed4c78"); $("#detonate-submit").html("Filters Detonated"); $('#detonate-submit').prop('disabled', true); $([document.documentElement, document.body]).animate({ scrollTop: $("#detonate-submit").offset().top }, 1000); } else { myDetonateDropzone.processQueue(); } }); </script> <script> var primedFilters = []; var detonatedFilters = []; function primeFilter(filter) { primedFilters.push(filter); switch (filter.Filter) { case "Cisco IronPort": $("#ciscoIronPortStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Sophos AV": $("#sophosAVStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "McAfee AV": $("#mcafeeAVStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Sophos ESA": $("#sophosESAStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Sophos PureMessage": $("#sophosPureMessageStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Trustwave SEG": $("#trustwaveSEGStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Exchange Online Protection": $("#eopStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Proofpoint SEG": $("#proofpointSEGStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "FireEye MX": $("#fireEyeMXStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "FireEye ETP Cloud": $("#fireEyeETPStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Forcepoint ESG": $("#forcepointESGStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Trend Micro HES": $("#trendMicroHESStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Symantec MessageLabs": $("#symantecMessageLabsStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Mimecast SEG": $("#mimecastSEGStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Forcepoint Cloud": $("#forcepointCloudStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Clearswift SEG": $("#clearswiftSEGStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); break; case "Barracuda Email Security": $("#barracudaESStatus").html('<span class="badge badge-soft-warning"><i class="fas fa-circle mr-1"></i>Primed</span>'); //default: // console.log("No filter found"); // console.log(filter); } } function detonateFilter(filters) { detonatedFilters = filters; for (var i in primedFilters) { var filterResponse = false; for (var x in filters) { if (primedFilters[i].Filter == filters[x].Filter) { filterResponse = true; detonateFilterResponse(filters[x]); } } if (!filterResponse) { console.log("5th Function"); detonateFilterResponse(primedFilters[i]); } } primedFilters = []; } function detonateFilterResponse(dFilter) { console.log(dFilter); switch (dFilter.Filter) { case "Cisco IronPort": if (dFilter.Status == "Vulnerable") { $("#ciscoIronPortStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#ciscoIronPortStatus").addClass("pVuln"); } else if (((dFilter.Status == "Secure") && !($("#ciscoIronPortStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#ciscoIronPortStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#ciscoIronPortView").removeClass('disabled'); break; case "Sophos AV": if (dFilter.Status == "Vulnerable") { $("#sophosAVStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#sophosAVStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#sophosAVStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#sophosAVStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#sophosAVView").removeClass('disabled'); break; case "McAfee AV": if (dFilter.Status == "Vulnerable") { $("#mcafeeAVStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#mcafeeAVStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#mcafeeAVStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#mcafeeAVStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#mcafeeAVView").removeClass('disabled'); break; case "Sophos ESA": if (dFilter.Status == "Vulnerable") { $("#sophosESAStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#sophosESAStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#sophosESAStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#sophosESAStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#sophosESAView").removeClass('disabled'); break; case "Sophos PureMessage": if (dFilter.Status == "Vulnerable") { $("#sophosPureMessageStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#sophosPureMessageStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#sophosPureMessageStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#sophosPureMessageStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#sophosPureMessageView").removeClass('disabled'); break; case "Trustwave SEG": if (dFilter.Status == "Vulnerable") { $("#trustwaveSEGStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#trustwaveSEGStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#trustwaveSEGStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#trustwaveSEGStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#trustwaveSEGView").removeClass('disabled'); break; case "Exchange Online Protection": if (dFilter.Status == "Vulnerable") { $("#eopStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#eopStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#eopStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#eopStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#eopView").removeClass('disabled'); break; case "Proofpoint SEG": if (dFilter.Status == "Vulnerable") { $("#proofpointSEGStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#proofpointSEGStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#proofpointSEGStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#proofpointSEGStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#proofpointSEGView").removeClass('disabled'); break; case "FireEye MX": if (dFilter.Status == "Vulnerable") { $("#fireEyeMXStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#fireEyeMXStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#fireEyeMXStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#fireEyeMXStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#fireEyeMXView").removeClass('disabled'); break; case "FireEye ETP Cloud": if (dFilter.Status == "Vulnerable") { $("#fireEyeETPStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#fireEyeETPStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#fireEyeETPStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#fireEyeETPStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#fireEyeETPView").removeClass('disabled'); break; case "Forcepoint ESG": if (dFilter.Status == "Vulnerable") { $("#forcepointESGStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#forcepointESGStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#forcepointESGStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#forcepointESGStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#forcepointESGView").removeClass('disabled'); break; case "Trend Micro HES": if (dFilter.Status == "Vulnerable") { $("#trendMicroHESStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#trendMicroHESStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#trendMicroHESStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#trendMicroHESStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#trendMicroHESView").removeClass('disabled'); break; case "Symantec MessageLabs": if (dFilter.Status == "Vulnerable") { $("#symantecMessageLabsStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#symantecMessageLabsStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#symantecMessageLabsStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#symantecMessageLabsStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#symantecMessageLabsView").removeClass('disabled'); break; case "Mimecast SEG": if (dFilter.Status == "Vulnerable") { $("#mimecastSEGStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#mimecastSEGStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#mimecastSEGStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#mimecastSEGStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#mimecastSEGView").removeClass('disabled'); break; case "Forcepoint Cloud": if (dFilter.Status == "Vulnerable") { $("#forcepointCloudStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#forcepointCloudStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#forcepointCloudStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#forcepointCloudStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#forcepointCloudView").removeClass('disabled'); break; case "Clearswift SEG": if (dFilter.Status == "Vulnerable") { $("#clearswiftSEGStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#clearswiftSEGStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#clearswiftSEGStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#clearswiftSEGStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#clearswiftSEGView").removeClass('disabled'); break; case "Barracuda Email Security": if (dFilter.Status == "Vulnerable") { $("#barracudaESStatus").html('<span class="badge badge-soft-danger"><i class="fas fa-exclamation-circle mr-1"></i>Phish Undetected</span>'); $("#barracudaESStatus").addClass("pVuln"); } else if ((dFilter.Status == "Secure" && !($("#barracudaESStatus").hasClass("pVuln"))) || (dFilter.Status == "Priming")) { $("#barracudaESStatus").html('<span class="badge badge-soft-success"><i class="fas fa-check-circle mr-1"></i>Phish Blocked</span>'); } $("#barracudaESView").removeClass('disabled'); default: console.log("No filter found"); } } </script> <script> function DisplayProgressMessage(ctl, msg) { $(ctl).text(msg); $(ctl).submit(); return true; } var entityMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;', '`': '&#x60;', '=': '&#x3D;' }; function viewFilterDetail(filterName) { $("#fNameDetail").text(filterName); var objTo = document.getElementById('filterDetailSummary'); $("#filterDetailSummary").html(''); var filterStatus = ''; var filterFound = false; for (var x in detonatedFilters) { if (detonatedFilters[x].Filter == filterName) { filterFound = true; if ((filterStatus === '') || (filterStatus === "Secure")) { filterStatus = detonatedFilters[x].Status; } var tempStatus = ""; if (detonatedFilters[x].Status === "Secure") { tempStatus = "<a class='text-success'>Phish Blocked</a>"; } else if (detonatedFilters[x].Status === "Vulnerable") { tempStatus = "<a class='text-danger'>Phish Undetected</a>"; } var escapeString = escapeHtml(detonatedFilters[x].SurroundingText); var divtest = document.createElement("div"); var fAnalysed = `<ul class="list-group mb-4"> <li class="list-group-item text-dark"> <div class="d-flex justify-content-between align-items-center"> <small>File Analysed</small> <small>` + detonatedFilters[x].FileName + `</small> </div> </li>` var fStatus = `<li class="list-group-item text-dark"> <div class="d-flex justify-content-between align-items-center"> <small>Phish Status</small> <small>` + tempStatus + `</small> </div> </li>` var tAnalysed = ""; for (var t in detonatedFilters[x].TextAnalysed) { tAnalysed += `<li class="list-group-item list-group-item-light text-dark"> <div class="d-flex justify-content-between align-items-center"> <small style='max-width:38%'>Text Analysed: <code style='font-size:100%'>` + detonatedFilters[x].TextAnalysed[t].TextAnalysed + `</code></small> <small style='max-width:60%'><q>` + detonatedFilters[x].TextAnalysed[t].Description + `</q></small> </div> </li>` } var cSample = `<li class="list-group-item list-group-item-light text-dark"> <div class="card bg-dark mb-1"> <div class="card-body text-monospace font-size-1 p-6"> <div class="mb-1"> <span class="d-block text-white-70">> Header Snippet</span> <span id="codeSnippet" class="d-block text-success font-weight-normal"> ` + escapeString.replace(/(?:\r\n|\r|\n)/g, '<br>') + ` </span> </div> </div> </div> </li> </ul>` divtest.innerHTML = fAnalysed + fStatus + tAnalysed + cSample; objTo.appendChild(divtest); } } if (filterStatus === "Success") { $("#statusDetail").removeClass("text-danger"); $("#statusDetail").addClass("text-success"); $("#statusDetail").text("Phish Blocked"); } else if (filterStatus === "Vulnerable") { $("#statusDetail").removeClass("text-success"); $("#statusDetail").addClass("text-danger"); $("#statusDetail").text("Phish Undetected"); } else { $("#statusDetail").removeClass("text-danger"); $("#statusDetail").addClass("text-success"); $("#statusDetail").text("Phish Blocked"); } if (!filterFound) { $("#filterDetailSummary").html('<span>No filter response was detected. The filter has almost certainly detected any phishing material delivered.</span>'); } } function escapeHtml(string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); } </script>
the_stack
@page @model ResponsiveModel @{ ViewData["Title"] = "Responsive"; ViewData["PageName"] = "datatables_responsive"; ViewData["Category1"] = "Datatables"; ViewData["Heading"] = "<i class='subheader-icon fal fa-table'></i> DataTables: <span class='fw-300'>Responsive</span> <sup class='badge badge-primary fw-500'>ADDON</sup>"; ViewData["PageDescription"] = "Create headache free searching, sorting and pagination tables without any complex configuration"; } @section HeadBlock { <link rel="stylesheet" media="screen, print" href="~/css/datagrid/datatables/datatables.bundle.css"> } <div class="row"> <div class="col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> Example <span class="fw-300"><i>Table</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <table id="dt-basic-example" class="table table-bordered table-hover table-striped w-100"> <thead> <tr> <th>OrderID</th> <th>Recipient</th> <th>Shipping.Address</th> <th>Shipping.Country</th> <th>Shipping.City</th> <th>Agent</th> <th>Company</th> <th>OrganizationID</th> <th>Latitude</th> <th>Longitude</th> <th>Shipping.Date</th> <th>Delivery.Date</th> <th>Payment.Date</th> <th>Timezone</th> <th>Payment</th> <th>Email</th> <th>Phone</th> <th>Status</th> <th>Admin Controls</th> </tr> </thead> <tbody> <tr> <td>298728508</td> <td>Samuel A. Townsend</td> <td>Ap #376-4611 Et St.</td> <td>Togo</td> <td>Monceau-sur-Sambre</td> <td>Dorian Mcintyre</td> <td>Gravida Molestie PC</td> <td>00439892299</td> <td>17.61388</td> <td>96.86623</td> <td>2019-10-06 21:27:12</td> <td>30/05/18</td> <td>2019-04-19 09:08:30</td> <td>PDT</td> <td>$36158.32</td> <td>euismod.mauris.eu@@purusactellus.com</td> <td>511-7454</td> <td>1</td> <td></td> </tr> <tr> <td>398199588</td> <td>Clare C. Perkins</td> <td>1191 Sodales Avenue</td> <td>Costa Rica</td> <td>Mersin</td> <td>Robert Howe</td> <td>Gravida Molestie Arcu Ltd</td> <td>31305907399</td> <td>-68.29001</td> <td>100.86604</td> <td>2018-07-09 17:17:55</td> <td>05/08/18</td> <td>2020-02-08 16:49:29</td> <td>PDT</td> <td>$37471.19</td> <td>dictum.Proin.eget@@sed.ca</td> <td>611-8302</td> <td>1</td> <td></td> </tr> <tr> <td>419738638</td> <td>Perry I. Gonzales</td> <td>4895 Vel, Rd.</td> <td>United States</td> <td>Paglieta</td> <td>Nita Taylor</td> <td>Lobortis Ultrices Vivamus Corp.</td> <td>55848451599</td> <td>-76.12256</td> <td>-71.3302</td> <td>2019-12-17 05:39:26</td> <td>15/05/19</td> <td>2018-05-06 13:26:42</td> <td>PDT</td> <td>$70959.34</td> <td>ut@@sitametluctus.ca</td> <td>750-0429</td> <td>2</td> <td></td> </tr> <tr> <td>63227196</td> <td>Jelani L. Phelps</td> <td>P.O. Box 632, 1009 Erat. St.</td> <td>Myanmar</td> <td>Moorsele</td> <td>Rhona Contreras</td> <td>Arcu Foundation</td> <td>05775245799</td> <td>-77.54682</td> <td>132.85627</td> <td>2019-10-19 14:01:20</td> <td>22/11/18</td> <td>2019-07-04 18:52:44</td> <td>PDT</td> <td>$49125.35</td> <td>aliquet.diam.Sed@@Nullam.edu</td> <td>409-6605</td> <td>8</td> <td></td> </tr> <tr> <td>93816161</td> <td>Xerxes T. Conner</td> <td>776-2061 Sodales Rd.</td> <td>Faroe Islands</td> <td>Santander</td> <td>Stephen Frye</td> <td>Ligula LLC</td> <td>15462873499</td> <td>24.54806</td> <td>65.87806</td> <td>2020-03-08 21:29:49</td> <td>05/09/18</td> <td>2018-07-25 00:28:16</td> <td>PST</td> <td>$18967.68</td> <td>nec@@euodioPhasellus.org</td> <td>257-0999</td> <td>8</td> <td></td> </tr> <tr> <td>163796139</td> <td>Candice L. Donaldson</td> <td>4589 Augue St.</td> <td>Congo (Brazzaville)</td> <td>Peñalolén</td> <td>Adam Lyons</td> <td>Ullamcorper LLP</td> <td>68866776699</td> <td>-41.32</td> <td>-65.2217</td> <td>2018-11-05 11:41:22</td> <td>27/06/18</td> <td>2018-09-11 23:52:20</td> <td>PST</td> <td>$50588.44</td> <td>Duis.cursus.diam@@Aenean.co.uk</td> <td>1-852-753-2487</td> <td>8</td> <td></td> </tr> <tr> <td>437801703</td> <td>Hyacinth P. Carson</td> <td>1892 Et, St.</td> <td>Korea, North</td> <td>Beaumaris</td> <td>Lawrence Powell</td> <td>Aliquam Eros Foundation</td> <td>06430069899</td> <td>54.39702</td> <td>-149.16263</td> <td>2018-09-16 21:33:18</td> <td>18/01/20</td> <td>2019-08-31 08:43:58</td> <td>PDT</td> <td>$90455.68</td> <td>ac@@duisemperet.edu</td> <td>1-868-762-5439</td> <td>2</td> <td></td> </tr> <tr> <td>29387302K</td> <td>Omar E. Morrison</td> <td>4901 Donec Avenue</td> <td>Mali</td> <td>Kansas City</td> <td>Dai Walters</td> <td>Est Ac Mattis Corporation</td> <td>79969224599</td> <td>-56.95423</td> <td>-176.51121</td> <td>2019-07-27 18:19:38</td> <td>24/07/19</td> <td>2019-06-04 10:14:46</td> <td>PDT</td> <td>$51246.35</td> <td>vehicula.risus@@accumsanneque.com</td> <td>1-914-907-0932</td> <td>8</td> <td></td> </tr> <tr> <td>24438546K</td> <td>Dora H. Mcmillan</td> <td>230-6443 Sed Rd.</td> <td>Angola</td> <td>Joliet</td> <td>Kyla Perry</td> <td>Interdum Associates</td> <td>91465277899</td> <td>-9.27641</td> <td>168.93885</td> <td>2020-01-18 04:40:04</td> <td>05/08/19</td> <td>2018-12-21 13:58:27</td> <td>PST</td> <td>$66645.66</td> <td>sem.elit.pharetra@@molestiesodalesMauris.ca</td> <td>1-186-429-8809</td> <td>3</td> <td></td> </tr> <tr> <td>236288242</td> <td>Howard J. Watkins</td> <td>9532 Ut Avenue</td> <td>United States</td> <td>Cannock</td> <td>Ora Patterson</td> <td>Eu Incorporated</td> <td>63202631099</td> <td>-71.62815</td> <td>104.40843</td> <td>2018-10-28 19:14:38</td> <td>21/09/18</td> <td>2019-03-24 09:04:54</td> <td>PST</td> <td>$06463.36</td> <td>mi@@indolor.org</td> <td>515-1656</td> <td>8</td> <td></td> </tr> <tr> <td>78251840</td> <td>Peter E. Riggs</td> <td>5178 Phasellus Avenue</td> <td>Cyprus</td> <td>Litueche</td> <td>Tallulah Booker</td> <td>Faucibus Corporation</td> <td>46695699299</td> <td>-7.23908</td> <td>-130.77606</td> <td>2020-03-14 14:56:34</td> <td>13/04/20</td> <td>2019-02-23 10:15:53</td> <td>PST</td> <td>$77593.22</td> <td>mi@@Ut.ca</td> <td>874-9462</td> <td>4</td> <td></td> </tr> <tr> <td>69169546</td> <td>Armand X. Roberson</td> <td>318-3022 Adipiscing Av.</td> <td>Switzerland</td> <td>Doues</td> <td>Willa Hensley</td> <td>Vehicula LLP</td> <td>25972471299</td> <td>-36.95449</td> <td>35.7161</td> <td>2019-03-23 11:36:19</td> <td>13/04/20</td> <td>2020-01-12 17:36:13</td> <td>PDT</td> <td>$72178.30</td> <td>ut.molestie.in@@loremvitae.ca</td> <td>631-6228</td> <td>6</td> <td></td> </tr> <tr> <td>465099461</td> <td>Reese Y. Wagner</td> <td>9248 Hendrerit Ave</td> <td>Canada</td> <td>Bellevue</td> <td>Jade Thomas</td> <td>Magna Corp.</td> <td>89884508899</td> <td>-21.19867</td> <td>-90.01975</td> <td>2019-07-21 23:16:57</td> <td>04/09/18</td> <td>2018-07-14 03:01:55</td> <td>PDT</td> <td>$52335.19</td> <td>sem@@porttitorvulputateposuere.co.uk</td> <td>289-9705</td> <td>5</td> <td></td> </tr> <tr> <td>398720431</td> <td>Cassandra N. Gross</td> <td>141-6837 Amet, Ave</td> <td>Oman</td> <td>Guardia Sanframondi</td> <td>Thor Powell</td> <td>Non Ante Inc.</td> <td>82480723199</td> <td>70.98602</td> <td>82.79917</td> <td>2020-03-15 20:24:27</td> <td>26/10/19</td> <td>2018-11-04 08:06:56</td> <td>PDT</td> <td>$16708.05</td> <td>tristique.neque.venenatis@@libero.co.uk</td> <td>1-781-822-1852</td> <td>1</td> <td></td> </tr> <tr> <td>9036359K</td> <td>Ishmael Y. Clayton</td> <td>483-6510 Primis Rd.</td> <td>Sint Maarten</td> <td>Genzano di Lucania</td> <td>Murphy Wolf</td> <td>In Hendrerit Consectetuer Limited</td> <td>63909733499</td> <td>89.58444</td> <td>76.23368</td> <td>2019-03-21 13:00:20</td> <td>27/10/18</td> <td>2018-05-20 19:01:31</td> <td>PDT</td> <td>$84047.92</td> <td>luctus.Curabitur.egestas@@Crasconvallisconvallis.edu</td> <td>1-461-193-0112</td> <td>7</td> <td></td> </tr> <tr> <td>389772283</td> <td>Stuart C. Joyce</td> <td>Ap #131-985 Integer Av.</td> <td>Bouvet Island</td> <td>Leersum</td> <td>Denise Barry</td> <td>Suspendisse Aliquet Sem LLP</td> <td>34887383999</td> <td>-88.78717</td> <td>28.97232</td> <td>2018-05-03 01:23:46</td> <td>20/08/18</td> <td>2020-03-18 23:38:00</td> <td>PST</td> <td>$88461.01</td> <td>egestas@@inmolestietortor.net</td> <td>597-2871</td> <td>5</td> <td></td> </tr> <tr> <td>81446695</td> <td>Willa I. George</td> <td>942-2277 Semper Avenue</td> <td>Tokelau</td> <td>Greenwich</td> <td>Grace Butler</td> <td>Eros Incorporated</td> <td>12979293099</td> <td>56.21428</td> <td>12.63295</td> <td>2019-12-09 14:40:36</td> <td>26/02/19</td> <td>2019-07-31 11:14:30</td> <td>PDT</td> <td>$12197.07</td> <td>mi.eleifend.egestas@@risus.com</td> <td>389-0900</td> <td>8</td> <td></td> </tr> <tr> <td>500685816</td> <td>Carlos U. Reyes</td> <td>Ap #815-3108 Conubia Road</td> <td>Falkland Islands</td> <td>Itajaí</td> <td>Dean Sherman</td> <td>Libero Integer LLP</td> <td>15847671499</td> <td>5.8307</td> <td>-74.93198</td> <td>2019-06-15 17:44:54</td> <td>29/09/19</td> <td>2020-03-01 19:37:04</td> <td>PDT</td> <td>$43345.74</td> <td>eleifend.nec@@vitaesodalesat.ca</td> <td>455-7113</td> <td>5</td> <td></td> </tr> <tr> <td>457242182</td> <td>Hermione B. Lee</td> <td>Ap #422-1839 Rutrum Rd.</td> <td>Rwanda</td> <td>PiŽtrain</td> <td>Howard Valdez</td> <td>Sollicitudin Limited</td> <td>80426922499</td> <td>-9.01342</td> <td>68.71341</td> <td>2020-01-14 15:53:18</td> <td>04/10/18</td> <td>2019-09-28 18:27:51</td> <td>PDT</td> <td>$49349.89</td> <td>eleifend.nec.malesuada@@molestiearcuSed.org</td> <td>655-7290</td> <td>7</td> <td></td> </tr> <tr> <td>183731130</td> <td>Nelle T. Humphrey</td> <td>889-6097 Erat Av.</td> <td>Moldova</td> <td>Fort St. John</td> <td>Phoebe Roy</td> <td>Luctus Et Ultrices Associates</td> <td>71218005699</td> <td>80.81534</td> <td>-23.54473</td> <td>2018-08-06 00:30:48</td> <td>28/07/18</td> <td>2019-07-20 18:58:39</td> <td>PST</td> <td>$20426.08</td> <td>non@@sedestNunc.com</td> <td>1-217-489-4334</td> <td>4</td> <td></td> </tr> <tr> <td>434423244</td> <td>Cooper M. Estes</td> <td>4438 Et, Road</td> <td>Colombia</td> <td>Viesville</td> <td>Quentin Kent</td> <td>Ut Tincidunt Orci Foundation</td> <td>22577824199</td> <td>88.14995</td> <td>10.13151</td> <td>2019-09-27 05:13:59</td> <td>17/06/19</td> <td>2020-02-19 16:46:00</td> <td>PDT</td> <td>$00479.64</td> <td>pede.malesuada@@magnis.com</td> <td>120-2740</td> <td>1</td> <td></td> </tr> <tr> <td>173142277</td> <td>Odette A. Contreras</td> <td>Ap #595-976 Mauris Av.</td> <td>Cuba</td> <td>Charny</td> <td>Mara Goodwin</td> <td>Pellentesque LLC</td> <td>12418581499</td> <td>-27.97145</td> <td>-66.93835</td> <td>2018-09-13 17:16:23</td> <td>28/02/19</td> <td>2019-12-03 15:10:20</td> <td>PDT</td> <td>$03195.51</td> <td>lorem.vitae@@aultriciesadipiscing.com</td> <td>563-1027</td> <td>1</td> <td></td> </tr> <tr> <td>329934357</td> <td>Keelie H. Nicholson</td> <td>P.O. Box 699, 2608 Tortor, Road</td> <td>Russian Federation</td> <td>Trollhättan</td> <td>Silas Diaz</td> <td>Mollis Associates</td> <td>63700729899</td> <td>79.61691</td> <td>-83.95099</td> <td>2019-11-28 18:58:15</td> <td>16/03/20</td> <td>2019-07-17 08:19:36</td> <td>PDT</td> <td>$53207.42</td> <td>ipsum.Suspendisse.sagittis@@sem.org</td> <td>1-559-904-1886</td> <td>7</td> <td></td> </tr> <tr> <td>474872939</td> <td>Cecilia H. Frank</td> <td>839-1282 Nec Road</td> <td>Northern Mariana Islands</td> <td>San Giovanni Lipioni</td> <td>Paloma Dean</td> <td>At Corp.</td> <td>24891310699</td> <td>30.42826</td> <td>-142.47665</td> <td>2019-05-24 17:49:35</td> <td>26/09/19</td> <td>2019-12-05 11:34:22</td> <td>PST</td> <td>$10381.16</td> <td>Donec.tempus@@enim.ca</td> <td>1-767-599-5793</td> <td>2</td> <td></td> </tr> <tr> <td>237732855</td> <td>Melinda V. Hancock</td> <td>Ap #935-5278 Ut, Av.</td> <td>French Polynesia</td> <td>Saint-Denis</td> <td>Vanna Weber</td> <td>Vulputate Dui Corporation</td> <td>93847126699</td> <td>-35.24843</td> <td>139.47048</td> <td>2020-04-01 01:53:34</td> <td>27/08/19</td> <td>2019-09-12 09:58:48</td> <td>PDT</td> <td>$02518.53</td> <td>tempus.risus@@arcuNunc.com</td> <td>629-3462</td> <td>7</td> <td></td> </tr> <tr> <td>36599904K</td> <td>Sandra W. Mcclain</td> <td>Ap #685-944 Suspendisse Rd.</td> <td>French Guiana</td> <td>Chiari</td> <td>Kennan Blanchard</td> <td>Nisi A Odio Industries</td> <td>34600392099</td> <td>0.3617</td> <td>-21.78242</td> <td>2020-02-10 06:28:52</td> <td>23/09/19</td> <td>2018-09-04 04:51:27</td> <td>PDT</td> <td>$14114.00</td> <td>et.netus@@laciniaorci.net</td> <td>477-8047</td> <td>7</td> <td></td> </tr> <tr> <td>391273049</td> <td>Leah T. Henson</td> <td>426-927 Metus. Av.</td> <td>Switzerland</td> <td>Fabro</td> <td>Jolie Orr</td> <td>Scelerisque Dui Suspendisse Ltd</td> <td>81751496899</td> <td>47.77387</td> <td>47.75601</td> <td>2018-06-04 17:50:17</td> <td>21/11/19</td> <td>2019-10-28 20:19:02</td> <td>PDT</td> <td>$44936.48</td> <td>mauris.ut@@tempusrisusDonec.edu</td> <td>212-2265</td> <td>1</td> <td></td> </tr> <tr> <td>381714640</td> <td>Samuel A. Anthony</td> <td>1778 Proin St.</td> <td>Nepal</td> <td>Aisemont</td> <td>Xavier Hoover</td> <td>Per Ltd</td> <td>75946837399</td> <td>-15.41389</td> <td>142.52182</td> <td>2020-03-02 13:37:26</td> <td>28/01/19</td> <td>2018-06-01 01:45:55</td> <td>PDT</td> <td>$26708.66</td> <td>Duis@@Donecnibhenim.co.uk</td> <td>753-2322</td> <td>3</td> <td></td> </tr> <tr> <td>466825212</td> <td>Tanner Q. Powers</td> <td>675-5189 Donec Ave</td> <td>Mauritania</td> <td>Ucluelet</td> <td>Molly Cain</td> <td>Imperdiet Non Inc.</td> <td>43623678899</td> <td>34.17445</td> <td>-60.66068</td> <td>2020-01-12 07:09:57</td> <td>20/09/19</td> <td>2018-10-01 10:15:46</td> <td>PST</td> <td>$29941.26</td> <td>nibh@@sedfacilisisvitae.net</td> <td>709-3504</td> <td>2</td> <td></td> </tr> <tr> <td>306059262</td> <td>Gemma S. Donaldson</td> <td>815-4374 Sodales Rd.</td> <td>Mongolia</td> <td>Stirling</td> <td>Sonya Charles</td> <td>Donec Tempus Lorem Foundation</td> <td>96492478299</td> <td>-84.75575</td> <td>30.85759</td> <td>2019-07-16 16:20:57</td> <td>26/08/18</td> <td>2019-06-21 04:38:33</td> <td>PDT</td> <td>$12765.79</td> <td>velit.Pellentesque.ultricies@@orciconsectetuereuismod.org</td> <td>1-196-679-5398</td> <td>4</td> <td></td> </tr> <tr> <td>498097030</td> <td>Devin P. Cline</td> <td>168-5287 Libero Ave</td> <td>Hungary</td> <td>Akşehir</td> <td>Cailin Bruce</td> <td>Mauris Corporation</td> <td>16200595699</td> <td>76.59449</td> <td>114.27132</td> <td>2018-12-13 16:48:11</td> <td>12/04/20</td> <td>2018-10-31 09:13:51</td> <td>PDT</td> <td>$85822.90</td> <td>risus.Donec.nibh@@adipiscingelitAliquam.org</td> <td>1-231-949-2611</td> <td>8</td> <td></td> </tr> <tr> <td>120249843</td> <td>Zeph P. Garcia</td> <td>Ap #104-7705 Per Avenue</td> <td>Liechtenstein</td> <td>Valkenburg aan de Geul</td> <td>Hiram Fleming</td> <td>Placerat Velit Quisque Institute</td> <td>63398162499</td> <td>88.30805</td> <td>-89.04727</td> <td>2019-01-12 23:49:31</td> <td>09/03/20</td> <td>2018-06-30 05:01:18</td> <td>PDT</td> <td>$25462.41</td> <td>iaculis.odio@@Suspendisseacmetus.org</td> <td>1-603-762-9764</td> <td>7</td> <td></td> </tr> <tr> <td>50846806</td> <td>Kellie Q. Charles</td> <td>Ap #435-5911 Quis St.</td> <td>South Africa</td> <td>Merzig</td> <td>Hermione Carney</td> <td>Mollis Nec Cursus Corporation</td> <td>84996045699</td> <td>76.79126</td> <td>-83.45942</td> <td>2018-08-21 21:48:00</td> <td>11/02/20</td> <td>2018-09-21 15:54:57</td> <td>PDT</td> <td>$30914.84</td> <td>blandit@@interdum.org</td> <td>1-255-356-5084</td> <td>6</td> <td></td> </tr> <tr> <td>37342868K</td> <td>Marny E. Shelton</td> <td>P.O. Box 942, 5733 Augue Street</td> <td>Moldova</td> <td>Treppo Carnico</td> <td>Teagan Haley</td> <td>Volutpat Nulla LLC</td> <td>39216464299</td> <td>-59.09746</td> <td>148.31371</td> <td>2019-08-10 01:18:23</td> <td>15/11/19</td> <td>2019-01-21 15:46:43</td> <td>PST</td> <td>$81585.15</td> <td>in.tempus@@metusInlorem.org</td> <td>820-8296</td> <td>4</td> <td></td> </tr> <tr> <td>383281571</td> <td>Kaye K. Velazquez</td> <td>Ap #797-9673 Lorem, Ave</td> <td>Panama</td> <td>Québec City</td> <td>Natalie Jensen</td> <td>Purus Ac Tellus Corporation</td> <td>87769235299</td> <td>-75.81824</td> <td>-164.53735</td> <td>2019-11-26 16:13:50</td> <td>19/10/18</td> <td>2018-04-26 02:36:22</td> <td>PDT</td> <td>$60217.84</td> <td>in@@nunc.org</td> <td>1-470-907-7287</td> <td>3</td> <td></td> </tr> <tr> <td>137423448</td> <td>David Z. Allison</td> <td>2852 Dictum Road</td> <td>India</td> <td>Rachecourt</td> <td>Ryder Mays</td> <td>Nulla Facilisis Suspendisse Incorporated</td> <td>37662209799</td> <td>-86.46214</td> <td>-10.41009</td> <td>2019-05-30 13:41:44</td> <td>26/10/18</td> <td>2020-04-09 06:16:15</td> <td>PDT</td> <td>$12094.43</td> <td>Nullam.ut.nisi@@vitaenibhDonec.ca</td> <td>1-780-194-9652</td> <td>1</td> <td></td> </tr> <tr> <td>484358303</td> <td>Alea W. Myers</td> <td>9068 Aptent Rd.</td> <td>Georgia</td> <td>Milwaukee</td> <td>Ayanna Bradshaw</td> <td>Est Mauris Industries</td> <td>84505303699</td> <td>-41.82831</td> <td>-78.13223</td> <td>2019-12-11 19:41:42</td> <td>18/07/19</td> <td>2020-01-15 16:43:56</td> <td>PST</td> <td>$36288.42</td> <td>Quisque@@augueeutempor.co.uk</td> <td>463-1143</td> <td>7</td> <td></td> </tr> <tr> <td>251222134</td> <td>Igor E. House</td> <td>Ap #684-4781 Ut Ave</td> <td>Bhutan</td> <td>Todi</td> <td>Kaseem Nash</td> <td>Bibendum Sed Incorporated</td> <td>91393836599</td> <td>10.53105</td> <td>-160.14301</td> <td>2018-09-14 12:02:53</td> <td>08/11/19</td> <td>2019-02-01 07:53:03</td> <td>PDT</td> <td>$30489.03</td> <td>arcu.Nunc@@vulputateduinec.ca</td> <td>174-5351</td> <td>5</td> <td></td> </tr> <tr> <td>423102993</td> <td>Sasha X. Sherman</td> <td>7260 Nunc Street</td> <td>New Zealand</td> <td>Sokoto</td> <td>Lev Alvarado</td> <td>Sociis Natoque Penatibus Associates</td> <td>02707597499</td> <td>80.09698</td> <td>28.94072</td> <td>2019-08-18 17:03:45</td> <td>21/05/19</td> <td>2018-10-19 11:13:06</td> <td>PDT</td> <td>$14243.46</td> <td>lorem@@Cumsociis.com</td> <td>1-982-499-2446</td> <td>2</td> <td></td> </tr> <tr> <td>408702941</td> <td>Signe T. Witt</td> <td>Ap #753-6683 Id, Road</td> <td>Mexico</td> <td>Roio del Sangro</td> <td>Julian Brooks</td> <td>Eleifend Non Dapibus Associates</td> <td>97265820799</td> <td>69.91254</td> <td>74.32922</td> <td>2018-08-31 05:37:45</td> <td>20/09/18</td> <td>2019-03-07 09:37:10</td> <td>PST</td> <td>$33073.34</td> <td>gravida@@sedpede.net</td> <td>176-3692</td> <td>8</td> <td></td> </tr> <tr> <td>167181678</td> <td>Nevada P. Mccoy</td> <td>Ap #559-1017 Dignissim. Ave</td> <td>Bonaire, Sint Eustatius and Saba</td> <td>Vigo</td> <td>Wyoming Robles</td> <td>Ultricies Ligula Nullam Inc.</td> <td>62802708699</td> <td>23.91274</td> <td>100.39545</td> <td>2018-09-17 05:24:52</td> <td>23/09/19</td> <td>2019-09-15 08:55:27</td> <td>PDT</td> <td>$18285.53</td> <td>Nulla.semper.tellus@@seddui.net</td> <td>644-8477</td> <td>8</td> <td></td> </tr> <tr> <td>255498665</td> <td>Aiko P. Benton</td> <td>4916 Pede. Av.</td> <td>Canada</td> <td>Relegem</td> <td>Dora Atkinson</td> <td>Risus Associates</td> <td>03529162299</td> <td>-56.22161</td> <td>110.98359</td> <td>2019-11-01 08:13:20</td> <td>27/09/18</td> <td>2020-03-04 03:14:35</td> <td>PST</td> <td>$60809.24</td> <td>eget@@elementumduiquis.edu</td> <td>636-9430</td> <td>4</td> <td></td> </tr> <tr> <td>371567968</td> <td>Sade P. Bartlett</td> <td>903-9013 A Avenue</td> <td>Northern Mariana Islands</td> <td>Castiglione di Sicilia</td> <td>Hamilton Merrill</td> <td>Suspendisse Institute</td> <td>27982457699</td> <td>-30.66337</td> <td>175.47112</td> <td>2018-12-16 10:03:04</td> <td>20/03/20</td> <td>2018-06-09 12:12:32</td> <td>PST</td> <td>$14895.94</td> <td>velit@@nonummyultricies.edu</td> <td>1-987-651-5664</td> <td>3</td> <td></td> </tr> <tr> <td>322994877</td> <td>Fredericka H. Landry</td> <td>P.O. Box 342, 1285 Elit. Rd.</td> <td>Albania</td> <td>Sankt Wendel</td> <td>Theodore Jordan</td> <td>Ac Associates</td> <td>22783898699</td> <td>-29.9656</td> <td>104.55726</td> <td>2018-06-08 06:59:35</td> <td>01/06/19</td> <td>2019-07-18 00:34:48</td> <td>PST</td> <td>$52855.11</td> <td>dolor.quam@@viverraDonectempus.co.uk</td> <td>615-9888</td> <td>1</td> <td></td> </tr> <tr> <td>277976412</td> <td>Indira H. Fletcher</td> <td>6264 Curae; Rd.</td> <td>India</td> <td>Genval</td> <td>Gage Church</td> <td>Molestie Dapibus Ligula LLP</td> <td>42843400299</td> <td>21.96031</td> <td>-0.31619</td> <td>2019-07-18 22:57:54</td> <td>15/12/19</td> <td>2018-09-14 04:35:23</td> <td>PDT</td> <td>$46095.22</td> <td>Nulla.eu.neque@@ac.org</td> <td>1-413-621-4698</td> <td>7</td> <td></td> </tr> <tr> <td>372757892</td> <td>Blythe X. Avery</td> <td>Ap #603-8246 Nunc Av.</td> <td>Guyana</td> <td>Whyalla</td> <td>Lee Pittman</td> <td>Convallis Erat PC</td> <td>41227267999</td> <td>-42.87923</td> <td>58.47521</td> <td>2020-03-12 08:50:50</td> <td>30/03/19</td> <td>2018-10-11 09:21:57</td> <td>PDT</td> <td>$51743.81</td> <td>tincidunt.congue@@arcu.co.uk</td> <td>533-7409</td> <td>7</td> <td></td> </tr> <tr> <td>378410142</td> <td>Armando N. Ferrell</td> <td>579-9743 In, Avenue</td> <td>Slovenia</td> <td>Dehri</td> <td>Stephanie Gallegos</td> <td>Tempor LLC</td> <td>14402742299</td> <td>58.59807</td> <td>-27.38365</td> <td>2018-06-26 06:44:44</td> <td>19/09/19</td> <td>2018-07-07 17:34:04</td> <td>PST</td> <td>$00006.09</td> <td>Nullam@@sitametdiam.com</td> <td>1-921-435-9660</td> <td>8</td> <td></td> </tr> <tr> <td>359626215</td> <td>Dorian O. Bates</td> <td>P.O. Box 917, 4670 Et Road</td> <td>Swaziland</td> <td>Dolceacqua</td> <td>Cassandra Mcclure</td> <td>Erat Nonummy Consulting</td> <td>88439344999</td> <td>-68.67631</td> <td>-114.51021</td> <td>2019-08-30 04:35:48</td> <td>27/07/19</td> <td>2018-09-30 03:39:41</td> <td>PST</td> <td>$92574.36</td> <td>elit.erat@@sedorcilobortis.org</td> <td>1-523-322-1092</td> <td>3</td> <td></td> </tr> <tr> <td>393869526</td> <td>Caleb D. Vance</td> <td>4891 Scelerisque Street</td> <td>Laos</td> <td>Devon</td> <td>Amal Massey</td> <td>Iaculis Enim Industries</td> <td>60601484499</td> <td>-28.89288</td> <td>-151.24472</td> <td>2019-07-28 15:44:18</td> <td>19/10/19</td> <td>2019-08-19 17:01:20</td> <td>PST</td> <td>$00327.19</td> <td>augue.porttitor@@nuncidenim.co.uk</td> <td>1-919-235-9223</td> <td>5</td> <td></td> </tr> <tr> <td>191576322</td> <td>Amy I. Bradley</td> <td>7609 Non, St.</td> <td>Niue</td> <td>Austin</td> <td>Brandon Douglas</td> <td>Fermentum Metus Aenean Limited</td> <td>96234657299</td> <td>-42.88492</td> <td>88.77296</td> <td>2019-08-05 13:59:19</td> <td>13/03/19</td> <td>2019-05-10 06:36:17</td> <td>PDT</td> <td>$98908.88</td> <td>elementum.sem@@eleifend.org</td> <td>1-221-812-3627</td> <td>3</td> <td></td> </tr> <tr> <td>274109173</td> <td>Wendy B. Riley</td> <td>1043 Etiam St.</td> <td>Moldova</td> <td>Lac-Serent</td> <td>Cain Kaufman</td> <td>Non Limited</td> <td>38737016799</td> <td>-89.07199</td> <td>130.00282</td> <td>2019-02-20 21:19:39</td> <td>15/09/19</td> <td>2018-07-14 17:39:56</td> <td>PDT</td> <td>$98870.17</td> <td>ac.tellus.Suspendisse@@quamelementumat.edu</td> <td>1-431-279-9222</td> <td>7</td> <td></td> </tr> <tr> <td>342230571</td> <td>Holmes K. Dean</td> <td>P.O. Box 584, 1226 Nulla Av.</td> <td>Isle of Man</td> <td>Cochrane</td> <td>Griffin Barker</td> <td>Et Tristique Incorporated</td> <td>76916715299</td> <td>58.53424</td> <td>-164.90836</td> <td>2018-12-19 17:43:52</td> <td>02/09/18</td> <td>2020-02-07 01:54:26</td> <td>PDT</td> <td>$94095.01</td> <td>enim@@Phasellus.com</td> <td>541-1278</td> <td>4</td> <td></td> </tr> <tr> <td>400751277</td> <td>Shea R. Haley</td> <td>274-7179 Conubia Street</td> <td>Serbia</td> <td>Richmond Hill</td> <td>Brent Mullen</td> <td>Aliquet Odio Inc.</td> <td>11716056699</td> <td>16.77936</td> <td>88.80543</td> <td>2019-12-24 12:38:31</td> <td>07/12/18</td> <td>2020-04-09 15:56:09</td> <td>PDT</td> <td>$31939.82</td> <td>Nullam.lobortis.quam@@turpis.net</td> <td>534-8076</td> <td>4</td> <td></td> </tr> <tr> <td>456710905</td> <td>Delilah K. Spencer</td> <td>992-9720 Commodo Road</td> <td>Togo</td> <td>NeuprŽ</td> <td>Kevin Mann</td> <td>Tristique Pharetra Quisque Corporation</td> <td>02721953099</td> <td>81.27888</td> <td>52.6698</td> <td>2018-08-29 00:13:36</td> <td>02/02/20</td> <td>2019-08-12 20:56:42</td> <td>PDT</td> <td>$73532.60</td> <td>consequat@@accumsan.edu</td> <td>446-8816</td> <td>2</td> <td></td> </tr> <tr> <td>408012252</td> <td>Colorado B. Horne</td> <td>P.O. Box 876, 286 Tortor. St.</td> <td>Saint Barthélemy</td> <td>Aix-en-Provence</td> <td>Lillith Compton</td> <td>Erat Sed Consulting</td> <td>28779013599</td> <td>24.69341</td> <td>143.42428</td> <td>2018-09-18 23:29:18</td> <td>30/01/19</td> <td>2020-01-24 01:14:13</td> <td>PST</td> <td>$99619.10</td> <td>magna.a@@Cum.ca</td> <td>1-132-237-7856</td> <td>7</td> <td></td> </tr> <tr> <td>57079681</td> <td>Kameko N. Castillo</td> <td>342-6582 Ipsum. Street</td> <td>Norfolk Island</td> <td>Maiduguri</td> <td>Georgia Whitney</td> <td>Interdum Company</td> <td>21781388199</td> <td>-70.7838</td> <td>63.30322</td> <td>2019-04-18 07:16:38</td> <td>07/11/18</td> <td>2019-09-30 20:14:40</td> <td>PDT</td> <td>$42950.54</td> <td>malesuada.vel@@ametdapibusid.org</td> <td>219-9153</td> <td>5</td> <td></td> </tr> <tr> <td>291463509</td> <td>Hedy I. Burnett</td> <td>7880 Ac Rd.</td> <td>Israel</td> <td>Muridke</td> <td>Emerald Morrow</td> <td>Cras Lorem PC</td> <td>48202005899</td> <td>67.76944</td> <td>98.63072</td> <td>2019-11-29 12:53:58</td> <td>15/05/18</td> <td>2018-06-28 01:55:13</td> <td>PDT</td> <td>$73491.65</td> <td>blandit.viverra@@Maecenasornareegestas.co.uk</td> <td>1-623-197-9498</td> <td>7</td> <td></td> </tr> <tr> <td>233746428</td> <td>Rama P. Garner</td> <td>P.O. Box 582, 9264 Scelerisque Av.</td> <td>Svalbard and Jan Mayen Islands</td> <td>Mignanego</td> <td>Ashton Vazquez</td> <td>Rutrum PC</td> <td>11815293899</td> <td>-61.68378</td> <td>-164.07959</td> <td>2020-01-03 22:49:21</td> <td>29/01/19</td> <td>2019-09-13 07:38:05</td> <td>PDT</td> <td>$96546.65</td> <td>elit.Nulla@@Loremipsum.ca</td> <td>215-2924</td> <td>3</td> <td></td> </tr> <tr> <td>212851345</td> <td>Christian G. Hooper</td> <td>P.O. Box 141, 9652 Fusce Road</td> <td>Haiti</td> <td>Montebelluna</td> <td>Hilary Justice</td> <td>Nec Tempus Scelerisque LLP</td> <td>92511588599</td> <td>-60.01603</td> <td>-90.7262</td> <td>2018-04-19 07:35:50</td> <td>22/10/19</td> <td>2019-09-14 13:45:10</td> <td>PDT</td> <td>$49560.33</td> <td>consequat.nec@@Duisacarcu.com</td> <td>1-862-649-4581</td> <td>6</td> <td></td> </tr> <tr> <td>431791277</td> <td>Isabelle B. Beach</td> <td>P.O. Box 416, 8092 Mollis. Street</td> <td>Azerbaijan</td> <td>Whitewater Region Township</td> <td>Kalia Knight</td> <td>Vel Pede Blandit Limited</td> <td>48782180399</td> <td>-83.18442</td> <td>2.56926</td> <td>2019-09-07 22:49:42</td> <td>28/05/18</td> <td>2019-09-16 01:12:12</td> <td>PDT</td> <td>$50666.20</td> <td>sit.amet@@adipiscingenim.org</td> <td>975-6200</td> <td>3</td> <td></td> </tr> <tr> <td>196830774</td> <td>Melyssa Y. Guy</td> <td>1110 Pharetra Rd.</td> <td>Nigeria</td> <td>Hard</td> <td>Brian Fischer</td> <td>Cursus Vestibulum Mauris Corporation</td> <td>67789976099</td> <td>42.12955</td> <td>-130.52365</td> <td>2019-04-16 23:40:07</td> <td>10/09/19</td> <td>2018-11-13 21:12:59</td> <td>PDT</td> <td>$88840.77</td> <td>Lorem.ipsum@@Quisquenonummy.com</td> <td>816-4009</td> <td>3</td> <td></td> </tr> <tr> <td>356045890</td> <td>Fulton W. Kline</td> <td>Ap #831-1201 Gravida Rd.</td> <td>Armenia</td> <td>Borriana</td> <td>Blake Joyce</td> <td>Et Tristique Pellentesque LLC</td> <td>06560054099</td> <td>-26.95097</td> <td>-135.27855</td> <td>2018-09-23 08:18:00</td> <td>21/03/19</td> <td>2018-05-30 15:52:33</td> <td>PDT</td> <td>$92651.56</td> <td>turpis.egestas@@mi.ca</td> <td>1-946-874-1445</td> <td>4</td> <td></td> </tr> <tr> <td>11346755K</td> <td>Henry F. Torres</td> <td>P.O. Box 151, 2738 Dolor Street</td> <td>Saint Pierre and Miquelon</td> <td>Campofelice di Fitalia</td> <td>Dane Elliott</td> <td>Rutrum Institute</td> <td>60438798999</td> <td>-80.73091</td> <td>85.75828</td> <td>2018-11-09 00:09:09</td> <td>22/01/20</td> <td>2018-06-08 06:48:11</td> <td>PDT</td> <td>$46351.80</td> <td>tellus.Aenean@@sedconsequatauctor.co.uk</td> <td>1-973-715-9723</td> <td>8</td> <td></td> </tr> <tr> <td>350649417</td> <td>Felix T. Gallegos</td> <td>4770 Adipiscing Road</td> <td>Burundi</td> <td>Redruth</td> <td>Jack Mays</td> <td>Ullamcorper Company</td> <td>01976412099</td> <td>61.98608</td> <td>-150.62073</td> <td>2018-10-04 04:14:22</td> <td>24/08/18</td> <td>2018-12-19 05:56:20</td> <td>PDT</td> <td>$22480.04</td> <td>mus.Proin.vel@@etnetuset.co.uk</td> <td>1-744-820-0736</td> <td>8</td> <td></td> </tr> <tr> <td>30779909K</td> <td>Melissa U. Mcfadden</td> <td>6899 Mollis. St.</td> <td>Palau</td> <td>Sant'Agapito</td> <td>Uma Guy</td> <td>At Pede Cras Associates</td> <td>25735286799</td> <td>33.18624</td> <td>-124.29807</td> <td>2018-10-25 07:59:24</td> <td>04/07/19</td> <td>2018-11-01 16:20:05</td> <td>PST</td> <td>$29101.24</td> <td>molestie.arcu.Sed@@vitae.ca</td> <td>1-363-821-2178</td> <td>6</td> <td></td> </tr> <tr> <td>297351664</td> <td>Dolan M. Simon</td> <td>Ap #923-3239 Tincidunt Rd.</td> <td>Argentina</td> <td>San Marcello</td> <td>Holly Decker</td> <td>Semper Rutrum Foundation</td> <td>66927043999</td> <td>81.70433</td> <td>28.52344</td> <td>2020-03-26 16:06:06</td> <td>18/09/19</td> <td>2020-02-22 07:25:06</td> <td>PDT</td> <td>$30526.50</td> <td>metus.facilisis@@etrutrumnon.ca</td> <td>1-862-334-4124</td> <td>7</td> <td></td> </tr> <tr> <td>302691711</td> <td>Pamela G. Velazquez</td> <td>9109 Ultrices Avenue</td> <td>Hong Kong</td> <td>Siliguri</td> <td>Aladdin Hensley</td> <td>Leo In Ltd</td> <td>42238471399</td> <td>74.13009</td> <td>-144.03328</td> <td>2019-02-16 19:14:42</td> <td>29/10/18</td> <td>2019-07-07 23:21:19</td> <td>PST</td> <td>$09762.36</td> <td>venenatis.vel@@rhoncusDonecest.net</td> <td>1-450-434-6560</td> <td>7</td> <td></td> </tr> <tr> <td>156635804</td> <td>Xenos F. Mejia</td> <td>329-1131 Luctus St.</td> <td>Zimbabwe</td> <td>Milford Haven</td> <td>Jameson Norton</td> <td>Posuere Vulputate Lacus Corp.</td> <td>40240466699</td> <td>-46.5055</td> <td>-135.17906</td> <td>2019-07-05 07:30:30</td> <td>05/08/19</td> <td>2019-01-09 21:32:41</td> <td>PST</td> <td>$85792.90</td> <td>amet@@tortornibh.edu</td> <td>1-771-235-5891</td> <td>1</td> <td></td> </tr> <tr> <td>197525797</td> <td>Tasha U. Holder</td> <td>666-9190 Sodales St.</td> <td>Guinea-Bissau</td> <td>Bath</td> <td>Deacon Fowler</td> <td>Nascetur Associates</td> <td>41346740999</td> <td>21.73457</td> <td>138.78628</td> <td>2018-09-06 20:18:02</td> <td>28/07/18</td> <td>2020-02-09 17:58:11</td> <td>PST</td> <td>$12108.78</td> <td>vitae@@vulputate.org</td> <td>1-886-372-2849</td> <td>6</td> <td></td> </tr> <tr> <td>263771753</td> <td>Rajah K. Daugherty</td> <td>P.O. Box 192, 7868 Dis Av.</td> <td>Cocos (Keeling) Islands</td> <td>Strijtem</td> <td>Kerry Stephens</td> <td>Tincidunt Corp.</td> <td>34332164799</td> <td>59.48021</td> <td>33.62045</td> <td>2019-05-27 15:10:27</td> <td>17/01/19</td> <td>2019-10-11 18:53:11</td> <td>PDT</td> <td>$52461.05</td> <td>cursus.et@@malesuadamalesuada.org</td> <td>424-9734</td> <td>1</td> <td></td> </tr> <tr> <td>106965641</td> <td>Michelle H. Skinner</td> <td>P.O. Box 978, 3432 Nisi Rd.</td> <td>Saint Barthélemy</td> <td>Newark</td> <td>Ferdinand Parker</td> <td>Eu Industries</td> <td>62866798899</td> <td>-25.10953</td> <td>-132.46452</td> <td>2018-05-22 19:19:38</td> <td>29/09/18</td> <td>2019-01-31 07:46:53</td> <td>PDT</td> <td>$16582.56</td> <td>Lorem@@felisadipiscingfringilla.com</td> <td>981-0922</td> <td>7</td> <td></td> </tr> <tr> <td>348176331</td> <td>Baker D. Garza</td> <td>3482 Commodo Av.</td> <td>Taiwan</td> <td>Río Negro</td> <td>Marah Lang</td> <td>Erat Corp.</td> <td>23846522099</td> <td>80.77497</td> <td>123.63235</td> <td>2020-03-17 22:44:02</td> <td>16/01/19</td> <td>2020-01-29 07:34:30</td> <td>PDT</td> <td>$77648.21</td> <td>velit@@Sed.ca</td> <td>1-629-220-5441</td> <td>7</td> <td></td> </tr> <tr> <td>290604451</td> <td>Leilani H. Kennedy</td> <td>Ap #485-8020 Quisque Av.</td> <td>Poland</td> <td>Warszawa</td> <td>Lilah Huber</td> <td>Ut Company</td> <td>43368861099</td> <td>-54.6438</td> <td>129.1365</td> <td>2018-04-21 04:24:36</td> <td>15/08/19</td> <td>2019-07-23 12:31:59</td> <td>PDT</td> <td>$27262.43</td> <td>viverra.Donec@@In.ca</td> <td>446-1788</td> <td>4</td> <td></td> </tr> <tr> <td>504288811</td> <td>Cullen C. Johns</td> <td>832-6525 Molestie Av.</td> <td>French Polynesia</td> <td>Montese</td> <td>Eleanor Hendrix</td> <td>Laoreet Posuere Enim Company</td> <td>53307858899</td> <td>-38.52022</td> <td>82.43909</td> <td>2019-06-03 09:37:39</td> <td>27/08/18</td> <td>2019-06-26 11:54:35</td> <td>PST</td> <td>$55270.92</td> <td>erat@@auctornon.net</td> <td>346-1401</td> <td>2</td> <td></td> </tr> <tr> <td>39649812K</td> <td>Britanni M. Campos</td> <td>Ap #841-4250 Amet, Av.</td> <td>Thailand</td> <td>Armadale</td> <td>Emma Dotson</td> <td>Nisi Aenean Eget Corp.</td> <td>99422696899</td> <td>58.96752</td> <td>-117.58278</td> <td>2020-01-14 18:05:02</td> <td>15/10/19</td> <td>2019-02-16 09:17:26</td> <td>PDT</td> <td>$95060.19</td> <td>vitae@@mollis.net</td> <td>856-5406</td> <td>4</td> <td></td> </tr> <tr> <td>201184517</td> <td>Victor I. Barlow</td> <td>P.O. Box 837, 9273 Massa St.</td> <td>Zimbabwe</td> <td>Paiguano</td> <td>Denise Mcfadden</td> <td>Dui Semper Company</td> <td>57591149599</td> <td>-87.43323</td> <td>133.70405</td> <td>2019-04-30 20:07:29</td> <td>22/03/20</td> <td>2020-04-08 11:57:22</td> <td>PDT</td> <td>$12600.21</td> <td>Donec.dignissim@@Curabitur.com</td> <td>654-8676</td> <td>2</td> <td></td> </tr> <tr> <td>217082536</td> <td>Nina L. Cruz</td> <td>604-3821 Nunc, Av.</td> <td>Cocos (Keeling) Islands</td> <td>Contulmo</td> <td>James Hodges</td> <td>Id Enim Curabitur Associates</td> <td>00578882199</td> <td>-18.78253</td> <td>32.04073</td> <td>2019-08-14 13:38:26</td> <td>13/10/19</td> <td>2020-01-30 14:15:52</td> <td>PST</td> <td>$68693.77</td> <td>Lorem@@ligulaAeneaneuismod.net</td> <td>741-8918</td> <td>4</td> <td></td> </tr> <tr> <td>95620175</td> <td>Donovan N. Sutton</td> <td>8559 Etiam Rd.</td> <td>Kenya</td> <td>Gresham</td> <td>Thomas Sullivan</td> <td>Sit Amet Lorem LLC</td> <td>80795428099</td> <td>-27.63251</td> <td>-147.24252</td> <td>2020-03-16 16:58:30</td> <td>06/07/19</td> <td>2018-12-25 15:25:12</td> <td>PDT</td> <td>$84085.99</td> <td>et.netus@@erat.com</td> <td>876-9862</td> <td>2</td> <td></td> </tr> <tr> <td>116265168</td> <td>Scarlett G. Floyd</td> <td>P.O. Box 856, 189 Nec, St.</td> <td>Pakistan</td> <td>Phoenix</td> <td>Mikayla Hernandez</td> <td>Tincidunt Incorporated</td> <td>52498659299</td> <td>-20.46478</td> <td>-21.85605</td> <td>2018-04-27 01:07:57</td> <td>07/12/18</td> <td>2019-09-06 11:40:44</td> <td>PDT</td> <td>$07155.39</td> <td>vulputate.posuere.vulputate@@velitdui.edu</td> <td>717-2598</td> <td>4</td> <td></td> </tr> <tr> <td>150986923</td> <td>Linus D. Wells</td> <td>9103 Ipsum St.</td> <td>Russian Federation</td> <td>Oudenaken</td> <td>Isadora Howard</td> <td>Sem Nulla Institute</td> <td>71572161799</td> <td>-85.00485</td> <td>23.60684</td> <td>2019-01-08 11:11:32</td> <td>14/09/18</td> <td>2019-06-22 16:22:00</td> <td>PST</td> <td>$48920.57</td> <td>blandit.enim@@tristique.co.uk</td> <td>1-667-983-4018</td> <td>4</td> <td></td> </tr> <tr> <td>496997859</td> <td>Paula D. Navarro</td> <td>Ap #882-360 Mus. Avenue</td> <td>Guinea-Bissau</td> <td>Salihli</td> <td>Daquan Weaver</td> <td>Dignissim Lacus Aliquam Corporation</td> <td>15966325399</td> <td>85.43281</td> <td>-27.56574</td> <td>2020-01-09 22:41:08</td> <td>15/09/19</td> <td>2019-10-07 07:57:50</td> <td>PST</td> <td>$53235.64</td> <td>tincidunt.aliquam.arcu@@inconsectetueripsum.org</td> <td>1-829-166-6033</td> <td>7</td> <td></td> </tr> <tr> <td>492337595</td> <td>Malcolm T. Baxter</td> <td>568-5550 Cursus Rd.</td> <td>French Southern Territories</td> <td>Newport</td> <td>Susan Russo</td> <td>Vestibulum Industries</td> <td>92231061699</td> <td>67.64055</td> <td>-98.58401</td> <td>2019-04-07 02:56:54</td> <td>17/10/19</td> <td>2019-11-10 06:16:33</td> <td>PDT</td> <td>$57094.07</td> <td>placerat@@erateget.ca</td> <td>1-709-877-9930</td> <td>3</td> <td></td> </tr> <tr> <td>362241030</td> <td>Kai Y. Mueller</td> <td>P.O. Box 244, 6602 Duis Street</td> <td>Martinique</td> <td>Fayetteville</td> <td>Nell Nelson</td> <td>Torquent Per Consulting</td> <td>37548800899</td> <td>-86.35769</td> <td>64.80714</td> <td>2020-03-28 03:36:50</td> <td>31/10/19</td> <td>2018-05-12 17:54:37</td> <td>PST</td> <td>$78636.66</td> <td>dignissim.lacus.Aliquam@@utpharetra.com</td> <td>610-9694</td> <td>7</td> <td></td> </tr> <tr> <td>244637906</td> <td>Alice D. Holloway</td> <td>177-8463 Urna. Rd.</td> <td>Guam</td> <td>Tramutola</td> <td>Blake Holt</td> <td>Erat Industries</td> <td>16787961299</td> <td>-47.37492</td> <td>-129.1421</td> <td>2018-12-13 18:28:08</td> <td>28/09/19</td> <td>2018-07-27 08:03:43</td> <td>PST</td> <td>$98904.29</td> <td>Curae.Donec.tincidunt@@variuseteuismod.ca</td> <td>788-7780</td> <td>2</td> <td></td> </tr> <tr> <td>268052593</td> <td>Desirae U. Cameron</td> <td>642-5058 Nam St.</td> <td>Belgium</td> <td>GŽrouville</td> <td>Hayden Acosta</td> <td>Ornare Incorporated</td> <td>84373060799</td> <td>-81.46518</td> <td>-38.09689</td> <td>2018-08-14 02:36:06</td> <td>18/07/18</td> <td>2019-01-12 15:31:04</td> <td>PDT</td> <td>$58216.70</td> <td>Donec.egestas.Duis@@eu.co.uk</td> <td>1-548-329-0615</td> <td>7</td> <td></td> </tr> <tr> <td>23298905K</td> <td>Abdul V. Howard</td> <td>742 Dolor Avenue</td> <td>Morocco</td> <td>Itanagar</td> <td>Beatrice Maldonado</td> <td>Lobortis LLC</td> <td>13895800199</td> <td>10.65608</td> <td>58.87606</td> <td>2019-08-15 11:55:39</td> <td>19/12/18</td> <td>2019-03-22 19:07:37</td> <td>PDT</td> <td>$58997.02</td> <td>sed.pede@@egestashendrerit.ca</td> <td>1-932-948-6613</td> <td>8</td> <td></td> </tr> <tr> <td>189845170</td> <td>Zachery P. Calderon</td> <td>P.O. Box 138, 8385 Metus Av.</td> <td>Tajikistan</td> <td>Grand-Hallet</td> <td>Zephania Strickland</td> <td>Mauris Limited</td> <td>91974798799</td> <td>67.79569</td> <td>-120.92694</td> <td>2019-05-25 11:20:14</td> <td>17/02/19</td> <td>2019-01-12 08:41:41</td> <td>PDT</td> <td>$21806.93</td> <td>amet.ornare.lectus@@ante.edu</td> <td>958-6027</td> <td>8</td> <td></td> </tr> <tr> <td>162386190</td> <td>Kenyon H. Dunn</td> <td>Ap #739-8095 Amet, Road</td> <td>Venezuela</td> <td>Eisden</td> <td>Kylynn Britt</td> <td>Ut Nulla Ltd</td> <td>20286466599</td> <td>54.02909</td> <td>-108.08149</td> <td>2019-01-13 01:11:42</td> <td>12/07/19</td> <td>2019-03-28 11:44:18</td> <td>PST</td> <td>$81447.86</td> <td>nunc.nulla@@id.co.uk</td> <td>935-5653</td> <td>4</td> <td></td> </tr> <tr> <td>396568225</td> <td>Shay X. Bond</td> <td>1463 Cras St.</td> <td>Botswana</td> <td>Saarlouis</td> <td>Dakota Maldonado</td> <td>Rhoncus Company</td> <td>84815855899</td> <td>12.03054</td> <td>-37.46236</td> <td>2019-05-12 13:49:29</td> <td>04/07/18</td> <td>2018-08-15 09:50:20</td> <td>PST</td> <td>$91929.76</td> <td>pede@@Maurisvel.edu</td> <td>980-1327</td> <td>2</td> <td></td> </tr> <tr> <td>197834013</td> <td>Harlan T. Barr</td> <td>Ap #924-6404 Neque Rd.</td> <td>Iraq</td> <td>Kolkata</td> <td>Valentine Duran</td> <td>Semper Foundation</td> <td>34938043999</td> <td>56.3716</td> <td>-131.82047</td> <td>2018-08-05 14:15:57</td> <td>23/03/20</td> <td>2018-10-11 20:09:56</td> <td>PDT</td> <td>$48412.35</td> <td>Aliquam.auctor.velit@@pedeac.co.uk</td> <td>543-9056</td> <td>7</td> <td></td> </tr> <tr> <td>169854424</td> <td>Eleanor T. Owens</td> <td>P.O. Box 651, 1956 Tortor Av.</td> <td>Malaysia</td> <td>Campomorone</td> <td>Reece Contreras</td> <td>Orci Donec Nibh Industries</td> <td>85688141099</td> <td>-41.53144</td> <td>157.53845</td> <td>2019-02-14 05:03:54</td> <td>24/03/20</td> <td>2019-11-13 07:28:22</td> <td>PDT</td> <td>$46136.81</td> <td>eu.odio.Phasellus@@Namtempor.com</td> <td>1-272-761-8005</td> <td>3</td> <td></td> </tr> <tr> <td>506446694</td> <td>Quentin U. Atkins</td> <td>P.O. Box 243, 7126 Lacinia. Rd.</td> <td>India</td> <td>Zeist</td> <td>Malik Bartlett</td> <td>Luctus Company</td> <td>27368620499</td> <td>-76.99374</td> <td>30.11273</td> <td>2019-10-21 19:05:14</td> <td>09/11/18</td> <td>2018-12-19 10:38:59</td> <td>PST</td> <td>$13611.13</td> <td>per.inceptos@@eleifendnunc.net</td> <td>1-906-639-6116</td> <td>8</td> <td></td> </tr> <tr> <td>430229516</td> <td>Leilani C. Clayton</td> <td>Ap #973-2701 Urna. Ave</td> <td>Saint Kitts and Nevis</td> <td>Recklinghausen</td> <td>George Rhodes</td> <td>Nascetur Ridiculus Mus Associates</td> <td>39908301199</td> <td>40.4669</td> <td>-147.11366</td> <td>2018-07-11 16:44:14</td> <td>14/01/19</td> <td>2019-09-20 11:55:00</td> <td>PST</td> <td>$46316.60</td> <td>accumsan@@Integerid.com</td> <td>1-818-141-9416</td> <td>1</td> <td></td> </tr> <tr> <td>456183557</td> <td>Daniel C. Callahan</td> <td>1393 Eleifend, St.</td> <td>Equatorial Guinea</td> <td>Zamość</td> <td>Abigail Glass</td> <td>Arcu Eu Consulting</td> <td>53594464399</td> <td>-30.23054</td> <td>149.10508</td> <td>2019-10-31 04:54:26</td> <td>31/12/19</td> <td>2018-11-11 07:21:21</td> <td>PDT</td> <td>$79838.04</td> <td>eget@@est.ca</td> <td>1-481-364-8674</td> <td>7</td> <td></td> </tr> <tr> <td>322543123</td> <td>Quynn N. Bridges</td> <td>Ap #521-2543 Adipiscing St.</td> <td>Netherlands</td> <td>Rocca San Felice</td> <td>Celeste Roy</td> <td>Iaculis Lacus Pede Company</td> <td>41719070899</td> <td>68.67888</td> <td>-74.04999</td> <td>2018-07-27 03:00:18</td> <td>10/02/20</td> <td>2019-07-10 23:45:34</td> <td>PDT</td> <td>$24960.97</td> <td>sed@@massaQuisqueporttitor.co.uk</td> <td>1-622-378-0763</td> <td>2</td> <td></td> </tr> <tr> <td>173158629</td> <td>Dale Q. Hurst</td> <td>P.O. Box 169, 4784 Quis Av.</td> <td>Germany</td> <td>Golspie</td> <td>Lester Dixon</td> <td>Est Mauris Corporation</td> <td>14718185099</td> <td>-11.00683</td> <td>15.52299</td> <td>2019-04-20 07:28:31</td> <td>13/08/18</td> <td>2019-08-05 07:55:38</td> <td>PDT</td> <td>$67839.71</td> <td>rutrum@@quamPellentesque.co.uk</td> <td>1-818-551-0019</td> <td>8</td> <td></td> </tr> <tr> <td>309440242</td> <td>Cameron H. Hopper</td> <td>8862 Feugiat Street</td> <td>Sudan</td> <td>Dehri</td> <td>Nigel Bishop</td> <td>Donec Tincidunt Donec Incorporated</td> <td>47472714199</td> <td>20.55127</td> <td>161.71389</td> <td>2018-12-24 00:43:22</td> <td>06/03/19</td> <td>2020-02-10 05:01:43</td> <td>PST</td> <td>$88963.52</td> <td>Suspendisse@@rhoncusidmollis.com</td> <td>916-1391</td> <td>5</td> <td></td> </tr> <tr> <td>268602054</td> <td>Keiko X. Boone</td> <td>P.O. Box 375, 8461 Elit, Road</td> <td>Algeria</td> <td>Langenburg</td> <td>Tatyana Mcdowell</td> <td>Ut Mi Incorporated</td> <td>48332450299</td> <td>-89.57767</td> <td>165.03676</td> <td>2019-01-06 20:50:32</td> <td>23/06/18</td> <td>2018-10-04 09:36:04</td> <td>PDT</td> <td>$94003.71</td> <td>sociis@@leo.org</td> <td>1-481-947-2083</td> <td>5</td> <td></td> </tr> <tr> <td>441605153</td> <td>Boris A. Mccoy</td> <td>P.O. Box 648, 7647 A Avenue</td> <td>Bolivia</td> <td>East Gwillimbury</td> <td>Patricia Hoffman</td> <td>Lobortis Quis Pede Foundation</td> <td>26794376499</td> <td>64.54821</td> <td>-136.91975</td> <td>2019-08-17 13:21:51</td> <td>28/04/19</td> <td>2019-06-09 17:39:05</td> <td>PST</td> <td>$88189.21</td> <td>dui.lectus@@massaQuisqueporttitor.co.uk</td> <td>1-235-205-2996</td> <td>3</td> <td></td> </tr> <tr> <td>168445156</td> <td>Plato H. Dickerson</td> <td>6938 Volutpat. Ave</td> <td>Philippines</td> <td>Täby</td> <td>Jayme Hamilton</td> <td>Nec Cursus A PC</td> <td>25275627899</td> <td>78.49747</td> <td>-39.54536</td> <td>2020-02-05 07:40:16</td> <td>24/09/19</td> <td>2019-09-09 00:29:58</td> <td>PST</td> <td>$11099.41</td> <td>Nulla.tincidunt@@eleifend.co.uk</td> <td>157-9201</td> <td>6</td> <td></td> </tr> </tbody> <tfoot> <tr> <th>OrderID</th> <th>Recipient</th> <th>Shipping.Address</th> <th>Shipping.Country</th> <th>Shipping.City</th> <th>Agent</th> <th>Company</th> <th>OrganizationID</th> <th>Latitude</th> <th>Longitude</th> <th>Shipping.Date</th> <th>Delivery.Date</th> <th>Payment.Date</th> <th>Timezone</th> <th>Payment</th> <th>Email</th> <th>Phone</th> <th>Status</th> <th>Admin Controls</th> </tr> </tfoot> </table> </div> </div> </div> </div> </div> @section ScriptsBlock { <script src="~/js/datagrid/datatables/datatables.bundle.js"></script> <script> $(document).ready( function () { // initialize datatable $('#dt-basic-example').dataTable({ responsive: true, columnDefs: [ { targets: -1, title: 'Admin Controls', orderable: false, render: function(data, type, full, meta) { /* -- ES6 -- convert using https://babeljs.io online transpiler return ` <div class='d-flex mt-2'> <a href='javascript:void(0);' class='btn btn-sm btn-outline-danger mr-2' title='Delete Record'> <i class="@(Settings.Theme.IconPrefix) fa-times"></i> Delete Record </a> <a href='javascript:void(0);' class='btn btn-sm btn-outline-primary mr-2' title='Edit'> <i class="@(Settings.Theme.IconPrefix) fa-edit"></i> Edit </a> <div class='dropdown d-inline-block'> <a href='#'' class='btn btn-sm btn-outline-primary mr-2' data-toggle='dropdown' aria-expanded='true' title='More options'> <i class="@(Settings.Theme.IconPrefix) fa-plus"></i> </a> <div class='dropdown-menu'> <a class='dropdown-item' href='javascript:void(0);'>Change Status</a> <a class='dropdown-item' href='javascript:void(0);'>Generate Report</a> </div> </div> </div>`; ES5 example below: */ return "\n\t\t\t\t\t\t<div class='d-flex mt-2'>\n\t\t\t\t\t\t\t<a href='javascript:void(0);' class='btn btn-sm btn-outline-danger mr-2' title='Delete Record'><i class=\"@(Settings.Theme.IconPrefix) fa-times\"></i> Delete Record</a>\n\t\t\t\t\t\t\t<a href='javascript:void(0);' class='btn btn-sm btn-outline-primary mr-2' title='Edit'><i class=\"@(Settings.Theme.IconPrefix) fa-edit\"></i> Edit</a>\n\t\t\t\t\t\t\t<div class='dropdown d-inline-block'>\n\t\t\t\t\t\t\t\t<a href='#'' class='btn btn-sm btn-outline-primary mr-2' data-toggle='dropdown' aria-expanded='true' title='More options'><i class=\"@(Settings.Theme.IconPrefix) fa-plus\"></i></a>\n\t\t\t\t\t\t\t\t<div class='dropdown-menu'>\n\t\t\t\t\t\t\t\t\t<a class='dropdown-item' href='javascript:void(0);'>Change Status</a>\n\t\t\t\t\t\t\t\t\t<a class='dropdown-item' href='javascript:void(0);'>Generate Report</a>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>"; }, }, { targets: 17, /* The `data` parameter refers to the data for the cell (defined by the `data` option, which defaults to the column being worked with, in this case `data: 16`.*/ render: function(data, type, full, meta) { var badge = { 1: {'title': 'Pending', 'class': 'badge-warning'}, 2: {'title': 'Delivered', 'class': 'badge-success'}, 3: {'title': 'Canceled', 'class': 'badge-secondary'}, 4: {'title': 'Attempt #1', 'class': 'bg-danger-100 text-white'}, 5: {'title': 'Attempt #2', 'class': 'bg-danger-300 text-white'}, 6: {'title': 'Failed', 'class': 'badge-danger'}, 7: {'title': 'Attention!', 'class': 'badge-primary'}, 8: {'title': 'In Progress', 'class': 'badge-success'}, }; if (typeof badge[data] === 'undefined') { return data; } return '<span class="badge ' + badge[data].class + ' badge-pill">' + badge[data].title + '</span>'; }, } ], }); }); </script> }
the_stack
@model IEnumerable<WebApp.Models.BaseCode> @{ ViewBag.Title = "BaseCode"; } <!-- MAIN CONTENT --> <div id="content"> <!-- quick navigation bar --> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-table fa-fw "></i> 路径 <span> > BaseCode </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> </div> </div> <!-- end quick navigation bar --> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-table"></i> </span> <h2>BaseCode</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div class="alert alert-warning no-margin fade in"> <button class="close" data-dismiss="alert"> × </button> <i class="fa-fw fa fa-info"></i> A combined table effect with all classes mentioned above added to </div> <!--begin datagrid-content --> <div class="table-responsive"> <table id="basecodes_datagrid" class="easyui-datagrid" style="width:auto;height:auto" data-options=" rownumbers:true, checkOnSelect:true, selectOnCheck:true, idField:'Id', sortName:'Id', sortOrder:'desc', remoteFilter: true, singleSelect: true, toolbar: '#basecodes_toolbar', url: '/BaseCodes/GetData', method: 'get', onClickCell: onClickCell, pagination: true, striped:true "> <thead> <tr> @*<th data-options="field:'ck',checkbox:true"></th>*@ <th data-options="field:'_operate1',width:100 ,sortable:false,resizable:true,formatter:showdetailsformatter ">操作</th> @*<th data-options="field:'Id',width:80 ,sortable:true,resizable:true ">@Html.DisplayNameFor(model => model.Id)</th>*@ <th data-options="field:'CodeType' ,width:140,editor:{type:'textbox',options:{prompt:'代码名称' ,required:true ,validType:'length[0,20]' } } ,sortable:true,resizable:true ">@Html.DisplayNameFor(model => model.CodeType)</th> <th data-options="field:'Description' ,width:140,editor:{type:'textbox',options:{prompt:'描述' ,required:true ,validType:'length[0,50]' } } ,sortable:true,resizable:true ">@Html.DisplayNameFor(model => model.Description)</th> </tr> </thead> </table> <div id="basecodes_toolbar" style="height:auto"> <!-- 权限功能点控制 --> @*@if (Html.IsAuthorize("Create")) { <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-plus',plain:true" onclick="append()">新增</a> } @if (Html.IsAuthorize("Delete")) { <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-trash-o',plain:true" onclick="removeit()">删除</a> } @if (Html.IsAuthorize("Edit")) { <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-floppy-o',plain:true" onclick="accept()">保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-undo',plain:true" onclick="reject()">取消</a> } <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-refresh',plain:true" onclick="reload()">刷新</a> @if (Html.IsAuthorize("Import")) { <a href="javascript:void(0)" class="easyui-menubutton" data-options="menu:'#importmenu',iconCls:'fa fa-upload' " onclick="importexcel()">导入数据</a> <div id="importmenu" style="width:150px;"> <div data-options="iconCls:'fa fa-file-excel-o'" onclick="importexcel()">导入数据</div> <div data-options="iconCls:'fa fa-cloud-download '" onclick="downloadtemplate()" >下载用于导入的模板</div> </div> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-file-excel-o',plain:true" onclick="exportexcel()">导出至Excel</a> }*@ <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-plus',plain:true" onclick="append()">新增</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-trash-o',plain:true" onclick="removeit()">删除</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-floppy-o',plain:true" onclick="accept()">保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-undo',plain:true" onclick="reject()">取消</a> <a href="javascript:void(0)" class="easyui-menubutton" data-options="menu:'#importmenu',iconCls:'fa fa-upload' " onclick="importexcel()">导入数据</a> <div id="importmenu" style="width:150px;"> <div data-options="iconCls:'fa fa-file-excel-o'" onclick="importexcel()">导入数据</div> <div data-options="iconCls:'fa fa-cloud-download '" onclick="downloadtemplate()" >下载用于导入的模板</div> </div> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-file-excel-o',plain:true" onclick="exportexcel()">导出至Excel</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'fa fa-refresh',plain:true" onclick="reload()">刷新</a> </div> </div> <!--end datagrid-content --> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> </section> <!-- end widget grid --> <!-- file upload partial view --> @Html.Partial("_ImportWindow",new ViewDataDictionary { { "EntityName","BaseCode" }}) <!-- end file upload partial view --> </div> <!-- END MAIN CONTENT --> @section Scripts { <script type="text/javascript"> var entityname = "BaseCode"; //下载Excel导入模板 function downloadtemplate() { //TODO: 修改下载模板的路径 var url = "/ExcelTemplate/BaseCode.xlsx"; $.fileDownload(url) .fail(function () { $.messager.alert("错误","没有找到模板文件! {" + url + "}"); }); } //打开Excel上传导入 function importexcel() { $("#importwindow").window("open"); } //执行Excel到处下载 function exportexcel() { var filterRules = JSON.stringify($dg.datagrid("options").filterRules); //console.log(filterRules); $.messager.progress({ title: "正在执行导出!" }); var formData = new FormData(); formData.append("filterRules", filterRules); formData.append("sort", "Id"); formData.append("order", "asc"); $.postDownload("/BaseCodes/ExportExcel", formData, function (fileName) { $.messager.progress("close"); console.log(fileName); }) } //datagrid 增删改查操作 var $dg = $("#basecodes_datagrid"); var editIndex = undefined; function reload() { if (endEditing()) { $dg.datagrid("reload"); } } function endEditing() { if (editIndex == undefined) { return true } if ($dg.datagrid("validateRow", editIndex)) { $dg.datagrid("endEdit", editIndex); editIndex = undefined; return true; } else { return false; } } function onClickCell(index, field) { var _operates = ["_operate1", "_operate2", "_operate3", "ck"] if ($.inArray(field, _operates) >= 0) { return; } if (editIndex != index) { if (endEditing()) { $dg.datagrid("selectRow", index) .datagrid("beginEdit", index); var ed = $dg.datagrid("getEditor", { index: index, field: field }); if (ed) { ($(ed.target).data("textbox") ? $(ed.target).textbox("textbox") : $(ed.target)).focus(); } editIndex = index; } else { $dg.datagrid("selectRow", editIndex); } } } function append() { if (endEditing()) { //$dg.datagrid("appendRow", { Status: 0 }); //editIndex = $dg.datagrid("getRows").length - 1; $dg.datagrid("insertRow", { index: 0, row: { Status: 0 } }); editIndex = 0 ; $dg.datagrid("selectRow", editIndex) .datagrid("beginEdit", editIndex); } } function removeit() { if (editIndex == undefined) { return } $dg.datagrid("cancelEdit", editIndex) .datagrid("deleteRow", editIndex); editIndex = undefined; } function accept() { if (endEditing()) { if ($dg.datagrid("getChanges").length) { var inserted = $dg.datagrid("getChanges", "inserted"); var deleted = $dg.datagrid("getChanges", "deleted"); var updated = $dg.datagrid("getChanges", "updated"); var effectRow = new Object(); if (inserted.length) { effectRow.inserted = inserted; } if (deleted.length) { effectRow.deleted = deleted; } if (updated.length) { effectRow.updated = updated; } //console.log(JSON.stringify(effectRow)); $.post("/BaseCodes/SaveData", effectRow, function (response) { //console.log(response); if (response.success) { $.messager.alert("提示", "提交成功!"); $dg.datagrid("acceptChanges"); $dg.datagrid("reload"); } }, "json").fail(function (response) { //console.log(response); $.messager.alert("错误", "提交错误了!","error"); //$dg.datagrid("reload"); }); } //$dg.datagrid("acceptChanges"); } } function reject() { $dg.datagrid("rejectChanges"); editIndex = undefined; } function getChanges() { var rows = $dg.datagrid("getChanges"); alert(rows.length + " rows are changed!"); } //datagrid 开启筛选功能 $(function () { $dg.datagrid("enableFilter",[ { field: "Id", type: "numberbox", op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, ]); }) //----------------------------------------------------- //datagrid onSelect //----------------------------------------------------- function showdetailsformatter(value, row, index) { return '<a onclick="showDetailsWindow(' + row.Id + ')" class="easyui-linkbutton" href="javascript:void(0)">查看明细</a>'; } //弹出明细信息 function showDetailsWindow(id) { //console.log(index, row); } </script> <script src="~/Scripts/jquery.filerupload.js"></script> }
the_stack
@model Sheng.WeixinConstruction.Client.Shell.Models.LotteryViewModel @{ ViewBag.SubTitle = "活动"; Layout = "~/Views/Shared/_LayoutBlank.cshtml"; } <style type="text/css"> .campaignName { font-size: 0.14rem; font-weight: bold; } .campaignDescription { font-size: 0.13rem; color: #666; } #divMemberInfo { font-size: 0.14rem; line-height: 0.14rem; text-align: center; margin-top: 0.05rem; } #divShareMask { position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; width: 100%; height: 100%; background-color: black; text-align: right; filter: alpha(opacity=80); -moz-opacity: 0.8; -khtml-opacity: 0.8; opacity: 0.8; } .divOngoingPeriod { margin-top: 0.1rem; height: 0.35rem; line-height: 0.35rem; text-align: center; font-size: 0.16rem; font-weight: bold; color: white; } .divEndPeriod { margin-top: 0.1rem; border: 1px solid #AAAAAA; background-color: #EEEEEE; height: 0.35rem; line-height: 0.35rem; text-align: center; font-size: 0.16rem; font-weight: bold; color: #000000; } .divPeriodTitle { height: 0.35rem; line-height: 0.35rem; text-align: center; font-size: 0.16rem; font-weight: bold; color: #FFFFFF; } .divLogButton { border: 1px solid #FF4D4D; background-color: #FEEAE2; height: 0.5rem; line-height: 0.5rem; text-align: center; font-size: 0.16rem; font-weight: bold; color: #FF4C4C; } </style> <script> //当前页 var _ongoingCurrentPage = 1; var _ongoingTotalPage = 1; //当前页 var _endedCurrentPage = 1; var _endedTotalPage = 1; var _campaignId = getQueryString("campaignId"); $(document).ready(function () { $(document).scroll(function () { $("#divShareMask").css("top", document.body.scrollTop); }); var jsApiConfigStr = "@Newtonsoft.Json.JsonConvert.SerializeObject(Model.JsApiConfig)"; jsApiConfigStr = jsApiConfigStr.replace(new RegExp("&quot;", "gm"), "\""); jsApiConfigStr = jsApiConfigStr.replace(new RegExp("\r\n", "gm"), ""); jsApiConfigStr = jsApiConfigStr.replace(new RegExp("\n", "gm"), ""); var jsApiConfig = eval('(' + jsApiConfigStr + ')'); wx.config(jsApiConfig); loadOngoingPeriod(); loadEndedPeriod(); }); wx.ready(function () { wx.onMenuShareTimeline({ title: '@Model.Campaign.ShareTimelineTitle', // 分享标题 link: '@Request.Url.ToString()', // 分享链接 imgUrl: '@Model.Campaign.ShareImageUrl', // 分享图标 success: function () { shareSuccess("ShareTimeline"); }, cancel: function () { // 用户取消分享后执行的回调函数 } }); wx.onMenuShareAppMessage({ title: '@Model.Campaign.ShareAppMessageTitle', // 分享标题 desc: '@Model.Campaign.ShareAppMessageDescription', // 分享描述 link: '@Request.Url.ToString()', // 分享链接 imgUrl: '@Model.Campaign.ShareImageUrl', // 分享图标 type: 'link', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: function () { shareSuccess("ShareAppMessage"); }, cancel: function () { // 用户取消分享后执行的回调函数 } }); }); wx.error(function (res) { alert("error:" + res); }); function shareSuccess(type) { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/" + type + "/@ViewBag.Domain.Id?campaignId=" + _campaignId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { // alert(data); layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; if (resultObj.Point == 0) return; var msg = ""; if (resultObj.Point > 0) { msg += "获得积分:" + resultObj.Point; } if (msg != "") { layerAlertBtn(msg); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showCampaignDescription() { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/GetCampaignDescription/@ViewBag.Domain.Id?id=" + _campaignId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; var gettpl = document.getElementById('campaignDescription').innerHTML; laytpl(gettpl).render(resultObj, function (html) { var pageii = layer.open({ type: 1, content: html, shadeClose: false, style: 'position:fixed; left:0.1rem; top:0.1rem;right:0.1rem; bottom:0.1rem; border:none;' }); }); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function loadOngoingPeriod(targetPage) { if (targetPage > _ongoingTotalPage) return; var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); var args = new Object(); args.Page = targetPage || 1; args.PageSize = 10; args.CampaignId = _campaignId; $.ajax({ url: "/Api/Campaign/GetLotteryOngoingPeriodList/@ViewBag.Domain.Id", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; //alert(JSON.stringify(resultObj)); var gettpl = document.getElementById('ongoingPeriodItemTemplate').innerHTML; laytpl(gettpl).render(resultObj.ItemList, function (html) { document.getElementById('ongoingPeriodContainer').innerHTML += html; }); _ongoingCurrentPage = resultObj.Page; _ongoingTotalPage = resultObj.TotalPage; if (_ongoingCurrentPage >= _ongoingTotalPage) { // $("#divOngoingPagingContainer").html("没有更多了"); $("#divOngoingPagingContainer").hide(); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function loadEndedPeriod(targetPage) { if (targetPage > _endedTotalPage) return; var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); var args = new Object(); args.Page = targetPage || 1; args.PageSize = 10; args.CampaignId = _campaignId; $.ajax({ url: "/Api/Campaign/GetLotteryEndedPeriodList/@ViewBag.Domain.Id", type: "POST", dataType: "json", data: JSON.stringify(args), success: function (data, status, jqXHR) { // alert(data); layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; //alert(JSON.stringify(resultObj)); var gettpl = document.getElementById('endedPeriodItemTemplate').innerHTML; laytpl(gettpl).render(resultObj.ItemList, function (html) { document.getElementById('endedPeriodContainer').innerHTML += html; }); _endedCurrentPage = resultObj.Page; _endedTotalPage = resultObj.TotalPage; if (_endedCurrentPage >= _endedTotalPage) { // $("#divEndedPagingContainer").html("没有更多了"); $("#divEndedPagingContainer").hide(); } } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showOngoingDetail(periodId) { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/GetLotteryPeriod/@ViewBag.Domain.Id?id=" + periodId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; //alert(JSON.stringify(resultObj)); var gettpl = document.getElementById('ongoingDetailTemplate').innerHTML; laytpl(gettpl).render(resultObj, function (html) { var pageii = layer.open({ type: 1, content: html, shadeClose: false, style: 'border:none;' }); }); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showEndedDetail(periodId) { var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/GetLotteryWinnerList/@ViewBag.Domain.Id?periodId=" + periodId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var resultObj = data.Data; //alert(JSON.stringify(resultObj)); var gettpl = document.getElementById('endedDetailTemplate').innerHTML; laytpl(gettpl).render(resultObj, function (html) { var pageii = layer.open({ type: 1, content: html, shadeClose: false, style: 'position:fixed; left:0.1rem; top:0.1rem;right:0.1rem; bottom:0.1rem; border:none;' }); }); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function lotterySign(periodId) { @if (Model.Attention == false) { <text> layerAlertBtn("请先关注我们才可以参与哦~", function () { window.location.href = '@ViewBag.DomainContext.GuideSubscribeUrl'; }); return; </text> } var loadLayerIndex = layer.open({ type: 2, shadeClose: false, content: '请稍候...' }); $.ajax({ url: "/Api/Campaign/LotterySign/@ViewBag.Domain.Id?campaignId=" + _campaignId + "&periodId=" + periodId, type: "POST", dataType: "json", success: function (data, status, jqXHR) { layer.close(loadLayerIndex); if (data.Success) { var msg = ""; switch (data.Data.Result) { case 0: msg = "报名成功!"; layer.closeAll(); break; case 1: msg = "报名失败。"; break; case 2: msg = "活动或周期不在进行中。"; break; case 3: msg = "已经报过名了。"; break; case 4: msg = "活动或者周期不存在"; break; case 5: msg = "您积分不足了哦~"; break; case 6: msg = "本期已达最大允许参与人数~"; break; default: msg = "未知错误"; break; } layerAlert(msg); } else { layerAlert(data.Message); } }, error: function (xmlHttpRequest) { layer.close(loadLayerIndex); //alert("Error: " + xmlHttpRequest.status); } }); } function showShareMask() { $("#divShareMask").css("top", document.body.scrollTop); $("#divShareMask").show(); } function hideShareMask() { $("#divShareMask").hide(); } //0、46、64、96、132数值可选,0代表640*640正方形头像 function fitHeadImage(url, size) { if (url == undefined || url == null || url == "") return ""; url = url.substr(0, url.length - 1); url = url + size; return url; } function guideSubscribe() { window.location.href = '@ViewBag.DomainContext.GuideSubscribeUrl'; } </script> <script type="text/html" id="campaignDescription"> <div style="position: fixed; top: 0.1rem; left: 0.1rem; right: 0.1rem; bottom: 0.45rem; overflow: auto;"> {{ d }} </div> <div style="position: fixed; bottom: 0.1rem; left: 0.1rem; right: 0.1rem;"> <div class="divRectangle_Gray" style="margin-top: 0.1rem; " onclick="layer.closeAll()"> 关 闭 </div> </div> </script> <script type="text/html" id="ongoingDetailTemplate"> <div class="divPeriodTitle defaultBgColorLight"> {{d.Period.Name}} </div> <div style="background-color: white; margin-top: 0.2rem; margin-bottom: 0.15rem; padding-left: 0.15rem; padding-right: 0.15rem;"> @if (Model.Attention) { <text> {{# if(d.Log != undefined && d.Log != null){ }} <div> 您已经报过名了!<br /> 请留意抽奖结果~ </div> {{# } else{}} <div> 赶紧报名参加吧! </div> {{# } }} </text> } else { <div> 赶紧关注我们报名参加吧! </div> } <div style="margin-top: 0.1rem;"> 截止时间:{{ d.Period.EndTime }} </div> @if (Model.Lottery.Point > 0) { <div style="margin-top: 0.1rem;"> 所需积分:@Model.Lottery.Point </div> } <div style="margin-top: 0.2rem;"> @if (Model.Attention) { <text> {{# if(d.Log == undefined || d.Log == null){ }} <div class="divRectangle" style="margin-left: 0.2rem; margin-right: 0.2rem" onclick="lotterySign('{{d.Period.Id}}')"> 报 名 </div> {{# } }} </text> } else { <div class="divLogButton" style="margin-left: 0.2rem; margin-right: 0.2rem" onclick="guideSubscribe()"> 关注我们 </div> } <div class="divRectangle_Gray" style="margin-top: 0.15rem; margin-left: 0.2rem; margin-right: 0.2rem; " onclick="layer.closeAll()"> 再看看 </div> </div> </div> </script> <script type="text/html" id="endedDetailTemplate"> <div class="divPeriodTitle defaultBgColorLight"> {{d.Period.Name}} </div> <div style="position: fixed; top: 0.5rem; left: 0.1rem; right: 0.1rem; bottom: 0.45rem; overflow: auto;"> {{# if(d.Period.Drawn == false){ }} <div style="color: black; font-weight: bold"> 马上开奖,请稍候... </div> {{# } else{}} @if (Model.Attention) { <text> {{# if(d.IsWinner){ }} <div style="color: red; font-weight: bold"> 恭喜,您被抽中! </div> {{# } else{}} <div style="color: black; font-weight: bold"> 这次的名单中似乎没有你... </div> {{# } }} </text> } <div style="margin-top: 0.15rem"> 中奖名单: </div> <div style="margin-top: 0.15rem; margin-left: 0.2rem"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> {{# for(var i = 0, len = d.WinnerList.length; i < len; i=i+1){ }} {{# var headimg = fitHeadImage(d.WinnerList[i].Headimgurl,46) }} <tr style="height: 0.5rem;"> <td style="width: 0.5rem"> <img src="{{headimg}}" style="width: 0.4rem;"></td> <td>{{d.WinnerList[i].NickName}}</td> </tr> {{# } }} </table> </div> {{# } }} </div> <div style="position: fixed; bottom: 0.1rem; left: 0.1rem; right: 0.1rem;"> <div class="divRectangle_Gray" style="margin-top: 0.1rem; " onclick="layer.closeAll()"> 关 闭 </div> </div> </script> <script id="ongoingPeriodItemTemplate" type="text/html"> {{# for(var i = 0, len = d.length; i < len; i=i+1){ }} <div class="divOngoingPeriod defaultBgColorLight defaultBorderColor" onclick="showOngoingDetail('{{ d[i].Id }}')"> {{ d[i].Name }} </div> {{# } }} </script> <script id="endedPeriodItemTemplate" type="text/html"> {{# for(var i = 0, len = d.length; i < len; i=i+1){ }} <div class="divEndPeriod" onclick="showEndedDetail('{{ d[i].Id }}')"> {{ d[i].Name }} </div> {{# } }} </script> <div id="divImageContainer"> <img src="@Model.Campaign.ImageUrl" name="img" id="img" style="width: 100%;"> </div> <div class="divContent"> <div style="margin-top: 0.06rem" class="campaignName"> @Model.Campaign.Name </div> <div style="margin-top: 0.06rem" class="campaignDescription"> @Html.Raw(Model.Campaign.Introduction) </div> <div style="text-align: center"> <div class="divRectangle" style="margin-top: 0.1rem;" onclick="showCampaignDescription()"> 查看活动详情 </div> </div> <div style="text-align: center; margin-top: 0.1rem;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="33%" align="center">参与人数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.MemberCount</span> </td> <td width="33%" align="center">中奖人数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.WinMemberCount</span> </td> <td width="33%" align="center">围观次数<br /> <span class="defaultColor" style="font-weight:bold">@Model.DataReport.PageVisitCount</span> </td> </tr> </table> </div> <div class="divDotLine" style="margin-top: 0.05rem; margin-bottom: 0.1rem;"> </div> <div id="divMemberInfo" onclick="showShareMask()"> <table border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td align="left" style="width: 0.3rem"> <img src="/Content/Images/shareTimeLine.jpg" style="width: 0.2rem;"></td> <td align="left">分享给小伙伴吧~</td> </tr> </table> </div> <div style="margin-top: 0.1rem; font-weight: bold"> 进行中 </div> <div id="ongoingPeriodContainer"> </div> <div id="divOngoingPagingContainer" class="divPagingContainer" style="margin-top: 0.2rem; text-align: center" onclick="loadOngoingPeriod(_ongoingCurrentPage + 1)"> 查看更多 </div> <div style="margin-top: 0.1rem; font-weight: bold"> 已结束 </div> <div id="endedPeriodContainer"> </div> <div id="divEndedPagingContainer" class="divPagingContainer" style="margin-top: 0.2rem; text-align: center" onclick="loadOngoingPeriod(_ongoingCurrentPage + 1)"> 查看更多 </div> </div> <div id="divShareMask" style="display: none" onclick="hideShareMask()"> <img src="/Content/Images/share.PNG" width="200" height="145"> </div>
the_stack
@page "/QuartzUI" @model GZY.Quartz.MUI.Areas.MyFeature.Pages.MainModel @{ Layout = "_JavasCriptLayout"; } <div id="main"> <el-container> <el-header style="padding: 0;"> <!-- 头部样式 --> <el-menu :default-active="activeIndex" mode="horizontal" background-color="#fcfcfc"> <el-menu-item index="1">任务调度</el-menu-item> </el-menu> </el-header> <el-main> <el-row type="flex" align="middle"> <el-col :span="8"> <h4>后台任务列表</h4> </el-col> <el-col :span="16" style="text-align: right;"> <el-button type="primary" size="mini" icon="el-icon-plus" @@click="handleXJRW">新建任务</el-button> <el-button type="success" size="mini" icon="el-icon-video-pause" @@click="handleZTRW">暂停任务</el-button> <el-button type="warning" size="mini" icon="el-icon-open" @@click="handleKQRW">开启任务</el-button> <el-button type="danger" size="mini" icon="el-icon-video-play" @@click="handleLJZX">立即执行</el-button> <el-button type="info" size="mini" icon="el-icon-edit" @@click="handleXGRW">修改任务</el-button> <el-button type="danger" size="mini" icon="el-icon-delete-solid" @@click="OnDeleteJobs">删除任务</el-button> <el-button type="default" size="mini" icon="el-icon-refresh" @@click="OnLoadJobs">刷新数据</el-button> </el-col> </el-row> <el-row type="flex" align="middle"> <el-col :span="24" style="padding: 10px 0 0 0;"> <el-table ref="tb" :data="tableData" border stripe style="width: 100%;" highlight-current-row :header-cell-style="{backgroundColor:'#F5F7FA',color:'#000000'}" @@current-change="handleSelect"> <el-table-column type="index" width="50" label="序号" align="center"> </el-table-column> <el-table-column prop="TaskName" label="任务" width="180" align="center"> </el-table-column> <el-table-column prop="GroupName" label="分组" width="180" align="center"> </el-table-column> <el-table-column prop="Interval" label="间隔时间" align="center"> </el-table-column> <el-table-column prop="ApiUrl" label="ApiUrl" align="center"> </el-table-column> <el-table-column prop="Status" width="70" label="运行状态" align="center"> <template slot-scope="scope"> <el-tag type="info" disable-transitions v-if="scope.row.Status==4"> {{scope.row.Status|formatStatues}} </el-tag> <el-tag type="danger" disable-transitions v-if="scope.row.Status==5"> {{scope.row.Status|formatStatues}} </el-tag> <el-tag type="success" disable-transitions v-if="scope.row.Status==6"> {{scope.row.Status|formatStatues}} </el-tag> <el-tag type="primary" disable-transitions v-if="scope.row.Status==7"> {{scope.row.Status|formatStatues}} </el-tag> </template> </el-table-column> <el-table-column prop="LastRunTime" label="最近一次运行时间" align="center"> </el-table-column> <el-table-column prop="Describe" label="任务描述" :show-overflow-tooltip="true" align="center"> </el-table-column> <el-table-column prop="TaskType" label="任务类型" width="120" align="center"> <template slot-scope="scope"> {{scope.row.TaskType==1?'DLL':'API'}} </template> </el-table-column> <el-table-column label="操作" align="center"> <template slot-scope="scope"> <el-button size="mini" type="default" @@click="handleCZ(scope.$index, scope.row)">执行记录</el-button> </template> </el-table-column> </el-table> </el-col> </el-row> </el-main> </el-container> <el-dialog :title="title" :visible.sync="dialogFormVisible"> <el-row type="flex" justify="center"> <el-col :span="23"> <el-form :model="ruleForm" ref="ruleForm" label-width="10em" class="demo-ruleForm"> <el-form-item label="任务" prop="TaskName" :rules="rules.TaskName"> <el-input v-model="ruleForm.TaskName" placeholder="请输入任务名称"></el-input> </el-form-item> <el-form-item label="分组" prop="GroupName" :rules="rules.GroupName"> <el-input v-model="ruleForm.GroupName" placeholder="请输入分组名称"></el-input> </el-form-item> <el-form-item label="间隔时间" prop="Interval" :rules="rules.Interval"> <el-input v-model="ruleForm.Interval"></el-input> <p style="font-size:12px;color:red">间隔时间请输入Cron表达式<a target="_blank" href="https://qqe2.com/cron">在线生成</a></p> </el-form-item> <el-form-item label="任务类型" prop="TaskType" :rules="rules.TaskType"> <el-select v-model="ruleForm.TaskType" placeholder="请选择任务类型" @@change="taskTypeChange"> <el-option label="DLL" :value="1"></el-option> <el-option label="API" :value="2"></el-option> </el-select> </el-form-item> <el-form-item label="ApiUrl" prop="ApiUrl" :rules="rules.ApiUrl" v-if="ruleForm.TaskType==2"> <el-input v-model="ruleForm.ApiUrl" placeholder="请输入API地址"></el-input> </el-form-item> <el-form-item label="API访问类型" prop="ApiRequestType" :rules="rules.ApiRequestType" v-if="ruleForm.TaskType==2"> <el-select v-model="ruleForm.ApiRequestType" placeholder="请选择请求方式"> <el-option label="GET" value="GET"></el-option> <el-option label="POST" value="POST"></el-option> </el-select> </el-form-item> <el-form-item label="授权名" prop="ApiAuthKey" :rules="rules.ApiAuthKey" v-if="ruleForm.TaskType==2"> <el-input v-model="ruleForm.ApiAuthKey" placeholder="请输入API授权名"></el-input> </el-form-item> <el-form-item label="授权值" prop="ApiAuthValue" :rules="rules.ApiAuthValue" v-if="ruleForm.TaskType==2"> <el-input v-model="ruleForm.ApiAuthValue" placeholder="请输入API授权值"></el-input> </el-form-item> <el-form-item label="参数(API和DLL通用)" prop="ApiParameter" :rules="rules.ApiParameter"> <el-input v-model="ruleForm.ApiParameter" placeholder="请输入调用参数"></el-input> </el-form-item> <el-form-item label="DLL类型名" prop="DllClassName" :rules="rules.DllClassName" v-if="ruleForm.TaskType==1"> <el-input v-model="ruleForm.DllClassName" placeholder="请输入DLL类型名"></el-input> </el-form-item> @*<el-form-item label="Dll方法名" prop="DllActionName" :rules="rules.DllActionName" v-if="ruleForm.TaskType==1"> <el-input v-model="ruleForm.DllActionName" placeholder="请输入DLL方法名"></el-input> </el-form-item>*@ <el-form-item label="任务描述" prop="Describe"> <el-input type="textarea" :rows="5" v-model="ruleForm.Describe"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @@click="submitForm('ruleForm')">{{btnText}}</el-button> <el-button @@click="resetForm('ruleForm')">重置</el-button> </el-form-item> </el-form> </el-col> </el-row> </el-dialog> <el-dialog title="执行记录" :visible.sync="dialogRecordVisible"> <el-row type="flex" align="middle"> <el-col :span="24" style="padding: 10px 0 0 0;"> <el-table ref="tb_record" :data="recordData" border stripe style="width: 100%;" highlight-current-row :header-cell-style="{backgroundColor:'#F5F7FA',color:'#000000'}"> <el-table-column type="index" width="50" label="序号" align="center"> </el-table-column> <el-table-column prop="BeginDate" label="开始时间" width="180" align="center"> </el-table-column> <el-table-column prop="EndDate" label="结束时间" width="180" align="center"> </el-table-column> <el-table-column prop="Msg" label="消息" align="center" :show-overflow-tooltip="true"> </el-table-column> </el-table> </el-col> </el-row> <el-row type="flex" align="middle"> <el-col :span="24" style="text-align: right;"> <el-pagination @@size-change="handleSizeChange" @@current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" hide-on-single-page> </el-pagination> </el-col> </el-row> </el-dialog> </div> @section Scripts{ <script> new Vue({ el: "#main", data() { return { activeIndex: '1', tableData:[], dialogFormVisible: false, dialogRecordVisible: false, ruleForm: this.initTaskEntity(), rules: { TaskName: [ { required: true, message: '请输入任务名称', trigger: 'blur' } ], GroupName: [ { required: true, message: '请输入分组名称', trigger: 'blur' } ], Interval: [ { required: true, message: '请输入任务时间间隔', trigger: 'blur' } ], ApiUrl: [ { required: true, message: '请输入调用的API地址', trigger: 'blur' } ], Describe: [ { required: true, message: '请输入任务描述', trigger: 'blur' } ], TaskType: [ { required: true, message: '请选择任务类型', trigger: 'change' } ], ApiRequestType: [ { required: true, message: '请选择API访问类型', trigger: 'change' } ], //ApiAuthKey: [ // { required: true, message: '请输入Api授权名', trigger: 'blur' } //], //ApiAuthValue: [ // { required: true, message: '请输入Api授权值', trigger: 'blur' } //], //ApiParameter: [ // { required: true, message: '请输入API参数', trigger: 'blur' } //], DllClassName: [ { required: true, message: '请输入类名', trigger: 'blur' } ] //DllActionName: [ // { required: true, message: '请输入方法名', trigger: 'blur' } //] }, currentPage: 1, total: 0, pageSize: 20, pageSizes: [20, 30, 40, 50], selectrow: "", title: '新建任务', isedit: false, btnText: '立即创建', recordData:[] } }, mounted: function () { this.OnLoadJobs(); }, methods: { OnLoadJobs() { var that = this; axios("?handler=SelectJob").then(function (res) { that.tableData = res.data; }); }, handleXJRW() { this.title = "新建任务"; this.btnText = "立即创建"; this.isedit = false; this.ruleForm = this.initTaskEntity(); this.dialogFormVisible = true; }, OnDeleteJobs() { var that = this; ELEMENT.MessageBox.confirm('此操作将永久删除该任务, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { axios.post("?handler=DeleteJob", null, { params: that.selectrow }).then(function (res) { if (res.data.status) { that.OnLoadJobs(); } ELEMENT.MessageBox.alert(res.data.message, "系统提示"); }); }).catch(() => { }); }, handleSelect(val) { this.selectrow = val; }, resetForm(name) { var that = this; this.$refs[name].resetFields(); if (this.isedit) { this.ruleForm = this.initTaskEntity(); this.ruleForm.id = this.selectrow.id; this.ruleForm.timeflag = this.selectrow.timeflag; this.ruleForm.changetime = this.selectrow.changetime; } }, handleSizeChange(size) { this.currentPage = 1; this.pageSize = size; this.getRecord(); }, handleCurrentChange(page) { this.currentPage = page; this.getRecord(); }, handleCZ(index, row) { this.currentPage = 1; this.pageSize = 20; this.selectrow = row; this.getRecord(() => { this.dialogRecordVisible = true; }); }, getRecord(callback) { axios.post("?handler=JobRecord", null, { params: { taskName: this.selectrow.TaskName, groupName: this.selectrow.GroupName, current: this.currentPage, size: this.pageSize } }).then(res => { this.total = res.data.total; this.recordData = res.data.data; if (callback) { callback(); } }); }, handleZTRW() { if (!this.selectrow) { this.$message({ message: '请选择作业', type: 'warning' }); return false; } ELEMENT.MessageBox.confirm('确定暂停选中任务吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { axios.post("?handler=PauseJob", null, { params: this.selectrow }).then( res=> { if (res.data.status) { this.OnLoadJobs(); } ELEMENT.MessageBox.alert(res.data.message, "系统提示"); }); }).catch(() => { }); }, handleKQRW() { if (!this.selectrow) { this.$message({ message: '请选择作业', type: 'warning' }); return false; } ELEMENT.MessageBox.confirm('确定开启选中任务吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { axios.post("?handler=StartJob", null, { params: this.selectrow }).then(res => { if (res.data.status) { this.OnLoadJobs(); } ELEMENT.MessageBox.alert(res.data.message, "系统提示"); }); }).catch(() => { }); }, handleLJZX() { if (!this.selectrow) { this.$message({ message: '请选择作业', type: 'warning' }); return false; } ELEMENT.MessageBox.confirm('确定立即执行选中任务吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { axios.post("?handler=RunJob", null, { params: this.selectrow }).then(res => { if (res.data.status) { this.OnLoadJobs(); } ELEMENT.MessageBox.alert(res.data.message, "系统提示"); }); }).catch(() => { }); }, handleXGRW() { if (!this.selectrow) { this.$message({ message: '请选择作业', type: 'warning' }); return false; } this.isedit = true; this.title = "修改任务"; this.btnText = "立即修改"; this.dialogFormVisible = true; this.ruleForm = Object.assign({}, this.selectrow); }, submitForm(name) { var that = this; this.$refs[name].validate((valid) => { if (valid) { let url = ""; if (this.isedit) { url = "?handler=UpdateJob"; } else { url = "?handler=AddJob"; } axios.post(url, null, { params: that.ruleForm } ).then(function (res) { if (res.data.status) { ELEMENT.MessageBox.alert(res.data.message, "系统信息", { type: 'success', callback: () => { that.OnLoadJobs(); that.resetForm('ruleForm'); that.dialogFormVisible = false; } }); } else { ELEMENT.MessageBox.alert(res.data.message, "系统信息", { type: 'info', callback: () => { //that.OnLoadJobs(); //that.resetForm('ruleForm'); //that.dialogFormVisible = false; } }); } }); } }); }, taskTypeChange(val) { this.$refs["ruleForm"].clearValidate(); }, initTaskEntity() { return { TaskName: '', GroupName: '', Interval: '', ApiUrl: '', Describe: '', LastRunTime: '', Status: '', TaskType: '', ApiRequestType: '', ApiAuthKey: '', ApiAuthValue: '', ApiParameter: '', DllClassName: '', DllActionName: '', changetime: '', id: 0, timeflag:'' } } }, filters: { formatStatues(val) { switch (val) { case 1: return '新增'; case 2: return '删除'; case 3: return '修改'; case 4: return '暂停'; case 5: return '停止'; case 6: return '开启'; case 7: return '立即执行'; default: return ""; } } } }); </script> }
the_stack
@model WebApp.Models.Order @{ ViewBag.Title = "订单管理"; } <!-- MAIN CONTENT --> <div id="content"> <!-- quick navigation bar --> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-table fa-fw "></i> 订单中心 <span> > 订单管理 </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> </div> </div> <!-- end quick navigation bar --> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-table"></i> </span> <h2>订单管理</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div id="fakeLoader"></div> <div class="widget-body-toolbar"> <div class="row"> <div class="col-sm-8 "> <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") --> <div class="btn-group btn-group-sm"> <button onclick="append()" class="btn btn-default"> <i class="fa fa-plus"></i> 新增 </button> </div> <div class="btn-group btn-group-sm"> <button onclick="removeit()" class="btn btn-default"> <i class="fa fa-trash-o"></i> 删除 </button> </div> <div class="btn-group btn-group-sm"> <button onclick="accept()" class="btn btn-default"> <i class="fa fa-floppy-o"></i> 保存 </button> </div> <div class="btn-group btn-group-sm"> <button onclick="reload()" class="btn btn-default"> <i class="fa fa-refresh"></i> 刷新 </button> </div> <div class="btn-group btn-group-sm"> <button onclick="reject()" class="btn btn-default"> <i class="fa fa-ban"></i> 取消 </button> </div> <div class="btn-group btn-group-sm hidden-xs"> <button type="button" onclick="importexcel()" class="btn btn-default"><i class="fa fa-cloud-upload"></i> 导入数据 </button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a href="javascript:importexcel()"><i class="fa fa-file-excel-o"></i> 上传Excel </a></li> <li role="separator" class="divider"></li> <li><a href="javascript:downloadtemplate()"><i class="fa fa-download"></i> 下载模板 </a></li> </ul> </div> <div class="btn-group btn-group-sm hidden-xs hidden-md"> <button onclick="exportexcel()" class="btn btn-default"> <i class="fa fa-file-excel-o"></i> 导出Excel </button> </div> <div class="btn-group btn-group-sm visible-lg-inline-block"> <button onclick="print()" class="btn btn-default"> <i class="fa fa-print"></i> 打印 </button> </div> <div class="btn-group btn-group-sm visible-lg-inline-block"> <button onclick="dohelp()" class="btn btn-default"> <i class="fa fa-question-circle-o"></i> 帮助 </button> </div> </div> <div class="col-sm-4 text-align-right visible-lg-inline-block"> <div class="btn-group btn-group-sm"> <button onclick="window.history.back()" class="btn btn-sm btn-success"> <i class="fa fa-chevron-left"></i> 返回 </button> </div> </div> </div> </div> <div class="alert alert-warning no-margin fade in"> <button class="close" data-dismiss="alert"> × </button> <i class="fa-fw fa fa-info"></i> 注意事项: </div> <!--begin datagrid-content --> <div class="table-responsive"> <table id="orders_datagrid"> </table> </div> <!--end datagrid-content --> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> </section> <!-- end widget grid --> <!-- file upload partial view --> @Html.Partial("_ImportWindow",new ViewDataDictionary {{ "EntityName","Order" }}) <!-- end file upload partial view --> <!-- detail popup window --> @Html.Partial("_PopupDetailFormView",new WebApp.Models.Order()) <!-- end detail popup window --> </div> <!-- END MAIN CONTENT --> @section Scripts { <script type="text/javascript"> //是否启用弹窗口模式新增编辑数据 const POPUPMODE = false; //是否强制从后台取值 const REQUIRBACKEND = false; //是否开启行内编辑 const EDITINLINE = true; //上传导入参数设定 const entityname = "Order"; var order = {}; //下载Excel导入模板 function downloadtemplate() { //默认模板路径存放位置 var url = '/FileUpload/Download?file=/ExcelTemplate/Order.xlsx'; $.fileDownload(url) .done(() => { //console.log('file download a success!'); toastr.success('模板下载完成!', { timeOut: 2000 }); }) .fail(() => { $.messager.alert('失败','没有下载到导入模板[Order.xlsx]文件!','error'); }); } //打印 function print() { $dg.datagrid('print', 'DataGrid'); } //打开Excel上传窗口 function importexcel() { $('#importwindow').window('open'); } //执行导出下载Excel function exportexcel() { var filterRules = JSON.stringify($dg.datagrid('options').filterRules); //console.log(filterRules); $.messager.progress({ title: '正在执行导出!' }); var formData = new FormData(); formData.append('filterRules', filterRules); formData.append('sort', 'Id'); formData.append('order', 'asc'); $.postDownload('/Orders/ExportExcel', formData).then(res => { $.messager.progress('close'); toastr.success('导出完成', '确认', { timeOut: 2000 }); }).catch(err => { //console.log(err); $.messager.progress('close'); $.messager.alert('失败', err.statusText, 'error'); }); } //显示帮助信息 function dohelp() { toastr.info('有问题请联系管理员 <br><i class="fa fa-envelope-o" aria-hidden="true"></i> : demo@admin.com','帮助'); } var editIndex = undefined; //重新加载数据 function reload() { if (endEditing()) { $dg.datagrid('reload'); } } //关闭编辑状态 function endEditing() { if (editIndex === undefined) { return true; } if ($dg.datagrid('validateRow', editIndex)) { $dg.datagrid('endEdit', editIndex); editIndex = undefined; return true; } else { const invalidinput = $('input.validatebox-invalid'); const fieldnames = invalidinput.map((index, item) => { return $(item).attr('placeholder') || $(item).attr('id'); }); $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error'); return false; } } //单击列开启编辑功能 function onClickCell(index, field) { order = $dg.datagrid('getRows')[index]; var _operates = ['_operate1', 'ck']; if (!EDITINLINE || $.inArray(field, _operates) >= 0) { return; } if (editIndex !== index) { if (endEditing()) { $dg.datagrid('selectRow', index) .datagrid('beginEdit', index); hook = true; editIndex = index; var ed = $dg.datagrid('getEditor', { index: index, field: field }); if (ed) { ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus(); } } else { $dg.datagrid('selectRow', editIndex); } } } //新增记录 function append() { if (POPUPMODE) { //弹出新增窗口 showPopupCreateWindow(); } else { if (endEditing()) { //对必填字段进行默认值初始化 $dg.datagrid('insertRow', { index: 0, row: { } }); editIndex = 0; $dg.datagrid('selectRow', editIndex) .datagrid('beginEdit', editIndex); hook = true; } } } //删除编辑的行 function removeit() { if (EDITINLINE) { if (editIndex !== undefined) { $dg.datagrid('cancelEdit', editIndex) .datagrid('deleteRow', editIndex); editIndex = undefined; hook = true; }else{ var row = $dg.datagrid('getSelected'); if(row){ var rowindex = $dg.datagrid('getRowIndex', row); $dg.datagrid('deleteRow', rowindex); hook = true; }else{ $.messager.alert('提示', '没有选中删除的记录.', 'info'); } } } else { if ($dg.datagrid('getChecked').length > 0) { deletechecked(); } } } //删除该行 function deleteRow(id) { $.messager.confirm('确认', '你确定要删除该记录?', result => { if (result) { $.post('/Orders/DeleteCheckedAsync', { id: [id] }) .done(response => { if (response.success) { toastr.success('删除成功', '确认', { timeOut:2000 }); $dg.datagrid('uncheckAll'); $dg.datagrid('reload'); } else { $.messager.alert('错误', response.err,'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); $.messager.alert('失败', errorThrown,'error'); }); } }); } //删除选中的行 function deletechecked() { var rows = $dg.datagrid('getChecked'); if (rows.length > 0) { var id = rows.map(item => { return item.Id; }); $.messager.confirm('确认', `你确定要删除这 <span class='badge bg-color-red'>${id.length}</span> 行记录?`, result => { if (result) { $.post('/Orders/DeleteCheckedAsync', { id: id }) .done(response => { if (response.success) { toastr.success('删除成功', '确认', { timeOut:2000 }); $dg.datagrid('uncheckAll'); $dg.datagrid('reload'); } else { $.messager.alert('错误', response.err,'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); $.messager.alert('失败', errorThrown,'error'); }); } }); } else { $.messager.alert('提示', '请先选择要删除的记录!','question'); } } //提交保存后台数据库 function accept() { if (endEditing()) { if ($dg.datagrid('getChanges').length) { var inserted = $dg.datagrid('getChanges', 'inserted'); var deleted = $dg.datagrid('getChanges', 'deleted'); var updated = $dg.datagrid('getChanges', 'updated'); //过滤已删除的重复项 updated = updated.filter(item => { return !deleted.includes(item); }); var item = {}; if (inserted.length) { item.inserted = inserted; } if (deleted.length) { item.deleted = deleted; } if (updated.length) { item.updated = updated; } //console.log(JSON.stringify(item)); $.post('/Orders/SaveDataAsync', item) .done(response => { //console.log(response); if (response.success) { toastr.success('保存成功', '确认', { timeOut: 2000 }); $dg.datagrid('acceptChanges'); $dg.datagrid('reload'); hook = false; } else { $.messager.alert('错误', response.err ,'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); $.messager.alert('异常', errorThrown,'error'); }); } } } function reject() { $dg.datagrid('rejectChanges'); editIndex = undefined; hook = false; } function getChanges() { var rows = $dg.datagrid('getChanges'); //console.log(rows.length + ' rows are changed!'); } //弹出明细信息 function showDetailsWindow(id,row,index) { if (REQUIRBACKEND) { //console.log(index, row); $.get('/Orders/PopupEditAsync/' + id) .done(data => { //console.log(data); loadData(id,data,'Modified'); }) .fail((jqXHR, textStatus, errorThrown) => { $.messager.alert('错误', errorThrown,'error'); }); } else { loadData(id, JSON.parse(row),'Modified'); } } //弹出新建窗口 function showPopupCreateWindow() { //获取初始化对象 if (REQUIRBACKEND) { $.get('/Orders/PopupCreate') .done(data => { loadData(-1,data,'Added'); }) .fail((jqXHR, textStatus, errorThrown) => { $.messager.alert('错误', errorThrown, 'error'); }); } else { var item = { }; loadData(-1, item,'Added'); } } //初始化定义datagrid var $dg = $("#orders_datagrid"); $(() => { //定义datagrid结构 $dg.datagrid({ rownumbers:true, checkOnSelect:false, selectOnCheck:false, idField:'Id', sortName:'Id', sortOrder:'desc', remoteFilter: true, singleSelect: true, onBeforeLoad: function () { //datagrid resize when jarvisWidgets resized. const that = $(this); $(window).on("resize.jarvisWidgets", () => { that.datagrid('resize'); }) }, onSelect: function(index,row) { order = row; }, onEndEdit: function (index, row) { }, onBeforeEdit: function (index, row) { row.editing = true; $(this).datagrid('refreshRow', index); }, onAfterEdit: function (index, row) { row.editing = false; $(this).datagrid('refreshRow', index); }, onCancelEdit: function (index, row) { row.editing = false; $(this).datagrid('refreshRow', index); }, url: '/Orders/GetDataAsync', method: 'get', onClickCell: onClickCell, pagination: true, striped:true, columns: [[ /*开启CheckBox选择功能*/ { field: 'ck', checkbox: true }, { field: '_operate1', title:'操作', width: 80, sortable: false, resizable: true, formatter: function showdetailsformatter(value, row, index) { if (!row.editing) { return '<div class="btn-group">\ <button onclick="showDetailsWindow(\'' + row.Id + '\',\'' + JSON.stringify(row).replace(/\"/g, '&quot;') + '\',' + index +')" class="btn btn-default btn-xs" title="查看明细" ><i class="fa fa-pencil-square-o"></i> </button>\ <button onclick="deleteRow(\'' + row.Id + '\',\'' + JSON.stringify(row).replace(/\"/g, '&quot;') + '\',' + index +')" class="btn btn-default btn-xs" title="删除记录" ><i class="fa fa-trash-o"></i> </button>\ </div>'; } else { return '<button class="btn btn-default btn-xs" disabled title="查看明细" ><i class="fa fa-pencil-square-o"></i> </button>'; } } }, {field:'Id',title:'<span class="required">@Html.DisplayNameFor(model => model.Id)</span>', width:100 ,sortable:true,resizable:true, hidden:true}, { field:'OrderNo', title:'<span class="required">@Html.DisplayNameFor(model => model.OrderNo)</span>', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.OrderNo)',required:true ,validType:'length[12,12]' } }, sortable:true, resizable:true }, { field:'Customer', title:'<span class="required">@Html.DisplayNameFor(model => model.Customer)</span>', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Customer)',required:true ,validType:'length[0,30]' } }, sortable:true, resizable:true }, { field:'ShippingAddress', title:'<span class="required">@Html.DisplayNameFor(model => model.ShippingAddress)</span>', width:300, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.ShippingAddress)',required:true ,validType:'length[0,200]' } }, sortable:true, resizable:true }, { field:'Remark', title:'@Html.DisplayNameFor(model => model.Remark)', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Remark)',required:false ,validType:'length[0,100]' } }, sortable:true, resizable:true }, { field:'OrderDate', title:'<span class="required">@Html.DisplayNameFor(model => model.OrderDate)</span>', width:120, align:'right', editor:{ type:'datebox', options:{prompt:'@Html.DisplayNameFor(model => model.OrderDate)',required:true} }, formatter:dateformatter, sortable:true, resizable:true } , ]] }); $dg.datagrid('enableFilter',[ { field: 'Id', type: 'numberbox', op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: 'OrderDate', type: 'dateRange', options: { onChange: value => { $dg.datagrid('addFilterRule', { field: 'OrderDate', op: 'between', value: value }); $dg.datagrid('doFilter'); } } }, ]); }); </script> <!--begin popup detailview javascript block --> <script type="text/javascript"> //判断新增编辑状态 var MODELSTATE = 'Added'; var orderid = null; function loadData(id,data,state) { MODELSTATE = state; $("#detailswindow").window("open"); orderid = id; $('#order_form').form('load', data); var url='/OrderDetails/GetDataByOrderIdAsync?orderid=' + orderid; $orderdetailsdg.datagrid('load',url); $orderdetailsdg.datagrid('resize'); } var $editform = $('#order_form'); //async 保存数据 async function saveitem() { if ($editform.form('enableValidation').form('validate')) { var order = $editform.serializeJSON(); //获取明细表数据 if (!orderdetails_endEditing()) return false; var orderdetails = $orderdetailsdg.datagrid("getChanges"); if (MODELSTATE === 'Added') { order.OrderDetails = orderdetails ; } //如果没有保存明细记录调用一次保存 if (MODELSTATE === 'Modified' && orderdetails.length > 0) { let res = await orderdetails_accept(); if (!res.success) { return false; } } var url = '/Orders/EditAsync'; //判断是新增或是修改方法 if (MODELSTATE === 'Added') { url = '/Orders/CreateAsync'; } var token = $('input[name="__RequestVerificationToken"]', $editform).val(); $.ajax({ type: "POST", url: url, data: { __RequestVerificationToken: token, order:order }, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=utf-8' }) .done(response => { if (response.success) { $editform.form('disableValidation'); $dg.datagrid('reload'); $('#detailswindow').window("close"); toastr.success("保存成功", "确认", { timeOut:2000 }); } else { $.messager.alert("错误", response.err, "error"); } }) .fail((jqXHR, textStatus, errorThrown) => { $.messager.alert("失败", errorThrown,"error"); }); } } //关闭窗口 function closewindow() { $('#detailswindow').window('close'); } //todo function todo() { console.log('todo.....'); } //判断是否有没有保存的记录 function hasmodified() { if (!orderdetails_endEditing()) { return true; } var orderdetails = $orderdetailsdg.datagrid("getChanges"); if (MODELSTATE == 'Modified' && orderdetails.length > 0) { return true; } return false; } $('a[data-toggle="tab"]').on('shown.bs.tab', e => { var target = $(e.target).attr("href"); if(target === "#tab-orderdetails") $orderdetailsdg.datagrid("resize"); }); </script> <!-- orderdetail datagrid javascript block --> @Html.Partial("_orderdetaildatagridjsview", new WebApp.Models.OrderDetail()) <!--end popup detailview javascript block --> <script src="~/Scripts/jquery.filerupload.min.js"></script> }
the_stack
@model SmartAdmin.Domain.Models.Product @{ ViewData["Title"] = "产品主档"; ViewData["PageName"] = "products_index"; ViewData["Heading"] = "<i class='fal fa-window text-primary'></i> 产品主档"; ViewData["Category1"] = "主数据管理"; ViewData["PageDescription"] = ""; } <div class="row"> <div class="col-lg-12 col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> 产品主档 </h2> <div class="panel-toolbar"> <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button> <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button> </div> </div> <div class="panel-container enable-loader show"> <div class="loader"><i class="fal fa-spinner-third fa-spin-4x fs-xxl"></i></div> <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0 text-muted bg-subtlelight-fade "> <div class="row no-gutters align-items-center"> <div class="col"> <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") --> <div class="btn-group btn-group-sm"> <button onclick="appendItem()" class="btn btn-default"> <span class="fal fa-plus mr-1"></span> 新增 </button> </div> <div class="btn-group btn-group-sm"> <button name="deletebutton" disabled onclick="removeItem()" class="btn btn-default"> <span class="fal fa-times mr-1"></span> 删除 </button> </div> <div class="btn-group btn-group-sm"> <button name="savebutton" disabled onclick="acceptChanges()" class="btn btn-default"> <span class="fal fa-save mr-1"></span> 保存 </button> </div> <div class="btn-group btn-group-sm"> <button name="cancelbutton" disabled onclick="rejectChanges()" class="btn btn-default"> <span class="fal fa-ban mr-1"></span> 取消 </button> </div> <div class="btn-group btn-group-sm"> <button onclick="reload()" class="btn btn-default"> <span class="fal fa-search mr-1"></span> 查询 </button> <button type="button" class="btn btn-default dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu dropdown-menu-animated"> <a class="dropdown-item js-waves-on" href="javascript:void()"> 我的记录 </a> <div class="dropdown-divider"></div> <a class="dropdown-item js-waves-on" href="javascript:void()"> 自定义查询 </a> </div> </div> <div class="btn-group btn-group-sm hidden-xs"> <button type="button" onclick="importExcel.upload()" class="btn btn-default"><span class="fal fa-cloud-upload mr-1"></span> 导入 </button> <button type="button" class="btn btn-default dropdown-toggle dropdown-toggle-split waves-effect waves-themed" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu dropdown-menu-animated"> <a class="dropdown-item js-waves-on" href="javascript:importExcel.downloadtemplate()"> <span class="fal fa-download"></span> 下载模板 </a> </div> </div> <div class="btn-group btn-group-sm hidden-xs"> <button onclick="exportExcel()" class="btn btn-default"> <span class="fal fa-file-export mr-1"></span> 导出 </button> </div> </div> </div> </div> <div class="panel-content"> <div class="table-responsive"> <table id="companies_datagrid"> </table> </div> </div> </div> </div> </div> </div> <!-- 弹出窗体form表单 --> <div id="productdetailwindow" class="easyui-window" title="明细数据" data-options="modal:true, closed:true, minimizable:false, collapsible:false, maximized:false, iconCls:'fal fa-window', onBeforeClose:function(){ var that = $(this); if(producthasmodified()){ $.messager.confirm('确认','你确定要放弃保存修改的记录?',function(r){ if (r){ var opts = that.panel('options'); var onBeforeClose = opts.onBeforeClose; opts.onBeforeClose = function(){}; that.panel('close'); opts.onBeforeClose = onBeforeClose; hook = false; } }); return false; } }, onOpen:function(){ $(this).window('vcenter'); $(this).window('hcenter'); }, onRestore:function(){ }, onMaximize:function(){ } " style="width:820px;height:420px;display:none"> <!-- toolbar --> <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0 text-muted bg-subtlelight-fade sticky-top"> <div class="d-flex flex-row-reverse pr-4"> <div class="btn-group btn-group-sm mr-1"> <button name="saveitembutton" onclick="saveproductitem()" class="btn btn-default"> <i class="fal fa-save"></i> 保存 </button> </div> <div class="btn-group btn-group-sm mr-1" id="deleteitem-btn-group"> <button onclick="deleteproductitem()" class="btn btn-danger"> <i class="fal fa-trash-alt"></i> 删除 </button> </div> </div> </div> <div class="panel-container show"> <div class="container"> <div class="panel-content"> <form id="product_form" class="easyui-form form-horizontal p-1" method="post" data-options="novalidate:true, onChange: function(target){ hook = true; $('button[name*=\'saveitembutton\']').prop('disabled', false); }, onLoadSuccess:function(data){ hook = false; $('button[name*=\'saveitembutton\']').prop('disabled', true); }"> @Html.AntiForgeryToken() <!--Primary Key--> @Html.HiddenFor(model => model.Id) <fieldset class="form-group"> <!-- begin row --> <!--名称--> <div class="row h-100 justify-content-center align-items-center"> <label class="col-md-2 pr-1 form-label text-right"><span class="text-danger">*</span> @Html.DisplayNameFor(model => model.Name)</label> <div class="col-md-4 mb-1 pl-1"> <input id="@Html.IdFor(model => model.Name)" name="@Html.NameFor(model => model.Name)" value="@Html.ValueFor(model => model.Name)" tabindex="0" required class="easyui-textbox" style="width:100%" type="text" data-options="prompt:'@Html.DescriptionFor(model => model.Name)', required:true, validType: 'length[0,128]' " /> </div> <label class="col-md-2 pr-1 form-label text-right ">@Html.DisplayNameFor(model => model.Model)</label> <div class="col-md-4 mb-1 pl-1"> <input id="@Html.IdFor(model => model.Model)" name="@Html.NameFor(model => model.Model)" value="@Html.ValueFor(model => model.Model)" tabindex="1" required class="easyui-textbox" style="width:100%" type="text" data-options="prompt:'@Html.DescriptionFor(model => model.Model)', required:true,validType: 'length[0,60]' " /> </div> <label class="col-md-2 pr-1 form-label text-right">@Html.DisplayNameFor(model => model.Unit)</label> <div class="col-md-4 mb-1 pl-1"> <input id="@Html.IdFor(model => model.Unit)" name="@Html.NameFor(model => model.Unit)" value="@Html.ValueFor(model => model.Unit)" tabindex="2" class="easyui-textbox" style="width:100%" type="text" data-options="prompt:'@Html.DescriptionFor(model => model.Unit)', required:false, validType: 'length[0,10]' " /> </div> <label class="col-md-2 pr-1 form-label text-right">@Html.DisplayNameFor(model => model.UnitPrice)</label> <div class="col-md-4 mb-1 pl-1"> <input id="@Html.IdFor(model => model.UnitPrice)" name="@Html.NameFor(model => model.UnitPrice)" value="@Html.ValueFor(model => model.UnitPrice)" tabindex="3" class="easyui-numberbox" style="width:100%" type="text" data-options="prompt:'@Html.DescriptionFor(model => model.UnitPrice)', required:true, formatter:numberformatter,parser:parsernumber " /> </div> </div> </fieldset> </form> </div> </div> </div> </div> @await Component.InvokeAsync("ImportExcel", new ImportExcelOptions { entity = "Product", folder = "Products", url = "/Products", tpl = "Product.xlsx", callback="reload()" }) @section HeadBlock { <link href="~/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css" rel="stylesheet" asp-append-version="true" /> <link href="~/js/easyui/themes/insdep/easyui.css" rel="stylesheet" asp-append-version="true" /> } @section ScriptsBlock { <script src="~/js/dependency/numeral/numeral.min.js" asp-append-version="true"></script> <script src="~/js/dependency/moment/moment.js" asp-append-version="true"></script> <script src="~/js/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js" asp-append-version="true"></script> <script src="~/js/easyui/jquery.easyui.min.js" asp-append-version="true"></script> <script src="~/js/easyui/plugins/datagrid-filter.js" asp-append-version="true"></script> <script src="~/js/easyui/locale/easyui-lang-zh_CN.js" asp-append-version="true"></script> <script src="~/js/easyui/jquery.easyui.component.js" asp-append-version="true"></script> <script src="~/js/plugin/filesaver/FileSaver.js" asp-append-version="true"></script> <script src="~/js/plugin/jquery.serializejson/jquery.serializejson.js" asp-append-version="true"></script> <script src="~/js/jquery.custom.extend.js" asp-append-version="true"></script> <script src="~/js/jquery.extend.formatter.js" asp-append-version="true"></script> <script> //全屏事件 document.addEventListener('panel.onfullscreen', () => { $dg.treegrid('resize'); }); var $dg = $('#companies_datagrid'); var EDITINLINE = true; var product = null; var editIndex = undefined; //下载Excel导入模板 //执行导出下载Excel function exportExcel() { const filterRules = JSON.stringify($dg.datagrid('options').filterRules); console.log(filterRules); $.messager.progress({ title: '请等待', msg: '正在执行导出...' }); let formData = new FormData(); formData.append('filterRules', filterRules); formData.append('sort', 'Id'); formData.append('order', 'asc'); $.postDownload('/Products/ExportExcel', formData).then(res => { $.messager.progress('close'); toastr.success('导出成功!'); }).catch(err => { //console.log(err); $.messager.progress('close'); $.messager.alert('导出失败', err.statusText, 'error'); }); } //弹出明细信息 function showDetailsWindow(id, index) { const product = $dg.datagrid('getRows')[index]; openProductDetailWindow(product, 'Modified'); } function reload() { $dg.datagrid('uncheckAll'); $dg.datagrid('reload'); } //新增记录 function appendItem() { product = { Address: '-', RegisterDate: moment().format('YYYY-MM-DD HH:mm:ss'), }; if (!EDITINLINE) { //弹出新增窗口 openProductDetailWindow(product, 'Added'); } else { if (endEditing()) { //对必填字段进行默认值初始化 $dg.datagrid('insertRow', { index: 0, row: product }); editIndex = 0; $dg.datagrid('selectRow', editIndex) .datagrid('beginEdit', editIndex); hook = true; } } } //删除编辑的行 function removeItem() { if (this.$dg.datagrid('getChecked').length <= 0 && EDITINLINE) { if (editIndex !== undefined) { const delindex = editIndex; $dg.datagrid('cancelEdit', delindex) .datagrid('deleteRow', delindex); hook = true; $("button[name*='savebutton']").prop('disabled', false); $("button[name*='cancelbutton']").prop('disabled', false); } else { const rows = $dg.datagrid('getChecked'); rows.slice().reverse().forEach(row => { const rowindex = $dg.datagrid('getRowIndex', row); $dg.datagrid('deleteRow', rowindex); hook = true; }); } } else { deletechecked(); } } //删除选中的行 function deleteChecked() { const checked = $dg.datagrid('getChecked').filter(item => item.Id != null && item.Id > 0).map(item => { return item.Id; });; if (checked.length > 0) { deleteRows(checked); } else { $.messager.alert('提示', '请先选择要删除的记录!', 'question'); } } //执行删除 function deleteRows(selected) { $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${selected.length} </span> 行记录?`, result => { if (result) { $.post('/Products/DeleteChecked', { id: selected }) .done(response => { if (response.success) { toastr.error(`成功删除 [${selected.length}] 行记录`); reload(); } else { $.messager.alert('错误', response.err, 'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error'); }); } }); } //开启编辑状态 function onClickCell(index, field) { product = $dg.datagrid('getRows')[index]; const _actions = ['action', 'ck']; if (!EDITINLINE || $.inArray(field, _actions) >= 0) { return; } if (editIndex !== index) { if (endEditing()) { $dg.datagrid('selectRow', index) .datagrid('beginEdit', index); hook = true; editIndex = index; const ed = $dg.datagrid('getEditor', { index: index, field: field }); if (ed) { ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus(); } } else { $dg.datagrid('selectRow', editIndex); } } } //关闭编辑状态 function endEditing() { if (editIndex === undefined) { return true; } if (this.$dg.datagrid('validateRow', editIndex)) { $dg.datagrid('endEdit', editIndex); return true; } else { const invalidinput = $('input.validatebox-invalid', $dg.datagrid('getPanel')); const fieldnames = invalidinput.map((index, item) => { return $(item).attr('placeholder') || $(item).attr('id'); }); $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error'); return false; } } //提交保存后台数据库 function acceptChanges() { if (endEditing()) { if ($dg.datagrid('getChanges').length > 0) { const inserted = $dg.datagrid('getChanges', 'inserted').map(item => { item.TrackingState = 1; return item; }); const updated = $dg.datagrid('getChanges', 'updated').map(item => { item.TrackingState = 2 return item; }); const deleted = $dg.datagrid('getChanges', 'deleted').map(item => { item.TrackingState = 3 return item; }); //过滤已删除的重复项 const changed = inserted.concat(updated.filter(item => { return !deleted.includes(item); })).concat(deleted); //$.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 }); $.post('/Products/AcceptChanges', { products: changed }) .done(response => { //$.messager.progress('close'); //console.log(response); if (response.success) { toastr.success('保存成功'); $dg.datagrid('acceptChanges'); reload(); hook = false; } else { $.messager.alert('错误', response.err, 'error'); } }) .fail((jqXHR, textStatus, errorThrown) => { //$.messager.progress('close'); $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error'); }); } } } function rejectChanges() { $dg.datagrid('rejectChanges'); editIndex = undefined; hook = false; } $(document).ready(function () { //定义datagrid结构 $dg.datagrid({ rownumbers: true, checkOnSelect: false, selectOnCheck: false, idField: 'Id', sortName: 'Id', sortOrder: 'desc', remoteFilter: true, singleSelect: true, method: 'get', onClickCell: onClickCell, clientPaging: false, pagination: true, striped: true, filterRules: [], height: 670, pageSize: 15, pageList: [15, 20, 50, 100, 500, 2000], onBeforeLoad: function () { $('.enable-loader').removeClass('enable-loader') }, onLoadSuccess: function (data) { editIndex = undefined; $("button[name*='deletebutton']").prop('disabled', true); $("button[name*='savebutton']").prop('disabled', true); $("button[name*='cancelbutton']").prop('disabled', true); }, onCheckAll: function (rows) { if (rows.length > 0) { $("button[name*='deletebutton']").prop('disabled', false); } }, onUncheckAll: function () { $("button[name*='deletebutton']").prop('disabled', true); }, onCheck: function () { $("button[name*='deletebutton']").prop('disabled', false); }, onUncheck: function () { const checked = $(this).datagrid('getChecked').length > 0; $("button[name*='deletebutton']").prop('disabled', !checked); }, onSelect: function (index, row) { product = row; }, onBeginEdit: function (index, row) { //const editors = $(this).datagrid('getEditors', index); }, onEndEdit: function (index, row) { editIndex = undefined; }, onBeforeEdit: function (index, row) { editIndex = index; row.editing = true; $("button[name*='deletebutton']").prop('disabled', false); $("button[name*='cancelbutton']").prop('disabled', false); $("button[name*='savebutton']").prop('disabled', false); $(this).datagrid('refreshRow', index); }, onAfterEdit: function (index, row) { row.editing = false; editIndex = undefined; $(this).datagrid('refreshRow', index); }, onCancelEdit: function (index, row) { row.editing = false; editIndex = undefined; $("button[name*='deletebutton']").prop('disabled', true); $("button[name*='savebutton']").prop('disabled', true); $("button[name*='cancelbutton']").prop('disabled', true); $(this).datagrid('refreshRow', index); }, frozenColumns: [[ /*开启CheckBox选择功能*/ { field: 'ck', checkbox: true }, { field: 'action', title: '操作', width: 85, sortable: false, resizable: true, formatter: function showdetailsformatter(value, row, index) { if (!row.editing) { return `<div class="btn-group">\ <button onclick="showDetailsWindow('${row.Id}', ${index})" class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" title="查看明细" ><i class="fal fa-edit"></i> </button>\ <button onclick="deleteRows(['${row.Id}'],${index})" class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" title="删除记录" ><i class="fal fa-times"></i> </button>\ </div>`; } else { return `<button class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" disabled title="查看明细" ><i class="fal fa-edit"></i> </button>`; } } } ]], columns: [[ { /*名称*/ field: 'Name', title: '<span class="text-danger">*<span> @Html.DisplayNameFor(model => model.Name)', width: 200, hidden: false, editor: { type: 'textbox', options: { prompt: '@Html.DescriptionFor(model => model.Name)', required: true, validType: 'length[0,128]' } }, sortable: true, resizable: true }, { /*规格型号*/ field: 'Model', title: '@Html.DisplayNameFor(model => model.Model)', width: 120, hidden: false, editor: { type: 'textbox', options: { prompt: '@Html.DescriptionFor(model => model.Model)', required: true, validType: 'length[0,60]' } }, sortable: true, resizable: true }, { /*单位*/ field: 'Unit', title: '@Html.DisplayNameFor(model => model.Unit)', width: 200, hidden: false, editor: { type: 'textbox', options: { prompt: '@Html.DescriptionFor(model => model.Unit)', required: false, validType: 'length[0,10]' } }, sortable: true, resizable: true }, { /*单价*/ field: 'UnitPrice', title: '@Html.DisplayNameFor(model => model.UnitPrice)', width: 120, hidden: false, editor: { type: 'numberbox', options: { prompt: '@Html.DescriptionFor(model => model.UnitPrice)', required: true} }, sortable: true, resizable: true, formatter: numberformatter } ]] }) .datagrid('enableFilter', [ ]) .datagrid('load', '/Products/GetData'); } ); </script> <script type="text/javascript"> //判断新增编辑状态 var MODELSTATE = 'Added'; var productid = null; function openProductDetailWindow(data, state) { MODELSTATE = state; initproductdetailview(); productid = (data.Id || 0); $("#productdetailwindow").window("open"); $('#product_form').form('reset'); $('#product_form').form('load', data); } //删除当前记录 function deleteproductitem() { $.messager.confirm('确认', '你确定要删除该记录?', result => { if (result) { const url = `/Products/Delete/${productid}`; $.get(url).done(res => { if (res.success) { toastr.success("删除成功"); $("#productdetailwindow").window("close"); reload(); } else { $.messager.alert("错误", res.err, "error"); } }); } }); } //async 保存数据 async function saveproductitem() { const $productform = $('#product_form'); if ($productform.form('enableValidation').form('validate')) { let product = $productform.serializeJSON(); let url = '/Products/Edit'; //判断是新增或是修改方法 if (MODELSTATE === 'Added') { url = '/Products/Create'; } var token = $('input[name="__RequestVerificationToken"]', $productform).val(); //$.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 }); $.ajax({ type: "POST", url: url, data: { __RequestVerificationToken: token, product: product }, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=utf-8' }) .done(response => { //$.messager.progress('close'); if (response.success) { hook = false; $productform.form('disableValidation'); $dg.datagrid('reload'); $('#productdetailwindow').window("close"); toastr.success("保存成功"); } else { $.messager.alert("错误", response.err, "error"); } }) .fail((jqXHR, textStatus, errorThrown) => { //$.messager.progress('close'); $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error'); }); } } //关闭窗口 function closeproductdetailwindow() { $('#productdetailwindow').window('close'); } //判断是否有没有保存的记录 function producthasmodified() { return hook; } function initproductdetailview() { //判断是否显示功能按钮 } </script> }
the_stack
@model IEnumerable<WebApp.Models.Message> @{ ViewBag.Title = "日志信息"; } <!-- MAIN CONTENT --> <div id="content"> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-list-alt fa-fw "></i> 系统管理 <span> > 日志消息 </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> </div> </div> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <article class="col-xs-6 col-sm-3 col-md-3 col-lg-3"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-red" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-warning"></i> </span> <h2 class="font-md"><strong>新增异常</strong> <i>new</i></h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <h1 class=" "> @ViewBag.TotalNewError.ToString("N0") </h1> <small>新增异常</small> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> </article> <article class="col-xs-6 col-sm-3 col-md-3 col-lg-3"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-red" id="wid-id-1" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-warning"></i> </span> <h2 class="font-md"><strong>系统异常</strong> <i>all</i></h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <h1 class=" "> @ViewBag.TotalSysError.ToString("N0")</h1> <small>系统异常</small> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> </article> <article class="col-xs-6 col-sm-3 col-md-3 col-lg-3"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-red" id="wid-id-2" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-warning"></i> </span> <h2 class="font-md"><strong>操作异常</strong> <i>all</i></h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <h1 class=" "> @ViewBag.TotalOpError.ToString("N0")</h1> <small>操作异常</small> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> </article> <article class="col-xs-6 col-sm-3 col-md-3 col-lg-3"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget jarviswidget-color-red" id="wid-id-3" data-widget-editbutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-warning"></i> </span> <h2 class="font-md"><strong>接口异常</strong> <i>all</i></h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <h1 class=" "> @ViewBag.TotalInterfaceError.ToString("N0")</h1> <small>接口异常</small> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> </article> </div> <div class="row"> <div class="col-sm-12"> <div class="well"> <h1>系统日志</h1> <div class="table-responsive"> <table id="messages_datagrid" > </table> </div> </div> </div> </div> </section> <div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content animated bounceInRight"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h5 class="modal-title">日志</h5> </div> <div class="modal-body"> <div class="alert alert-success" role="alert" id="alert-content"> <h4 class="alert-heading" id="title-method"></h4> <p id="msg-content"></p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-white" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <!-- END MAIN CONTENT --> <!-- end file upload partial view --> @section Scripts { <script type="text/javascript"> //上传导入参数设定 const entityname = "Message"; //执行Excel到处下载 function exportexcel() { var filterRules = JSON.stringify($dg.datagrid("options").filterRules); //console.log(filterRules); $.messager.progress({ title: "正在执行导出!" }); var formData = new FormData(); formData.append("filterRules", filterRules); formData.append("sort", "Id"); formData.append("order", "asc"); $.postDownload("/Messages/ExportExcel", formData, function (fileName) { $.messager.progress("close"); console.log(fileName); }) } //datagrid 增删改查操作 var $dg = $("#messages_datagrid"); var editIndex = undefined; function reload() { $dg.datagrid("reload"); } function onClickCell(index, row) { console.log(row); $('#myModal').modal(); $('#title-method').text(row.Method); $('#msg-content').text(row.Content); $('#alert-content').removeClass(); if (row.Type === 0) { $('#alert-content').addClass('alert alert-success'); } else if (row.Type === 0) { $('#alert-content').addClass('alert alert-danger'); } else { $('#alert-content').addClass('alert alert-warning'); } } //datagrid 开启行赛选功能 $(function () { $dg.datagrid({ rownumbers: true, checkOnSelect: true, selectOnCheck: true, idField: 'Id', sortName: 'Id', sortOrder: 'desc', remoteFilter: true, singleSelect: true, url: '/Messages/GetData', method: 'get', onClickRow: onClickCell, onSelect: onSelect, pagination: 'true', columns: [[ { field: 'Group', title: '@Html.DisplayNameFor(model => model.Group)', width: 100, align: 'right', sortable: true, resizable: true, formatter: messagegroupformatter }, { field: 'ExtensionKey1', title: '@Html.DisplayNameFor(model => model.ExtensionKey1)',width:140 ,sortable:true,resizable:true }, { field: 'Type', title: '@Html.DisplayNameFor(model => model.Type)',width:100,align:'right' ,sortable:true,resizable:true ,formatter:messagetypeformatter }, { field: 'Code', title: '@Html.DisplayNameFor(model => model.Code)',width: 140, sortable: true, resizable: true }, { field:'Content' ,width:360 ,sortable:true,resizable:true,title:'@Html.DisplayNameFor(model => model.Content)' }, { field: 'User', width: 140, sortable: true, resizable: true, title: '@Html.DisplayNameFor(model => model.User)' }, { field: 'Tags', width: 140, sortable: true, resizable: true, title: '@Html.DisplayNameFor(model => model.Tags)' }, { field: 'Method', width: 120, sortable: true, resizable: true, title: '@Html.DisplayNameFor(model => model.Method)' }, { field: 'Created', width: 160, align: 'right', sortable: true, resizable: true, formatter: datetimeformatter, title: '@Html.DisplayNameFor(model => model.Created)' }, { field: 'ExtensionKey2', width: 140, sortable: true, resizable: true, title: '@Html.DisplayNameFor(model => model.ExtensionKey2)' }, { field: 'IsNew', width: 100, align: 'right', sortable: true, resizable: true, formatter: isnewformatter, title: '@Html.DisplayNameFor(model => model.IsNew)' }, { field: 'IsNotification', width: 100, align: 'right', sortable: true, resizable: true, formatter: isnoticeformatter, title: '@Html.DisplayNameFor(model => model.IsNotification)' } ]] }); $dg.datagrid("enableFilter", [ { field: 'Group', type: 'messagegroupfilter', }, { field: 'Type', type: 'messagetypefilter', }, { field: 'IsNew', type: 'isnewfilter', }, { field: 'IsNotification', type: 'isnoticefilter', }, { field: "Created", type: "datebox", options: { onChange: function (value) { if (value == "") { $dg.datagrid("removeFilterRule", "Created"); } else { $dg.datagrid("addFilterRule", { field: "Created", op: "equal", value: value }); } $dg.datagrid("doFilter"); } } } ]); $dg.datagrid('removeFilterRule', 'IsNew'); $dg.datagrid('addFilterRule', { field: 'IsNew', op: 'equal', value: '0' }); }); //----------------------------------------------------- //datagrid onSelect //----------------------------------------------------- function onSelect(index, row) { //console.log(index, row); } </script> }
the_stack
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Microsoft.Net.Http #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=Microsoft.VisualBasic #addin nuget:?package=Microsoft.Azure.KeyVault.Core&version=1.0.0.0 #addin nuget:?package=Microsoft.Data.Services.Client&version=5.8.1.0 #addin nuget:?package=Microsoft.Data.OData&version=5.8.1.0 #addin nuget:?package=Microsoft.Data.Edm&version=5.8.1.0 #addin nuget:?package=System.Spatial&version=5.8.1.0 #addin nuget:?package=WindowsAzure.Storage&version=8.1.4.0 #addin nuget:?package=Microsoft.IdentityModel.Clients.ActiveDirectory&version=2.28.3 #addin nuget:?package=Microsoft.Rest.ClientRuntime&version=2.3.9 #addin nuget:?package=Microsoft.Rest.ClientRuntime.Azure&version=3.3.10 #addin nuget:?package=Microsoft.Rest.ClientRuntime.Azure.Authentication&version=2.3.2 #addin nuget:?package=Microsoft.Azure.DocumentDB #addin nuget:?package=Microsoft.Azure.Management.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Storage.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.KeyVault.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Graph.RBAC.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Compute.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Network.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Batch.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.TrafficManager.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Dns.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Sql.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Redis.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Cdn.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Search.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.ServiceBus.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.ContainerInstance.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.ContainerRegistry.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.ContainerService.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.CosmosDB.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Locks.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Msi.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.BatchAI.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Monitor.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.EventHub.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.ResourceManager.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.AppService.Fluent&version=1.14.0 #addin nuget:?package=Microsoft.Azure.Management.Sql.Fluent&version=1.14.0 /////////////////////////////////////////////////////////////////////////////// // LOADS /////////////////////////////////////////////////////////////////////////////// #load cake/paths.cake /////////////////////////////////////////////////////////////////////////////// // USINGS /////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Microsoft.VisualBasic.FileIO; using System.Threading.Tasks; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.AppService.Fluent; using Microsoft.Azure.Management.CosmosDB.Fluent; using Microsoft.Azure.Management.CosmosDB.Fluent.Models; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Management.Storage.Fluent; using Microsoft.Azure.Management.Sql.Fluent; using Microsoft.Azure.Management.Sql.Fluent.Models; /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("Target", "Build"); var site = Argument("Site", "site"); var app = Argument("App", "app"); var env = Argument("Env", "Prod"); var configuration = Argument("Configuration", "Debug"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// IAzure azure = null; IResourceGroup resourceGroup = null; ICosmosDBAccount cosmosAccount = null; IStorageAccount storageAccount = null; IAppServicePlan appServicePlan = null; IAppServicePlan webAppServicePlan = null; IWebApp webApp = null; IFunctionApp driversFunctionsApp = null; IFunctionApp tripsFunctionsApp = null; IFunctionApp passengersFunctionsApp = null; IFunctionApp orchestratorsFunctionsApp = null; IFunctionApp archiverFunctionsApp = null; ISqlServer sqlDatabaseServer = null; ISqlDatabase sqlDatabase = null; string kuduApiAuthorizationToken = ""; /////////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // SETUP / TEARDOWN /////////////////////////////////////////////////////////////////////////////// Setup(ctx => { // Executed BEFORE the first task. Information("Running tasks..."); }); Teardown(ctx => { // Executed AFTER the last task. Information("Finished running tasks."); }); /////////////////////////////////////////////////////////////////////////////// // DEPLOY TASKS /////////////////////////////////////////////////////////////////////////////// Task("Restore") .Does(() => { Information($"Restoring API...{Paths.SolutionFile}"); NuGetRestore(Paths.SolutionFile); }); Task("Build") .IsDependentOn("Restore") .Does(() => { Information("Bulding API...."); DotNetBuild(Paths.SolutionFile, settings => settings.SetConfiguration(configuration).WithTarget("Build")); }); Task("Zip") .IsDependentOn("Build") .Does(() => { Information("Zipping API...."); EnsureDirectoryExists(Paths.PublishDirectory); CleanDirectory(Paths.PublishDirectory); // Copy the Functions App deploy files CopyDirectory($"{app}/bin/{configuration}/netstandard2.0", Paths.PublishDirectory); // Zip up Zip(Paths.PublishDirectory, Paths.Combine(Paths.PublishDirectory, $"{Resources.GetSite(site, env)}.zip")); }); Task("Authenticate") .IsDependentOn("Zip") .Does(() => { Information("Authenticate against Azure...."); AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Paths.GetAuthFile(env)); azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(Paths.GetSubscriptionId(env)); string functionsAppId = $"/subscriptions/{Paths.GetSubscriptionId(env)}/resourceGroups/{Resources.GetResourceGroup(env)}/providers/Microsoft.Web/sites/{Resources.GetSite(site, env)}"; Information($"Functions App ID: {functionsAppId}"); var functionsApp = azure.WebApps.GetById(functionsAppId); if (functionsApp == null) throw new Exception($"Unable to retrieve web app: {functionsAppId}"); var webPublishProfile = functionsApp.GetPublishingProfile(); Information($"Web App User ID: {webPublishProfile.GitUsername}"); kuduApiAuthorizationToken = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{webPublishProfile.GitUsername}:{webPublishProfile.GitPassword}")); Information($"Kudu API Auth Token: {kuduApiAuthorizationToken}"); }); Task("ImportAppSettings") .IsDependentOn("Authenticate") .Does(() => { Information("Import App Settings...."); var settingsFilePath = Paths.GetAppSettingsCSVFile(Resources.GetSite(site, env), env); Information($"Application settings File Path : {settingsFilePath}"); // https://github.com/projectkudu/kudu/wiki/REST-API // https://docs.microsoft.com/en-us/rest/api/appservice/webapps/updateapplicationsettings Dictionary<string, string> settings = new Dictionary<string, string>(); TextFieldParser parser = new TextFieldParser(settingsFilePath.ToString()); parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters("|"); int row = 0; while (!parser.EndOfData) { string[] fields = parser.ReadFields(); if (row > 0) // Skip the header row { //Process row try { var key = ""; var value = ""; int index = 0; foreach (string field in fields) { if (index == 0) { key = field; } else if (index == 1) { value = field; Information($"App Setting - Key: {key} => value: {value}"); settings.Add(key, value); } index = index + 1; } } catch (Exception e) { Error("A parser error on row {0} occurred {1} ", row, e.Message); } } row++; } parser.Close(); string webAppId = $"/subscriptions/{Paths.GetSubscriptionId(env)}/resourceGroups/{Resources.GetResourceGroup(env)}/providers/Microsoft.Web/sites/{Resources.GetSite(site, env)}"; Information($"Web App ID : {webAppId}"); var webApp = azure.WebApps.GetById(webAppId); if (webApp == null) throw new Exception($"Unable to retrieve web app: {webAppId}"); Information($"Updating web app settings: {settings.Count}"); webApp.Update().WithAppSettings(settings).Apply(); }); Task("Deploy") .IsDependentOn("ImportAppSettings") .Does(async () => { Information($"Deploying API using Kudu ZipDeploy API....target: {target} - site: {Resources.GetSite(site, env)} - configuration: {configuration}"); var scmPrefix = $"{Resources.GetSite(site, env)}"; var kuduApiUri = $"https://{scmPrefix}.scm.azurewebsites.net/api/zipdeploy"; Information($"Kudu URL: {kuduApiUri}"); var zipFilePath = Paths.Combine(Paths.PublishDirectory, $"{Resources.GetSite(site, env)}.zip").ToString(); Information($"Zip File Path: {zipFilePath}"); HttpClient client = null; try { client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", kuduApiAuthorizationToken); using (var stream = System.IO.File.OpenRead(zipFilePath)) { var content = new System.Net.Http.StreamContent(stream); content.Headers.Add("Content-Type", "multipart/form-data"); var response = await client.PostAsync(kuduApiUri, content); response.EnsureSuccessStatusCode(); } } catch (Exception ex) { Error($"Deploy failed: {ex.Message}"); } finally { if (client != null) client.Dispose(); } }); /////////////////////////////////////////////////////////////////////////////// // PROVISION TASKS /////////////////////////////////////////////////////////////////////////////// Task("ProvisionAuth") .Does(() => { Information("ProvisionAuth ...."); AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Paths.GetAuthFile(env)); azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(Paths.GetSubscriptionId(env)); Information("Authenticated!"); }); Task("ProvisionResourceGroup") .IsDependentOn("ProvisionAuth") .Does(() => { Information($"ProvisionResourceGroup...."); resourceGroup = azure.ResourceGroups.List().Where(r => r.Name.ToLower() == Resources.GetResourceGroup(env).ToLower()).FirstOrDefault(); if (resourceGroup == null) { resourceGroup = azure.ResourceGroups .Define(Resources.GetResourceGroup(env)) .WithRegion(Region.USEast) .Create(); Information($"Resource group: {resourceGroup.Name} created!"); } else Information($"Resource group: {resourceGroup.Name} already created!"); }); Task("ProvisionCosmos") .IsDependentOn("ProvisionResourceGroup") .Does(async () => { Information($"ProvisionCosmos...."); cosmosAccount = azure.CosmosDBAccounts.List().Where(a => a.Name.ToLower() == Resources.GetCosmosAccount(env)).FirstOrDefault(); if (cosmosAccount == null) { // NOTE: Provisiong a Cosmos Database takes a long time to be online. If you proceed with creating a database and a colection, // you will get an error that says something like `bad request` without much of an explanation. Once the account is online, you can // provision the rest (really all you have to do is restart the provision task). // The error is this: Error: One or more errors occurred. Long running operation failed with status 'BadRequest'. // The status in the portal is 'Creating' cosmosAccount = azure.CosmosDBAccounts.Define(Resources.GetCosmosAccount(env)) .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) .WithKind(DatabaseAccountKind.GlobalDocumentDB) .WithSessionConsistency() .WithWriteReplication(Region.USEast) .WithReadReplication(Region.USEast) .Create(); Information($"Cosmos Account: {cosmosAccount.Name} created!"); } else Information($"Cosmos Account: {cosmosAccount.Name} already created!"); // Get credentials for the CosmosDB. var databaseAccountListKeysResult = cosmosAccount.ListKeys(); string masterKey = databaseAccountListKeysResult.PrimaryMasterKey; string endPoint = cosmosAccount.DocumentEndpoint; // Connect to CosmosDB and add a collection DocumentClient documentClient = new DocumentClient(new System.Uri(endPoint), masterKey, ConnectionPolicy.Default, ConsistencyLevel.Session); var databases = documentClient.CreateDatabaseQuery().ToList(); var database = databases.Where(d => d.Id == Resources.GetCosmosDatabase(env)).FirstOrDefault(); if (database == null) { // Define a new database Database myDatabase = new Database(); myDatabase.Id = Resources.GetCosmosDatabase(env); myDatabase = await documentClient.CreateDatabaseAsync(myDatabase, null); Information("Created a new database"); // Define a new collection DocumentCollection myCollection = new DocumentCollection(); myCollection.Id = Resources.GetCosmosCollection(env); // Set the provisioned throughput for this collection to be 400 RUs. RequestOptions requestOptions = new RequestOptions(); requestOptions.OfferThroughput = 400; // Create a new collection. myCollection = await documentClient.CreateDocumentCollectionAsync( "dbs/" + Resources.GetCosmosDatabase(env), myCollection, requestOptions); Information("Created a new main collection"); // Define a new archive collection DocumentCollection archiveCollection = new DocumentCollection(); archiveCollection.Id = Resources.GetCosmosArchiveCollection(env); // Set the provisioned throughput for this collection to be 400 RUs. RequestOptions archiveRequestOptions = new RequestOptions(); archiveRequestOptions.OfferThroughput = 400; // Create a new collection. archiveCollection = await documentClient.CreateDocumentCollectionAsync( "dbs/" + Resources.GetCosmosDatabase(env), archiveCollection, archiveRequestOptions); Information("Created a new archive collection"); } else Information($"Cosmos Database: {Resources.GetCosmosDatabase(env)} already created!"); }); Task("ProvisionStorage") .IsDependentOn("ProvisionCosmos") .Does(() => { Information($"ProvisionStorage...."); storageAccount = azure.StorageAccounts.List().Where(r => r.Name.ToLower() == Resources.GetStorageAccount(env).ToLower()).FirstOrDefault(); if (storageAccount == null) { storageAccount = azure.StorageAccounts .Define(Resources.GetStorageAccount(env)) .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) .Create(); Information($"Storage Account: {storageAccount.Name} created with {storageAccount.Key}!"); } else Information($"Storage Account: {storageAccount.Name} already created!"); }); Task("ProvisionPlan") .IsDependentOn("ProvisionStorage") .Does(() => { Information($"ProvisionPlan...."); // NOTE: It appears I cannot create a `Consumption` based service plan for Azure Functions // Instead the first function will auto-create it...but it will be auto-named which means it will contains weird numbers in the name!! // appServicePlan = azure.AppServices.AppServicePlans.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetAppServicePlan(env).ToLower()).FirstOrDefault(); // if (appServicePlan == null) // { // appServicePlan = azure.AppServices.AppServicePlans // .Define(Resources.GetAppServicePlan(env)) // .WithRegion(Region.USEast) // .WithExistingResourceGroup(resourceGroup) // .WithPricingTier(PricingTier.StandardS1) // The pricing tier does not include `Consumption` // .WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Windows) // .Create(); // Information($"App Service Plan: {appServicePlan.Name} created!"); // } // else // Information($"App Service Plan: {appServicePlan.Name} already created!"); // Create a Web App Service Plan for the front-end webAppServicePlan = azure.AppServices.AppServicePlans.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetWebAppServicePlan(env).ToLower()).FirstOrDefault(); if (webAppServicePlan == null) { webAppServicePlan = azure.AppServices.AppServicePlans .Define(Resources.GetWebAppServicePlan(env)) .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) .WithPricingTier(PricingTier.FreeF1) .WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Windows) .Create(); Information($"App Service Plan: {webAppServicePlan.Name} created!"); } else Information($"App Service Plan: {webAppServicePlan.Name} already created!"); }); Task("ProvisionFunctionApps") .IsDependentOn("ProvisionPlan") .Does(() => { Information($"ProvisionFunctionApps...."); driversFunctionsApp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetDriversFunctionApp(env).ToLower()).FirstOrDefault(); if (driversFunctionsApp == null) { driversFunctionsApp = azure.AppServices.FunctionApps .Define(Resources.GetDriversFunctionApp(env)) .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) .WithExistingStorageAccount(storageAccount) .Create(); Information($"Functions App: {driversFunctionsApp.Name} created!"); } else Information($"Functions App: {driversFunctionsApp.Name} already created!"); appServicePlan = azure.AppServices.AppServicePlans.GetById(driversFunctionsApp.AppServicePlanId); tripsFunctionsApp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetTripsFunctionApp(env).ToLower()).FirstOrDefault(); if (tripsFunctionsApp == null) { tripsFunctionsApp = azure.AppServices.FunctionApps .Define(Resources.GetTripsFunctionApp(env)) .WithExistingAppServicePlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithExistingStorageAccount(storageAccount) .Create(); Information($"Functions App: {tripsFunctionsApp.Name} created!"); } else Information($"Functions App: {tripsFunctionsApp.Name} already created!"); passengersFunctionsApp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetPassengersFunctionApp(env).ToLower()).FirstOrDefault(); if (passengersFunctionsApp == null) { passengersFunctionsApp = azure.AppServices.FunctionApps .Define(Resources.GetPassengersFunctionApp(env)) .WithExistingAppServicePlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithExistingStorageAccount(storageAccount) .Create(); Information($"Functions App: {passengersFunctionsApp.Name} created!"); } else Information($"Functions App: {passengersFunctionsApp.Name} already created!"); orchestratorsFunctionsApp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetOrchestratorsFunctionApp(env).ToLower()).FirstOrDefault(); if (orchestratorsFunctionsApp == null) { orchestratorsFunctionsApp = azure.AppServices.FunctionApps .Define(Resources.GetOrchestratorsFunctionApp(env)) .WithExistingAppServicePlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithExistingStorageAccount(storageAccount) .Create(); Information($"Functions App: {orchestratorsFunctionsApp.Name} created!"); } else Information($"Functions App: {orchestratorsFunctionsApp.Name} already created!"); archiverFunctionsApp = azure.AppServices.FunctionApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetTripArchiverFunctionApp(env).ToLower()).FirstOrDefault(); if (archiverFunctionsApp == null) { archiverFunctionsApp = azure.AppServices.FunctionApps .Define(Resources.GetTripArchiverFunctionApp(env)) .WithExistingAppServicePlan(appServicePlan) .WithExistingResourceGroup(resourceGroup) .WithExistingStorageAccount(storageAccount) .Create(); Information($"Functions App: {archiverFunctionsApp.Name} created!"); } else Information($"Functions App: {archiverFunctionsApp.Name} already created!"); }); Task("ProvisionWebApp") .IsDependentOn("ProvisionFunctionApps") .Does(() => { Information($"ProvisionWebApp...."); webApp = azure.WebApps.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetWebAppName(env).ToLower()).FirstOrDefault(); if (webApp == null) { webApp = azure.WebApps .Define(Resources.GetWebAppName(env)) .WithExistingWindowsPlan(webAppServicePlan) .WithExistingResourceGroup(resourceGroup) .Create(); Information($"Web App: {webApp.Name} created!"); } else Information($"Web App: {webApp.Name} already created!"); }); Task("ProvisionSql") .IsDependentOn("ProvisionWebApp") .Does(() => { Information($"ProvisionSql...."); sqlDatabaseServer = azure.SqlServers.ListByResourceGroup(resourceGroup.Name).Where(r => r.Name.ToLower() == Resources.GetSqlDatabaseServerName(env).ToLower()).FirstOrDefault(); if (sqlDatabaseServer == null) { sqlDatabaseServer = azure.SqlServers .Define(Resources.GetSqlDatabaseServerName(env)) .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) .WithAdministratorLogin(Resources.SqlDatabaseServerAdminLogin) .WithAdministratorPassword(Resources.SqlDatabaseServerAdminPwd) .Create(); Information($"SQL Server: {sqlDatabaseServer.Name} created!"); } else Information($"SQL Server: {sqlDatabaseServer.Name} already created!"); sqlDatabase = sqlDatabaseServer.Databases.List().Where(r => r.Name.ToLower() == Resources.GetSqlDatabaseName(env).ToLower()).FirstOrDefault(); if (sqlDatabase == null) { sqlDatabase = sqlDatabaseServer.Databases .Define(Resources.GetSqlDatabaseName(env)) .Create(); Information($"SQL Server Database: {sqlDatabase.Name} created!"); } else Information($"SQL Server Database: {sqlDatabase.Name} already created!"); }); Task("ProvisionEventGrid") .IsDependentOn("ProvisionSql") .Does(() => { Information($"ProvisionEventGrid...."); // Unfortunately Event Grids cannot be provisioned using the fluent management APIs yet!! }); Task("ProvisionLogicApp") .IsDependentOn("ProvisionEventGrid") .Does(() => { Information($"ProvisionLogicApp...."); // Unfortunately Logic Apps cannot be provisioned using the fluent management APIs yet!! }); Task("ProvisionAppInsights") .IsDependentOn("ProvisionLogicApp") .Does(() => { Information($"ProvisionAppInsights...."); // Unfortunately Application Insights cannot be provisioned using the fluent management APIs yet!! }); Task("Provision") .IsDependentOn("ProvisionAppInsights") .Does(() => { Information($"Provision...."); // Update the functions app code }); /////////////////////////////////////////////////////////////////////////////// // DE-PROVISION TASKS /////////////////////////////////////////////////////////////////////////////// Task("Deprovision") .IsDependentOn("ProvisionAuth") .Does(() => { Information($"Deprovision...."); // NOTE: This takes forever...like 8-10 minutes...so be patient :-) azure.ResourceGroups.DeleteByName(Resources.GetResourceGroup(env)); }); /////////////////////////////////////////////////////////////////////////////// // BOOTSTRAP /////////////////////////////////////////////////////////////////////////////// RunTarget(target); // Sample Provision PowerShell commands: // ./build.ps1 -Target Provision -ScriptArgs '--Env=Prod' // ./build.ps1 -Target Provision -ScriptArgs '--Env=Dev' // ./build.ps1 -Target Deprovision -ScriptArgs '--Env=Prod' // ./build.ps1 -Target Deprovision -ScriptArgs '--Env=Dev' // Sample Deploy PowerShell commands: // ./build.ps1 -Target Deploy -Configuration Debug -ScriptArgs '--Site=Drivers','--App=ServerlessMicroservices.FunctionApp.Drivers','--Env=Dev' // ./build.ps1 -Target Deploy -Configuration Debug -ScriptArgs '--Site=Orchestrators','--App=ServerlessMicroservices.FunctionApp.Orchestrators','--Env=Dev' // ./build.ps1 -Target Deploy -Configuration Debug -ScriptArgs '--Site=Trips','--App=ServerlessMicroservices.FunctionApp.Trips','--Env=Dev' // ./build.ps1 -Target Deploy -Configuration Debug -ScriptArgs '--Site=Passengers','--App=ServerlessMicroservices.FunctionApp.Passengers','--Env=Dev' // ./build.ps1 -Target ImportAppSettings -ScriptArgs '--Site=Drivers','--App=ServerlessMicroservices.FunctionApp.Drivers','--Env=Dev' // ./build.ps1 -Target ImportAppSettings -ScriptArgs '--Site=Orchestrators','--App=ServerlessMicroservices.FunctionApp.Orchestrators','--Env=Dev' // ./build.ps1 -Target ImportAppSettings -ScriptArgs '--Site=Trips','--App=ServerlessMicroservices.FunctionApp.Trips','--Env=Dev' // ./build.ps1 -Target ImportAppSettings -ScriptArgs '--Site=Passengers','--App=ServerlessMicroservices.FunctionApp.Passengers','--Env=Dev' // Bootstrapping configuration via cake.config
the_stack
const string SOLUTION = "testcentric-gui.sln"; const string NUGET_ID = "TestCentric.GuiRunner"; const string CHOCO_ID = "testcentric-gui-runner"; const string GITHUB_OWNER = "testcentric"; const string GITHUB_REPO = "testcentric-gui"; const string DEFAULT_VERSION = "2.0.0"; const string DEFAULT_CONFIGURATION = "Release"; // NOTE: This must match what is actually referenced by // the GUI test model project. Hopefully, this is a temporary // fix, which we can get rid of in the future. const string REF_ENGINE_VERSION = "2.0.0-dev00014"; const string PACKAGE_NAME = "testcentric-gui"; const string NUGET_PACKAGE_NAME = "TestCentric.GuiRunner"; const string GUI_RUNNER = "testcentric.exe"; const string GUI_TESTS = "*.Tests.dll"; // Load scripts after defining constants #load "./cake/parameters.cake" using System.Xml; using System.Text.RegularExpressions; using System.Reflection; using System.Threading.Tasks; ////////////////////////////////////////////////////////////////////// // SETUP AND TEARDOWN ////////////////////////////////////////////////////////////////////// Setup<BuildParameters>((context) => { var parameters = BuildParameters.Create(context); if (BuildSystem.IsRunningOnAppVeyor) AppVeyor.UpdateBuildVersion(parameters.PackageVersion + "-" + AppVeyor.Environment.Build.Number); Information("Building {0} version {1} of TestCentric GUI.", parameters.Configuration, parameters.PackageVersion); return parameters; }); // If we run target Test, we catch errors here in teardown. // If we run packaging, the CheckTestErrors Task is run instead. Teardown(context => CheckTestErrors(ref ErrorDetail)); ////////////////////////////////////////////////////////////////////// // DUMP SETTINGS ////////////////////////////////////////////////////////////////////// Task("DumpSettings") .Does<BuildParameters>((parameters) => { parameters.DumpSettings(); }); ////////////////////////////////////////////////////////////////////// // CLEAN ////////////////////////////////////////////////////////////////////// Task("Clean") .Does<BuildParameters>((parameters) => { Information("Cleaning " + parameters.OutputDirectory); CleanDirectory(parameters.OutputDirectory); }); ////////////////////////////////////////////////////////////////////// // RESTORE NUGET PACKAGES ////////////////////////////////////////////////////////////////////// Task("RestorePackages") .Does<BuildParameters>((parameters) => { NuGetRestore(SOLUTION, parameters.RestoreSettings); }); ////////////////////////////////////////////////////////////////////// // BUILD ////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .IsDependentOn("RestorePackages") .IsDependentOn("CheckHeaders") .Does<BuildParameters>((parameters) => { MSBuild(SOLUTION, parameters.MSBuildSettings.WithProperty("Version", parameters.PackageVersion)); // The package does not restore correctly. As a temporary // fix, we install a local copy and then copy agents and // content to the output directory. CleanDirectory(parameters.NuGetTestDirectory); NuGetInstall("TestCentric.Engine", new NuGetInstallSettings() { Version = REF_ENGINE_VERSION, OutputDirectory = parameters.NuGetTestDirectory, ExcludeVersion = true }); CopyFileToDirectory( parameters.NuGetTestDirectory + "TestCentric.Engine/content/testcentric.nuget.addins", parameters.OutputDirectory); CopyDirectory( parameters.NuGetTestDirectory + "TestCentric.Engine/agents", parameters.OutputDirectory + "agents"); }); ////////////////////////////////////////////////////////////////////// // TESTS ////////////////////////////////////////////////////////////////////// static var ErrorDetail = new List<string>(); Task("CheckTestErrors") .Description("Checks for errors running the test suites") .Does(() => CheckTestErrors(ref ErrorDetail)); ////////////////////////////////////////////////////////////////////// // TESTS OF THE GUI ////////////////////////////////////////////////////////////////////// Task("Test") .IsDependentOn("Build") .Does<BuildParameters>((parameters) => { var guiTests = GetFiles(parameters.OutputDirectory + GUI_TESTS); var args = new StringBuilder(); foreach (var test in guiTests) args.Append($"\"{test}\" "); var guiTester = new GuiTester(parameters); guiTester.RunGuiUnattended(parameters.OutputDirectory + GUI_RUNNER, args.ToString()); var result = new ActualResult(parameters.OutputDirectory + "TestResult.xml"); new ConsoleReporter(result).Display(); if (result.OverallResult == "Failed") throw new System.Exception("There were test failures or errors. See listing."); }); //////////////////////////////////////////////////////////////////// // PACKAGING ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // ZIP PACKAGE ////////////////////////////////////////////////////////////////////// Task("BuildZipPackage") .Does<BuildParameters>((parameters) => { Information("Creating Zip Image Directory"); CreateDirectory(parameters.PackageDirectory); CreateZipImage(parameters); Information("Creating package " + parameters.ZipPackageName); var zipFiles = GetFiles(parameters.ZipImageDirectory + "**/*.*"); Zip(parameters.ZipImageDirectory, parameters.ZipPackage, zipFiles); }); Task("InstallZipPackage") .Does<BuildParameters>((parameters) => { CleanDirectory(parameters.ZipTestDirectory); Unzip(parameters.ZipPackage, parameters.ZipTestDirectory); Information($"Unzipped {parameters.ZipPackageName} to { parameters.ZipTestDirectory}"); }); Task("VerifyZipPackage") .IsDependentOn("InstallZipPackage") .Does<BuildParameters>((parameters) => { Check.That(parameters.ZipTestDirectory, HasFiles("CHANGES.txt", "LICENSE.txt", "NOTICES.txt"), HasDirectory("bin").WithFiles(GUI_FILES).AndFiles(ENGINE_FILES).AndFile("testcentric.zip.addins"), HasDirectory("bin/agents/net40").WithFiles(NET_FRAMEWORK_AGENT_FILES), HasDirectory("bin/agents/netcoreapp3.1").WithFiles(NET_CORE_AGENT_FILES), HasDirectory("bin/agents/net5.0").WithFiles(NET_CORE_AGENT_FILES), HasDirectory("bin/Images").WithFiles("DebugTests.png", "RunTests.png", "StopRun.png", "GroupBy_16x.png", "SummaryReport.png"), HasDirectory("bin/Images/Tree/Circles").WithFiles(TREE_ICONS_JPG), HasDirectory("bin/Images/Tree/Classic").WithFiles(TREE_ICONS_JPG), HasDirectory("bin/Images/Tree/Default").WithFiles(TREE_ICONS_PNG), HasDirectory("bin/Images/Tree/Visual Studio").WithFiles(TREE_ICONS_PNG)); Information("Verification was successful!"); }); Task("TestZipPackage") .IsDependentOn("InstallZipPackage") .Does<BuildParameters>((parameters) => { new ZipPackageTester(parameters).RunAllTests(); }); ////////////////////////////////////////////////////////////////////// // NUGET PACKAGE ////////////////////////////////////////////////////////////////////// Task("BuildNuGetPackage") .Does<BuildParameters>((parameters) => { CreateDirectory(parameters.PackageDirectory); Information("Creating package " + parameters.NuGetPackageName); NuGetPack($"{parameters.NuGetDirectory}/{NUGET_PACKAGE_NAME}.nuspec", new NuGetPackSettings() { Version = parameters.PackageVersion, BasePath = parameters.OutputDirectory, OutputDirectory = parameters.PackageDirectory, NoPackageAnalysis = true }); }); Task("InstallNuGetPackage") .Does<BuildParameters>((parameters) => { CleanDirectory(parameters.NuGetTestDirectory); Unzip(parameters.NuGetPackage, parameters.NuGetTestDirectory); Information($"Unzipped {parameters.NuGetPackageName} to { parameters.NuGetTestDirectory}"); }); Task("VerifyNuGetPackage") .IsDependentOn("InstallNuGetPackage") .Does<BuildParameters>((parameters) => { Check.That(parameters.NuGetTestDirectory, HasFiles("CHANGES.txt", "LICENSE.txt", "NOTICES.txt", "testcentric.png"), HasDirectory("tools").WithFiles(GUI_FILES).AndFiles(ENGINE_FILES).AndFile("testcentric.nuget.addins"), HasDirectory("tools/agents/net40").WithFiles(NET_FRAMEWORK_AGENT_FILES).AndFiles(ENGINE_CORE_FILES).AndFile("testcentric-agent.nuget.addins"), HasDirectory("tools/agents/netcoreapp3.1").WithFiles(NET_CORE_AGENT_FILES).AndFiles(ENGINE_CORE_FILES).AndFile("testcentric-agent.nuget.addins"), HasDirectory("tools/agents/net5.0").WithFiles(NET_CORE_AGENT_FILES).AndFiles(ENGINE_CORE_FILES).AndFile("testcentric-agent.nuget.addins"), HasDirectory("tools/Images").WithFiles("DebugTests.png", "RunTests.png", "StopRun.png", "GroupBy_16x.png", "SummaryReport.png"), HasDirectory("tools/Images/Tree/Circles").WithFiles(TREE_ICONS_JPG), HasDirectory("tools/Images/Tree/Classic").WithFiles(TREE_ICONS_JPG), HasDirectory("tools/Images/Tree/Default").WithFiles(TREE_ICONS_PNG), HasDirectory("tools/Images/Tree/Visual Studio").WithFiles(TREE_ICONS_PNG)); Information("Verification was successful!"); }); Task("TestNuGetPackage") .IsDependentOn("InstallNuGetPackage") .Does<BuildParameters>((parameters) => { new NuGetPackageTester(parameters).RunAllTests(); }); ////////////////////////////////////////////////////////////////////// // CHOCOLATEY PACKAGE ////////////////////////////////////////////////////////////////////// Task("BuildChocolateyPackage") .WithCriteria(IsRunningOnWindows()) .Does<BuildParameters>((parameters) => { CreateDirectory(parameters.PackageDirectory); Information("Creating package " + parameters.ChocolateyPackageName); ChocolateyPack($"{parameters.ChocoDirectory}/{PACKAGE_NAME}.nuspec", new ChocolateyPackSettings() { Version = parameters.PackageVersion, WorkingDirectory = parameters.OutputDirectory, OutputDirectory = parameters.PackageDirectory, ArgumentCustomization = args => args.Append($"BIN={parameters.OutputDirectory}") }); }); Task("InstallChocolateyPackage") .Does<BuildParameters>((parameters) => { CleanDirectory(parameters.ChocolateyTestDirectory); Unzip(parameters.ChocolateyPackage, parameters.ChocolateyTestDirectory); Information($"Unzipped {parameters.ChocolateyPackageName} to { parameters.ChocolateyTestDirectory}"); }); Task("VerifyChocolateyPackage") .IsDependentOn("InstallChocolateyPackage") .Does<BuildParameters>((parameters) => { Check.That(parameters.ChocolateyTestDirectory, HasDirectory("tools").WithFiles("CHANGES.txt", "LICENSE.txt", "NOTICES.txt", "VERIFICATION.txt", "testcentric.choco.addins").AndFiles(GUI_FILES).AndFiles(ENGINE_FILES).AndFile("testcentric.choco.addins"), HasDirectory("tools/agents/net40").WithFiles(NET_FRAMEWORK_AGENT_FILES).AndFile("testcentric-agent.choco.addins"), HasDirectory("tools/agents/netcoreapp3.1").WithFiles(NET_CORE_AGENT_FILES).AndFile("testcentric-agent.choco.addins"), HasDirectory("tools/agents/net5.0").WithFiles(NET_CORE_AGENT_FILES).AndFile("testcentric-agent.choco.addins"), HasDirectory("tools/Images").WithFiles("DebugTests.png", "RunTests.png", "StopRun.png", "GroupBy_16x.png", "SummaryReport.png"), HasDirectory("tools/Images/Tree/Circles").WithFiles(TREE_ICONS_JPG), HasDirectory("tools/Images/Tree/Classic").WithFiles(TREE_ICONS_JPG), HasDirectory("tools/Images/Tree/Default").WithFiles(TREE_ICONS_PNG), HasDirectory("tools/Images/Tree/Visual%20Studio").WithFiles(TREE_ICONS_PNG)); Information("Verification was successful!"); }); Task("TestChocolateyPackage") .IsDependentOn("InstallChocolateyPackage") .WithCriteria(IsRunningOnWindows()) .Does<BuildParameters>((parameters) => { new ChocolateyPackageTester(parameters).RunAllTests(); }); ////////////////////////////////////////////////////////////////////// // ENGINE CORE PACKAGE ////////////////////////////////////////////////////////////////////// // NOTE: The testcentric.engine.core assembly and its dependencies are // included in all the main packages. It is also published separately // as a nuget package for use in creating pluggable agents and for any // other projects, which may want to make use of it. Task("BuildEngineCorePackage") .Does<BuildParameters>((parameters) => { NuGetPack($"{parameters.NuGetDirectory}/TestCentric.Engine.Core.nuspec", new NuGetPackSettings() { Version = parameters.PackageVersion, OutputDirectory = parameters.PackageDirectory, NoPackageAnalysis = true }); }); ////////////////////////////////////////////////////////////////////// // ENGINE API PACKAGE ////////////////////////////////////////////////////////////////////// Task("BuildEngineApiPackage") .Does<BuildParameters>((parameters) => { NuGetPack($"{parameters.NuGetDirectory}/TestCentric.Engine.Api.nuspec", new NuGetPackSettings() { Version = parameters.PackageVersion, OutputDirectory = parameters.PackageDirectory, NoPackageAnalysis = true }); }); ////////////////////////////////////////////////////////////////////// // PUBLISH PACKAGES ////////////////////////////////////////////////////////////////////// static bool hadPublishingErrors = false; Task("PublishPackages") .Description("Publish nuget and chocolatey packages according to the current settings") .IsDependentOn("PublishToMyGet") .IsDependentOn("PublishToNuGet") .IsDependentOn("PublishToChocolatey") .Does(() => { if (hadPublishingErrors) throw new Exception("One of the publishing steps failed."); }); // This task may either be run by the PublishPackages task, // which depends on it, or directly when recovering from errors. Task("PublishToMyGet") .Description("Publish packages to MyGet") .Does<BuildParameters>((parameters) => { if (!parameters.ShouldPublishToMyGet) Information("Nothing to publish to MyGet from this run."); else try { PushNuGetPackage(parameters.NuGetPackage, parameters.MyGetApiKey, parameters.MyGetPushUrl); PushChocolateyPackage(parameters.ChocolateyPackage, parameters.MyGetApiKey, parameters.MyGetPushUrl); } catch(Exception) { hadPublishingErrors = true; } }); // This task may either be run by the PublishPackages task, // which depends on it, or directly when recovering from errors. Task("PublishToNuGet") .Description("Publish packages to NuGet") .Does<BuildParameters>((parameters) => { if (!parameters.ShouldPublishToNuGet) Information("Nothing to publish to NuGet from this run."); else try { PushNuGetPackage(parameters.NuGetPackage, parameters.NuGetApiKey, parameters.NuGetPushUrl); } catch(Exception) { hadPublishingErrors = true; } }); // This task may either be run by the PublishPackages task, // which depends on it, or directly when recovering from errors. Task("PublishToChocolatey") .Description("Publish packages to Chocolatey") .Does<BuildParameters>((parameters) => { if (!parameters.ShouldPublishToChocolatey) Information("Nothing to publish to Chocolatey from this run."); else try { PushChocolateyPackage(parameters.ChocolateyPackage, parameters.ChocolateyApiKey, parameters.ChocolateyPushUrl); } catch(Exception) { hadPublishingErrors = true; } }); ////////////////////////////////////////////////////////////////////// // CREATE A DRAFT RELEASE ////////////////////////////////////////////////////////////////////// Task("CreateDraftRelease") .Does<BuildParameters>((parameters) => { if (parameters.IsReleaseBranch) { // Exit if any PackageTests failed CheckTestErrors(ref ErrorDetail); // NOTE: Since this is a release branch, the pre-release label // is "pre", which we don't want to use for the draft release. // The branch name contains the full information to be used // for both the name of the draft release and the milestone, // i.e. release-2.0.0, release-2.0.0-beta2, etc. string milestone = parameters.BranchName.Substring(8); string releaseName = $"TestCentric {milestone}"; Information($"Creating draft release for {releaseName}"); try { GitReleaseManagerCreate(parameters.GitHubAccessToken, GITHUB_OWNER, GITHUB_REPO, new GitReleaseManagerCreateSettings() { Name = releaseName, Milestone = milestone }); } catch { Error($"Unable to create draft release for {releaseName}."); Error($"Check that there is a {milestone} milestone with at least one closed issue."); Error(""); throw; } } else { Information("Skipping Release creation because this is not a release branch"); } }); ////////////////////////////////////////////////////////////////////// // CREATE A PRODUCTION RELEASE ////////////////////////////////////////////////////////////////////// Task("CreateProductionRelease") .Does<BuildParameters>((parameters) => { if (parameters.IsProductionRelease) { // Exit if any PackageTests failed CheckTestErrors(ref ErrorDetail); string token = parameters.GitHubAccessToken; string tagName = parameters.PackageVersion; string assets = parameters.GitHubReleaseAssets; Information($"Publishing release {tagName} to GitHub"); GitReleaseManagerAddAssets(token, GITHUB_OWNER, GITHUB_REPO, tagName, assets); GitReleaseManagerClose(token, GITHUB_OWNER, GITHUB_REPO, tagName); } else { Information("Skipping CreateProductionRelease because this is not a production release"); } }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Package") .IsDependentOn("Build") .IsDependentOn("PackageZip") .IsDependentOn("PackageNuGet") .IsDependentOn("PackageChocolatey"); Task("PackageZip") .IsDependentOn("BuildZipPackage") .IsDependentOn("VerifyZipPackage") .IsDependentOn("TestZipPackage"); Task("PackageNuGet") .IsDependentOn("BuildNuGetPackage") .IsDependentOn("VerifyNuGetPackage") .IsDependentOn("TestNuGetPackage"); Task("PackageChocolatey") .IsDependentOn("BuildChocolateyPackage") .IsDependentOn("VerifyChocolateyPackage") .IsDependentOn("TestChocolateyPackage"); Task("AppVeyor") .IsDependentOn("DumpSettings") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Package") .IsDependentOn("PublishPackages") .IsDependentOn("CreateDraftRelease") .IsDependentOn("CreateProductionRelease"); Task("Travis") .IsDependentOn("Build") .IsDependentOn("Test"); Task("Full") .IsDependentOn("DumpSettings") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Package"); Task("Default") .IsDependentOn("Build"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(Argument("target", "Default"));
the_stack
#load "poco.cake" #load "poco.yaml.cake" // #load "poco.xml.cake" using System.Linq; using YamlDotNet.Core; using YamlDotNet.Serialization; using Newtonsoft.Json; var TARGET = Argument ("target", Argument ("t", Argument ("Target", "build"))); var COMPONENT_NAME = Argument ("component-name", Argument ("cn", Argument ("Component-name", ""))); var COMPONENT_VERSION = Argument ("component-version", Argument ("cv", Argument ("Component-version", ""))); var BUMP_DEPENDENTS = Argument ("bump-dependents", Argument ("bd", false)); // Creates a dictionary of components available in repo that are not deprecated. public Dictionary<string, GoogleBase> CreateComponents () { var googleComponents = new Dictionary<string, GoogleBase> (); googleComponents ["Firebase.ABTesting"] = GetComponent<Firebase.ABTesting> (); googleComponents ["Firebase.AdMob"] = GetComponent<Firebase.AdMob> (); googleComponents ["Firebase.Analytics"] = GetComponent<Firebase.Analytics> (); googleComponents ["Firebase.Auth"] = GetComponent<Firebase.Auth> (); googleComponents ["Firebase.CloudFirestore"] = GetComponent<Firebase.CloudFirestore> (); googleComponents ["Firebase.CloudMessaging"] = GetComponent<Firebase.CloudMessaging> (); googleComponents ["Firebase.Core"] = GetComponent<Firebase.Core> (); googleComponents ["Firebase.Crashlytics"] = GetComponent<Firebase.Crashlytics> (); googleComponents ["Firebase.CrashReporting"] = GetComponent<Firebase.CrashReporting> (); googleComponents ["Firebase.Database"] = GetComponent<Firebase.Database> (); googleComponents ["Firebase.DynamicLinks"] = GetComponent<Firebase.DynamicLinks> (); googleComponents ["Firebase.CloudFunctions"] = GetComponent<Firebase.CloudFunctions> (); googleComponents ["Firebase.InstanceID"] = GetComponent<Firebase.InstanceID> (); googleComponents ["Firebase.Invites"] = GetComponent<Firebase.Invites> (); googleComponents ["Firebase.MLKit"] = GetComponent<Firebase.MLKit> (); googleComponents ["Firebase.MLKit.Common"] = GetComponent<Firebase.MLKit.Common> (); googleComponents ["Firebase.MLKit.ModelInterpreter"] = GetComponent<Firebase.MLKit.ModelInterpreter> (); googleComponents ["Firebase.PerformanceMonitoring"] = GetComponent<Firebase.PerformanceMonitoring> (); googleComponents ["Firebase.RemoteConfig"] = GetComponent<Firebase.RemoteConfig> (); googleComponents ["Firebase.Storage"] = GetComponent<Firebase.Storage> (); googleComponents ["Google.Analytics"] = GetComponent<Google.Analytics> (); googleComponents ["Google.AppIndexing"] = GetComponent<Google.AppIndexing> (); googleComponents ["Google.Cast"] = GetComponent<Google.Cast> (); googleComponents ["Google.Core"] = GetComponent<Google.Core> (); googleComponents ["Google.InstanceID"] = GetComponent<Google.InstanceID> (); googleComponents ["Google.Maps"] = GetComponent<Google.Maps> (); googleComponents ["Google.MobileAds"] = GetComponent<Google.MobileAds> (); googleComponents ["Google.Places"] = GetComponent<Google.Places> (); googleComponents ["Google.PlayGames"] = GetComponent<Google.PlayGames> (); googleComponents ["Google.SignIn"] = GetComponent<Google.SignIn> (); googleComponents ["Google.TagManager"] = GetComponent<Google.TagManager> (); googleComponents ["Xamarin.Build.Download"] = GetComponent<Xamarin.Build.Download> (); return googleComponents; } // Gets a component with its basic information. public T GetComponent<T> () where T : GoogleBase, new () { T component = new T (); FilePath nuspecPath = null; // XBD doesn't have its own .nuspec file, we need to get // the XBD version from one of the Firebase/Google .nuspec files. // Get the version with XPath. if (component is Xamarin.Build.Download) { nuspecPath = GetFiles ($"./Firebase.Core/nuget/*.nuspec").ToList () [0]; component.CurrentVersion = XmlPeek (nuspecPath, "/package/metadata/dependencies/group[@targetFramework='Xamarin.iOS10']/dependency[@id='Xamarin.Build.Download']/@version"); } else { nuspecPath = GetFiles ($"./{component.Name}/nuget/*.nuspec").ToList () [0]; component.CurrentVersion = XmlPeek (nuspecPath, "/package/metadata/version/text()"); } // Create the bumped version, in case we need to use it, // by incresing by one the last digit. var versionParts = component.CurrentVersion.Split ('.'); var lastIndex = versionParts.Length - 1; versionParts [lastIndex] = (int.Parse (versionParts [lastIndex]) + 1).ToString (); component.NewVersion = string.Join (".", versionParts); return component; } // Updates versions inside of the component.yaml of the desired component public void UpdateYamlVersions (GoogleBase component) { var yamlPath = new FilePath ($"./{component.Name}/component/component.yaml"); // Some components doesn't have a component.yaml file if (!FileExists (yamlPath)) return; Information ($"Updating version in component.yaml file of {component.Name} component."); // Deserialize the component.yaml into an object var componentData = DeserializeYamlFromFile<Component> (yamlPath); // Update the main version of component.yaml componentData.Version = component.NewVersion; // Update the NuGet package version of component.yaml var parts = componentData.Packages.iOSUnifiedPaths [0].Split ('='); parts [1] = component.NewVersion; componentData.Packages.iOSUnifiedPaths [0] = string.Join ("=", parts); // Serialize the object into component.yaml file SerializeYamlToFile (yamlPath, componentData); } // Updates the main version of the .nuspec file of desired component public void UpdateNuspecMainVersion (GoogleBase component) { // XBD doesn't have its own .nuspec file, so, // we cannot update a main version of .nuspec file. if (component is Xamarin.Build.Download) return; Information ($"Updating main version in .nuspec file of {component.Name} component.\n"); // There is just one .nuspec file per component, // so we are safe to call the first result. var nuspecPath = GetFiles ($"./{component.Name}/nuget/*.nuspec").ToList () [0]; XmlPoke (nuspecPath, "/package/metadata/version", component.NewVersion); } // Updates the dependency version of the .nuspec file on dependent components public void UpdateNuspecDependencyVersion (GoogleBase component) { foreach (var name in component.BaseOf) { Information ($"Updating {component.Name} dependency version in .nuspec file of {name} component."); // There is just one .nuspec file per component, // so we are safe to call the first result. var nuspecPath = GetFiles ($"./{name}/nuget/*.nuspec").ToList () [0]; var result = XmlPeek (nuspecPath, $"/package/metadata/dependencies/group[@targetFramework='Xamarin.iOS10']/dependency[@id='{component.NuGetId}']/@version"); if (!string.IsNullOrWhiteSpace (result)) XmlPoke (nuspecPath, $"/package/metadata/dependencies/group[@targetFramework='Xamarin.iOS10']/dependency[@id='{component.NuGetId}']/@version", component.NewVersion); } } // This method is only called if we are updating XBD // Updates XBD's version in all packages.config files of component's samples public void UpdateSamplesPackagesConfigVersion (GoogleBase component) { foreach (var name in component.BaseOf) { // A component could have more than one sample, so, // we need to iterate through all of sample's packages.config var packagesPaths = GetFiles ($"./{name}/samples/**/packages.config"); foreach (var packagePath in packagesPaths) { Information ($"Updating {component.Name} version in packages.config file of {name} sample component."); XmlPoke (packagePath, $"/packages/package[@id='{component.Name}']/@version", component.NewVersion); } } } // This method is only called if we are updating XBD // Updates XBD's version in all .csproj files of component's samples public void UpdateCsprojVersion (GoogleBase component) { // Xml .csproj has Namespaces, we need to pass the namespaces // to XPath to be able to find the desired node. var xmlPeekSettings = new XmlPeekSettings { Namespaces = new Dictionary<string, string> { { "Project", "http://schemas.microsoft.com/developer/msbuild/2003" } } }; var xmlPokeSettings = new XmlPokeSettings { Namespaces = new Dictionary<string, string> { { "Project", "http://schemas.microsoft.com/developer/msbuild/2003" } } }; foreach (var name in component.BaseOf) { // A component could have more than one sample, so, // we need to iterate through all of sample's .csproj var csprojPaths = GetFiles ($"./{name}/samples/**/*.csproj"); foreach (var csprojPath in csprojPaths) { Information ($"Updating {component.Name} version in .csproj file of {name} sample component."); var result = XmlPeek (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.props')]/@Project", xmlPeekSettings); var parts = result.Split (new [] { component.CurrentVersion }, StringSplitOptions.RemoveEmptyEntries); var newValue = string.Join (component.NewVersion, parts); XmlPoke (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.props')]/@Project", newValue, xmlPokeSettings); result = XmlPeek (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.props')]/@Condition", xmlPeekSettings); parts = result.Split (new [] { component.CurrentVersion }, StringSplitOptions.RemoveEmptyEntries); newValue = string.Join (component.NewVersion, parts); XmlPoke (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.props')]/@Condition", newValue, xmlPokeSettings); result = XmlPeek (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.targets')]/@Project", xmlPeekSettings); parts = result.Split (new [] { component.CurrentVersion }, StringSplitOptions.RemoveEmptyEntries); newValue = string.Join (component.NewVersion, parts); XmlPoke (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.targets')]/@Project", newValue, xmlPokeSettings); result = XmlPeek (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.targets')]/@Condition", xmlPeekSettings); parts = result.Split (new [] { component.CurrentVersion }, StringSplitOptions.RemoveEmptyEntries); newValue = string.Join (component.NewVersion, parts); XmlPoke (csprojPath, $"/Project:Project/Project:Import[contains(@Project, '{component.Name}.targets')]/@Condition", newValue, xmlPokeSettings); } } } public void UpdateComponentVersion (Dictionary<string, GoogleBase> components, string componentName, bool bumpDependents) { var message = $"Working on {componentName} component"; Information ($"{new string ('/', message.Length + 6)}"); Information ($"// {message} //"); Information ($"{new string ('/', message.Length + 6)}\n"); var component = components [componentName]; UpdateYamlVersions (component); UpdateNuspecMainVersion (component); UpdateNuspecDependencyVersion (component); if (component is Xamarin.Build.Download) { UpdateSamplesPackagesConfigVersion (component); UpdateCsprojVersion (component); } if (!bumpDependents) return; Information ($"\nBUMP_DEPENDENTS was set to true! Starting bumping {component.Name} dependent components due {component.Name} version update..."); foreach (var name in component.BaseOf) { var dependentComponent = components [name]; dependentComponent.Bumped = true; Information ($"\nBumping {dependentComponent.Name} component from version {dependentComponent.CurrentVersion} to {dependentComponent.NewVersion}...\n"); UpdateComponentVersion (components, name, false); } } Task ("build").Does (() => { if (string.IsNullOrWhiteSpace (COMPONENT_NAME)) throw new CakeException ("COMPONENT_NAME You must to specify a Component Name to update with -cn | --component-name | --Component-name."); if (string.IsNullOrWhiteSpace (COMPONENT_VERSION)) throw new CakeException ("COMPONENT_VERSION You must to specify the new Component version with -cv | --component-version | --Component-version."); var components = CreateComponents(); var updatedComponent = components [COMPONENT_NAME]; updatedComponent.NewVersion = COMPONENT_VERSION; Information ($"Component to updated: {updatedComponent.Name} {updatedComponent.CurrentVersion} => {updatedComponent.NewVersion}\n"); UpdateComponentVersion (components, COMPONENT_NAME, BUMP_DEPENDENTS); components.Remove (updatedComponent.Name); Information ($"Component updated: {updatedComponent.Name} {updatedComponent.CurrentVersion} => {updatedComponent.NewVersion}\n"); Information ("List of bumped components due update:"); foreach (var pair in components) if (pair.Value.Bumped) Information ($"{pair.Key,-31}{pair.Value.CurrentVersion,-11}=>{"",-3}{pair.Value.NewVersion}"); }); Task ("Default").IsDependentOn ("build"); RunTarget (TARGET); // public T DeserializeXmlFromFile<T> (FilePath filename) // { // T result = default (T); // // var serializer = new System.Xml.XmlSerializer (typeof (T)); // // A FileStream is needed to read the XML document. // using (FileStream fileStream = new FileStream (filename.FullPath, FileMode.Open)) { // var reader = XmlReader.Create (fileStream); // // result = (T)serializer.Deserialize (reader); // } // return result; // } // public void SerializeXmlToFile<T> (FilePath filename, T instance) // { // var serializer = new XmlSerializer (typeof (T)); // var namespace = new XmlSerializerNamespaces (); // namespace.Add ("", ""); // using (var textWriter = new StreamWriter (nuspec)) // serializer.Serialize (textWriter, instance, namespace); // } // public void AddNuGetCommentToFilesNode (FilePath filename) // { // XDocument xml = null; // using (FileStream fileStream = new FileStream (filename.FullPath, FileMode.Open)) // xml = XDocument.Load (fileStream); // var filesNode = xml.Root.Element ("files"); // foreach (var fileNode in filesNode.Elements ()) { // if (!fileNode.Attribute ("target").Value.EndsWith ("targets", StringComparison.CurrentCulture)) // continue; // fileNode.AddBeforeSelf (new XComment ("Add targets file for external native reference download")); // break; // } // using (TextWriter textWriter = new NoEncodingStreamWriter (nuspec)) // xml.Save (tw); // }
the_stack
@model Kahla.Home.Models.HomeViewModels.IndexViewModel @{ if (Model.IsProduction) { ViewBag.Title = "Kahla App"; } else { ViewBag.Title = "Kahla App Staging"; } ViewBag.Des = Localizer["As a cross-platform business messaging app, Kahla can encrypt communications at any location, on any device. And it is completely open source and free."].Value; var requestCultureFeature = Context.Features.Get<IRequestCultureFeature>(); if (requestCultureFeature == null) { return; } var requestCulture = requestCultureFeature.RequestCulture.UICulture.IetfLanguageTag; var isChineseUser = requestCulture.ToLower().Trim() == "zh"; var blockMainlandChineseUser = Configuration["BlockMainlandChineseUser"] == true.ToString(); } <vc:kahla-nav is-production="@Model.IsProduction"></vc:kahla-nav> <div class="hero pt-6 text-center"> <div class="container-new px-3"> <h1 class="f00-light text-white"> @if (Model.IsProduction) { @Localizer["Kahla - Connect everyone's thoughts"] } else { @Localizer["Kahla - Staging"] } </h1> @if (!Model.IsProduction) { <div class="container alert alert-danger alert-dismissible mt-3" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">x</span></button> <strong>Unstable version!</strong> <p>Kahla Staging is our internal test version. We can not ensure all your data is safe! The app you see is very unstable and may crash frequently!</p> </div> } <p class="col-md-8 mx-auto mb-4 f3-light"> @ViewBag.Des </p> <p> @if (Model.AppLatestVersion == Model.CLILatestVersion && Model.AppLatestVersion == Model.SDKLatestVersion) { @Localizer["Latest version:"] <kbd data-href="@Configuration["GitHubAddress"]">@Model.SDKLatestVersion</kbd> } else { @Localizer["App Latest version:"] <kbd>@Model.AppLatestVersion</kbd> @Localizer["CLI Latest version:"] <kbd>@Model.CLILatestVersion</kbd> @Localizer["SDK Latest version:"] <kbd>@Model.SDKLatestVersion</kbd> } </p> @if (isChineseUser && blockMainlandChineseUser) { <p class="text-danger">很抱歉,卡拉不为中国大陆用户提供服务。<a href="http://www.cac.gov.cn/2019-04/16/c_1124373996.htm" target="_blank">为什么?</a></p> } else { <p> <a asp-controller="Home" asp-action="PlatformSupport">View platform support status</a> </p> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="#" data-toggle="modal" data-target="#downloadModal">@Localizer["Download"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple d-none d-md-inline" href="#" data-toggle="modal" data-target="#openModal">@Localizer["Open in browser"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple d-md-none" href="@Html.Raw(Model.KahlaWebPath)">@Localizer["Open in browser"]</a> <p> @Localizer["By downloading, you agree to the"] <a href="@($"{ServiceLocation.WWW}{Values.TermsAfterWWW}")">@Localizer["license agreement"]</a>@Localizer["."] </p> } <div class="d-block d-md-none width-fit mx-auto mt-6 mb-6"> <img style="width:100%;max-width:640px;" src="@ServiceLocation.UI/images/kahla-demo.png" class="app-screenshot" /> </div> <div class="d-block d-none d-md-inline"> <img style="width:100%;max-width:1140px;" src="@ServiceLocation.UI/images/kahla-demo-wide.png" class="app-screenshot" /> </div> </div> </div> @if (Model.IsProduction) { <div class="container-new px-3 text-center"> <h2 class="f0-light mb-3 text-white"> @Localizer["Ready to choose Kahla?"] </h2> <div class="d-md-flex flex-md-row col-xl-10 mx-auto text-white-75 f4 gut-lg"> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-university"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Business level"] </h2> <p> @Localizer["Kahla is designed for commercial use. the service can be deployed inside your company and access to the full functionality of Kahla without internet."] </p> </div> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-tv"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Cross-platform"] </h2> <p> @Localizer["Kahla faced almost all mobile and desktop platforms. Use only one app for quick access by any customer. Kahla also supports open in browser without installation."] </p> </div> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-lock"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Highly secure"] </h2> <p> @Localizer["Kahla supports end-to-end encrypted message communication and supports the automatic destruction of messages. Even if you don't trust Kahla's server, you can safely deliver secrets."] </p> </div> </div> <div class="d-md-flex flex-md-row col-xl-10 mx-auto text-white-75 f4 gut-lg"> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-gift"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Always free"] </h2> <p> @Localizer["Kahla is an open source project supported by grants and donations. There is no ad, no affiliate marketer, no creepy tracking. Just for a fast, simple, and secure messaging experience."] </p> </div> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-server"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Large amount"] </h2> <p> @Localizer["Kahla provides extremely large storage space for free. Files can remain on the server for up to 100 days. And messages can retain up to 20,000 per conversation and never lose."] </p> </div> <div class="col-sm-10 mx-auto col-md-4 my-5 my-md-3"> <i class="fas fa-3x fa-code-branch"></i> <h2 class="f2-light my-2 text-white lh-condensed"> @Localizer["Open development"] </h2> <p> @Localizer["Kahla opens all of its APIs to the public for free. Whether it's building notifier, open account or chatbots, Kahla makes the process extremely easy."] </p> </div> </div> <a class="btn btn-outline-white f4 mb-6 ml-3" href="@Configuration["GitHubAddress"]"> <i class="fab fa-fw fa-github"></i> @Localizer["View on GitHub"] </a> @if (isChineseUser && blockMainlandChineseUser) { <p class="text-danger">很抱歉,由于您所在地区政策原因,卡拉无法向您提供服务,请关闭此页。<a href="http://www.cac.gov.cn/2019-04/16/c_1124373996.htm" target="_blank">了解更多</a></p> } else { <a class="btn btn-outline-white f4 mb-6" href="#" data-toggle="modal" data-target="#downloadModal"> <i class="fas fa-download"></i> @Localizer["Download now"] </a> } <hr class="my-6 mx-auto" style="width: 100px;"> </div> } <div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="openModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body text-center"> <h4 class="text-dark mb-3 mt-3"> Version: @Model.AppLatestVersion </h4> <img src="/images/qrcode.png"> <p> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Html.Raw(Model.KahlaWebPath)" target="_blank">@Localizer["Open now"]</a> </p> </div> </div> </div> </div> <div class="modal fade" id="downloadModal" tabindex="-1" role="dialog" aria-labelledby="downloadModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header pb-0" style="border-bottom: unset!important"> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="app-tab" data-toggle="tab" href="#app" role="tab" aria-controls="app" aria-selected="true"> PC <span class="badge badge-secondary ml-1">@Model.AppLatestVersion</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="mobile-tab" data-toggle="tab" href="#mobile" role="tab" aria-controls="app" aria-selected="true"> Mobile <span class="badge badge-secondary ml-1">@Model.AppLatestVersion</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="sdk-tab" data-toggle="tab" href="#sdk" role="tab" aria-controls="app" aria-selected="true"> SDK <span class="badge badge-secondary ml-1">@Model.SDKLatestVersion</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="cli-tab" data-toggle="tab" href="#cli" role="tab" aria-controls="cli" aria-selected="false"> CLI <span class="badge badge-secondary ml-1">@Model.CLILatestVersion</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="tpy-tab" data-toggle="tab" href="#tpy" role="tab" aria-controls="tpt" aria-selected="false"> Third-party <span class="badge badge-secondary ml-1">@Model.AppLatestVersion</span> </a> </li> </ul> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body text-center" style="color:black"> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="app" role="tabpanel" aria-labelledby="app-tab"> <h3 class="mt-3">@Localizer["For Windows"]</h3> <a href='https://www.microsoft.com/en-us/p/kahla/9pc6j2lz180m'> <img src="~/images/English_get-it-from-MS_InvariantCulture_Default.png" alt='English badge' style='height: 54px;margin-right: 6px;' /> </a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaWindows/Kahla.Setup.@(Model.AppLatestVersion).exe" target="_blank">@Localizer["Installer (exe)"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaWindows/Kahla-@(Model.AppLatestVersion)-win.zip" target="_blank">@Localizer["Portable (zip)"]</a> <hr /> <h3>@Localizer["For Linux"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaLinux/kahla_@(Model.AppLatestVersion)_amd64.deb" target="_blank">@Localizer["Debian, Ubuntu (deb)"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaLinux/kahla-@(Model.AppLatestVersion).x86_64.rpm" target="_blank">@Localizer["Redhat, Fedora (rpm)"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaLinux/kahla-@(Model.AppLatestVersion).tar.gz" target="_blank">@Localizer["Others (tar.gz)"]</a> <hr /> <h3>@Localizer["For Mac OS"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.DownloadRoot/KahlaMacOS/Kahla-@(Model.AppLatestVersion).dmg" target="_blank">@Localizer["dmg"]</a> <hr /> <h3>@Localizer["For Chrome OS"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Html.Raw(Model.KahlaWebPath)" target="_blank">@Localizer["Chrome App"]</a> </div> <div class="tab-pane fade" id="mobile" role="tabpanel" aria-labelledby="mobile-tab"> <h3 class="mt-3 mb-2">@Localizer["For Windows 10 Mobile"]</h3> <a href='https://www.microsoft.com/en-us/p/kahla/9pc6j2lz180m'> <img src='https://assets.windowsphone.com/85864462-9c82-451e-9355-a3d5f874397a/English_get-it-from-MS_InvariantCulture_Default.png' alt='English badge' style='height: 54px; ' /> </a> <h3 class="mt-3">@Localizer["For Android"]</h3> <a class="mx-1 my-3 f3" href="https://play.google.com/store/apps/details?id=com.aiursoft.kahla"> <img style="height:74px" alt="Get it on Google Play" src="~/images/en_badge_web_generic.png" /> </a> <h3 class="mt-3">@Localizer["For iOS"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Html.Raw(Model.KahlaWebPath)"><label class="text-muted">@Localizer["(We are working on iOS app...)"]</label></a> </div> <div class="tab-pane fade" id="sdk" role="tabpanel" aria-labelledby="sdk-tab"> <h3 class="mt-3 mb-2">@Localizer["For .NET Core"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://www.nuget.org/packages/Kahla.SDK/" target="_blank"> @Localizer["Nuget.org"] </a> </div> <div class="tab-pane fade" id="cli" role="tabpanel" aria-labelledby="cli-tab"> <h3 class="mt-3">@Localizer["CLI Tools"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.CliDownloadRoot/WindowsCLI/Kahla-CLI-Windows.zip" target="_blank">@Localizer["Windows (exe)"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.CliDownloadRoot/MacCLI/Kahla-CLI-Mac.zip" target="_blank">@Localizer["Mac OS"]</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.CliDownloadRoot/LinuxCLI/Kahla-CLI-Linux.zip" target="_blank">@Localizer["Linux"]</a> </div> <div class="tab-pane fade" id="tpy" role="tabpanel" aria-labelledby="cli-tab"> <h3 class="mt-3">@Localizer["Partners"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://alternativeto.net/software/kahla/" target="_blank">alternativeto.net</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://www.softpedia.com/get/Internet/Chat/Instant-Messaging/Kahla.shtml" target="_blank">softpedia.com</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://electronjs.org/apps/kahla" target="_blank">electron.io</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="http://kahla.findmysoft.com/" target="_blank">findmysoft.com</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://betapage.co/startup/kahla" target="_blank">betapage.co</a> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="https://freeappsforme.com/kahla-app-review/" target="_blank">Freeappsforme.com</a> <h3 class="mt-3">@Localizer["Others"]</h3> <a class="mx-1 my-3 f3 btn btn-large btn-outline-purple" href="@Model.ArchiveRoot/v@(Model.AppLatestVersion)/@(Model.AppLatestVersion).zip" target="_blank">@Localizer["Source code"]</a> </div> </div> </div> </div> </div> </div>
the_stack
@{ ViewBag.Title = "Form"; Layout = "~/Views/Shared/_Form.cshtml"; } <!--表格组件end--> <script type="text/javascript"> var keyValue = SF.utility.request('keyValue'); var parentId = SF.utility.request('parentId'); $(function () { initialPage(); buttonOperation(); // getGridButton(); // getGridView(); }) //初始化页面 function initialPage() { //加载导向 $('#wizard').wizard().on('change', function (e, data) { var $finish = $("#btn_finish"); var $next = $("#btn_next"); if (data.direction == "next") { if (data.step == 2) { $finish.removeAttr('disabled'); $next.attr('disabled', 'disabled'); } else { $finish.attr('disabled', 'disabled'); } } else { $finish.attr('disabled', 'disabled'); $next.removeAttr('disabled'); } }); initControl(); } //初始化控件 function initControl() { //目标 SF.utility.comboBox($("#Target"), { description: "==请选择==", height: "200px" }); //上级 SF.utility.comboBoxTree($("#ParentId"), { url: "/Api/Module/GetTreeJson", description: "==请选择==", height: "195px", allowSearch: true }); //获取表单 if (!!keyValue) { SF.utility.setForm({ url: "/Api/Module/" + keyValue, success: function (data) { SF.utility.setWebControls('form1', data); if (data.IsMenu == 1) { $("#btn_next").removeAttr('disabled'); $("#btn_finish").attr('disabled', 'disabled'); }Module1 } }); } else { SF.utility.comboBoxTreeSetValue( $("#ParentId"),parentId); } } //选取图标 function SelectIcon() { SF.utility.dialogOpen({ id: "SelectIcon", title: '选取图标', url: '/Module/Icon?ControlId=Icon', width: "1000px", height: "600px", btn: false }) } //保存表单 function AcceptClick(type) { if (!$('#form1').Validform()) { return false; } var postData = SF.utility.getWebControls('form1', keyValue); if (postData["ParentId"] == "") { postData["ParentId"] = 0; } //postData["moduleButtonListJson"] = JSON.stringify(buttonJson); //postData["moduleColumnListJson"] = JSON.stringify(columnJson); var url = "/Api/Module/"; if (type == "PUT") url = url + keyValue; else if (type == "POST") url = url; SF.utility.saveForm({ type: type, url: url, param: postData, loading: "正在保存数据...", success: function () { SF.utility.currentIframe().$("#gridTable").resetSelection(); SF.utility.currentIframe().$("#gridTable").trigger("reloadGrid"); } }) } //按钮操作(上一步、下一步、完成、关闭) function buttonOperation() { var $last = $("#btn_last"); var $next = $("#btn_next"); var $finish = $("#btn_finish"); //如果是菜单,开启 上一步、下一步 $("#IsMenu").click(function () { if (!$(this).attr("checked")) { $(this).attr("checked", true) $next.removeAttr('disabled'); $finish.attr('disabled', 'disabled'); } else { $(this).attr("checked", false) $next.attr('disabled', 'disabled'); $finish.removeAttr('disabled'); } }); //完成提交保存 $finish.click(function () { AcceptClick(); }) } /*系统按钮being==================================*/ var buttonJson = ""; function getGridButton() { var moduleId = $("#ModuleId").val(); $.ajax({ url: "/Api/ModuleButton/GetListJson?moduleId=" + escape(moduleId), type: "get", dataType: "json", success: function (data) { buttonJson = data; }, }); var $grid = $("#gridTable-button"); $grid.jqGrid({ unwritten: false, url: "/Api/ModuleButton/GetTreeListJson?moduleId=" + escape(moduleId), datatype: "json", height: $(window).height() - 165, width: $(window).width() - 11, colModel: [ { label: "主键", name: "ModuleButtonId", hidden: true }, { label: "名称", name: "FullName", width: 140, align: "left", sortable: false }, { label: "编号", name: "EnCode", width: 140, align: "left", sortable: false }, { label: "地址", name: "ActionAddress", width: 500, align: "left", sortable: false }, ], treeGrid: true, treeGridModel: "nested", ExpandColumn: "EnCode", rowNum: "all", rownumbers: true }); //处理Json function ButtonListToListTreeJson(buttonJson) { $.ajax({ url: "/Api/ModuleButton/ListToListTreeJson", data: { moduleButtonJson: JSON.stringify(buttonJson) }, type: "post", dataType: "json", success: function (data) { $grid.clearGridData(); $grid[0].addJSONData(data); }, }); } //新增 $("#lr-add-button").click(function () { var parentId = $("#gridTable-button").jqGridRowValue("ModuleButtonId"); dialogOpen({ id: "buttonForm", title: '添加按钮', url: '/AuthorizeManage/ModuleButton/Form?parentId=' + parentId + "&moduleId=" + escape(moduleId), width: "450px", height: "300px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(function (data) { buttonJson.push(data); ButtonListToListTreeJson(buttonJson); }); } }); }) //编辑 $("#lr-edit-button").click(function () { var moduleButtonId = $("#gridTable-button").jqGridRowValue("ModuleButtonId"); if (checkedRow(moduleButtonId)) { dialogOpen({ id: "buttonForm", title: '编辑按钮', url: '/AuthorizeManage/ModuleButton/Form?moduleButtonId=' + moduleButtonId + "&moduleId=" + escape(moduleId), width: "450px", height: "300px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(function (data) { $.each(buttonJson, function (i) { if (buttonJson[i].ModuleButtonId == moduleButtonId) { buttonJson[i] = data; } }); ButtonListToListTreeJson(buttonJson); }); } }); } }) //删除 $("#lr-delete-button").click(function () { var moduleButtonId = $("#gridTable-button").jqGridRowValue("ModuleButtonId"); if (checkedRow(moduleButtonId)) { $.each(buttonJson, function (i) { if (buttonJson[i].ModuleButtonId == moduleButtonId) { buttonJson.splice(i, 1); ButtonListToListTreeJson(buttonJson); return false; } }); } }); //复制 $("#lr-copy-button").click(function () { var moduleButtonId = $("#gridTable-button").jqGridRowValue("ModuleButtonId"); if (checkedRow(moduleButtonId)) { dialogOpen({ id: "OptionModule", title: '将按钮复制到指定功能里面', url: '/AuthorizeManage/ModuleButton/OptionModule?keyValue=' + moduleButtonId, width: "500px", height: "500px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(); } }); } }); } /*系统按钮end====================================*/ /*系统视图being==================================*/ var columnJson = ""; function getGridView() { var moduleId = $("#ModuleId").val(); $.ajax({ url: "/Api/ModuleColumn/GetListJson?moduleId=" + escape(moduleId), type: "get", dataType: "json", success: function (data) { columnJson = data; }, }); var $grid = $("#gridTable-view"); $grid.jqGrid({ unwritten: false, url: "/Api/ModuleColumn/GetTreeListJson?moduleId=" + escape(moduleId), datatype: "json", height: $(window).height() - 165, width: $(window).width() - 11, colModel: [ { label: "主键", name: "ModuleColumnId", index: "ModuleColumnId", hidden: true }, { label: "名称", name: "FullName", index: "FullName", width: 140, align: "left", sortable: false, }, { label: "编号", name: "EnCode", index: "EnCode", width: 140, align: "left", sortable: false }, { label: "描述", name: "Description", index: "Description", width: 500, align: "left", sortable: false } ], rowNum: 1000, rownumbers: true }); //处理Json function ViewListToListTreeJson(columnJson) { $.ajax({ url: "/Api/ModuleColumn/ListToListTreeJson", data: { moduleColumnJson: JSON.stringify(columnJson) }, type: "post", dataType: "json", success: function (data) { $grid.clearGridData(); $grid[0].addJSONData(data); }, }); } //新增 $("#lr-add-view").click(function () { dialogOpen({ id: "viewForm", title: '添加视图', url: '/AuthorizeManage/ModuleColumn/Form?moduleId=' + escape(moduleId), width: "450px", height: "260px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(function (data) { columnJson.push(data); ViewListToListTreeJson(columnJson); }); } }); }) //编辑 $("#lr-edit-view").click(function () { var moduleColumnId = $("#gridTable-view").jqGridRowValue("ModuleColumnId"); if (checkedRow(moduleColumnId)) { dialogOpen({ id: "viewForm", title: '编辑视图', url: '/AuthorizeManage/ModuleColumn/Form?moduleColumnId=' + moduleColumnId + "&moduleId=" + escape(moduleId), width: "450px", height: "260px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(function (data) { $.each(columnJson, function (i) { if (columnJson[i].ModuleColumnId == moduleColumnId) { columnJson[i] = data; } }); ViewListToListTreeJson(columnJson); }); } }); } }) //删除 $("#lr-delete-view").click(function () { var moduleColumnId = $("#gridTable-view").jqGridRowValue("ModuleColumnId"); if (checkedRow(moduleColumnId)) { $.each(columnJson, function (i) { if (columnJson[i].ModuleColumnId == moduleColumnId) { columnJson.splice(i, 1); ViewListToListTreeJson(columnJson); return false; } }); } }); //批量添加 $("#lr-batch-addview").click(function () { dialogOpen({ id: "viewForm", title: '批量添加视图', url: '/AuthorizeManage/ModuleColumn/BatchAdd?moduleId=' + escape(moduleId), width: "450px", height: "300px", callBack: function (iframeId) { top.frames[iframeId].AcceptClick(function (data) { columnJson = data; ViewListToListTreeJson(data); }); } }); }) } /*系统视图end====================================*/ </script> <div class="widget-body"> <div id="wizard" class="wizard" data-target="#wizard-steps" style="border-left: none; border-top: none; border-right: none;"> <ul class="steps"> <li data-target="#step-1" class="active"><span class="step">1</span>系统功能<span class="chevron"></span></li> <li data-target="#step-2"><span class="step">2</span>系统按钮<span class="chevron"></span></li> <li data-target="#step-3"><span class="step">3</span>系统视图<span class="chevron"></span></li> </ul> </div> <div class="step-content" id="wizard-steps" style="border-left: none; border-bottom: none; border-right: none;"> <div class="step-pane active" id="step-1" style="margin-left: 0px; margin-top: 15px; margin-right: 30px;"> <input id="ModuleId" type="hidden" value="@ViewBag.ModuleId" /> <table class="form"> <tr> <th class="formTitle">编号<font face="宋体">*</font></th> <td class="formValue"> <input id="EnCode" type="text" class="form-control" placeholder="请输入编号" isvalid="yes" checkexpession="NotNull" /> </td> <th class="formTitle">名称<font face="宋体">*</font></th> <td class="formValue"> <input id="FullName" type="text" class="form-control" placeholder="请输入名称" isvalid="yes" checkexpession="NotNull" /> </td> </tr> <tr> <th class="formTitle">上级</th> <td class="formValue"> <div id="ParentId" type="selectTree" class="ui-select"> </div> </td> <th class="formTitle">图标</th> <td class="formValue"> <input id="Icon" type="text" class="form-control" /> <span class="input-button" onclick="SelectIcon()" title="选取图标">...</span> </td> </tr> <tr> <th class="formTitle">目标<font face="宋体">*</font></th> <td class="formValue"> <div id="Target" type="select" class="ui-select" isvalid="yes" checkexpession="NotNull"> <ul> <li data-value="expand">expand</li> <li data-value="iframe">iframe</li> <li data-value="open">open</li> <li data-value="href">href</li> <li data-value="blank">blank</li> </ul> </div> </td> <th class="formTitle">排序<font face="宋体">*</font></th> <td class="formValue"> <input id="SortIndex" type="text" class="form-control" isvalid="yes" checkexpession="Num" /> </td> </tr> <tr> <th class="formTitle">地址</th> <td class="formValue" colspan="3"> <input id="UrlAddress" type="text" class="form-control" /> </td> </tr> <tr> <th class="formTitle" style="height: 37px;">选项</th> <td class="formValue"> <div class="checkbox user-select"> <label> <input id="IsMenu" type="checkbox" /> 菜单 </label> <label> <input id="IsPublic" type="checkbox" /> 公共 </label> <label> <input id="AllowExpand" type="checkbox" /> 展开 </label> <label> <input id="EnabledMark" type="checkbox" checked="checked" /> 有效 </label> </div> </td> </tr> <tr> <th class="formTitle" valign="top" style="padding-top: 4px;"> 描述 </th> <td class="formValue" colspan="3"> <textarea id="Description" class="form-control" style="height: 70px;"></textarea> </td> </tr> </table> </div> <div class="step-pane" id="step-2" style="margin: 5px;"> <div style="height: 40px; line-height: 33px; text-align: right;"> <div class="btn-group"> <a id="lr-add-button" class="btn btn-default"><i class="fa fa-plus"></i>&nbsp;新增</a> <a id="lr-edit-button" class="btn btn-default"><i class="fa fa-pencil-square-o"></i>&nbsp;编辑</a> <a id="lr-delete-button" class="btn btn-default"><i class="fa fa-trash-o"></i>&nbsp;删除</a> </div> <div class="btn-group"> <a id="lr-copy-button" class="btn btn-default"><i class="fa fa-copy"></i>&nbsp;复制</a> </div> </div> <table id="gridTable-button"></table> </div> <div class="step-pane" id="step-3" style="margin: 5px;"> <div style="height: 40px; line-height: 33px; text-align: right;"> <div class="btn-group"> <a id="lr-add-view" class="btn btn-default"><i class="fa fa-plus"></i>&nbsp;新增</a> <a id="lr-edit-view" class="btn btn-default"><i class="fa fa-pencil-square-o"></i>&nbsp;编辑</a> <a id="lr-delete-view" class="btn btn-default"><i class="fa fa-trash-o"></i>&nbsp;删除</a> </div> <div class="btn-group"> <a id="lr-batch-addview" class="btn btn-default"><i class="fa fa-sign-in"></i>&nbsp;批量添加</a> </div> </div> <table id="gridTable-view"></table> </div> </div> </div> <div class="form-button" id="wizard-actions"> <a id="btn_last" disabled class="btn btn-default btn-prev">上一步</a> <a id="btn_next" disabled class="btn btn-default btn-next">下一步</a> <a id="btn_finish" class="btn btn-success">完成</a> </div>
the_stack
@page @model FytSoa.Web.Pages.FytAdmin.WeChat.MaterialTextModel @{ ViewData["Title"] = "微信管理-素材-图文"; Layout = "~/Pages/FytAdmin/_Layout.cshtml"; } <style> .wxsc-left { width: 240px; position: absolute; left: 0; top: 0; bottom: 0; background-color: #f6f8f9; overflow: auto; padding: 20px; z-index: 1; } .wxsc-wall { position: relative; height: 608px; } .wxsc-add { background-color: #ffffff; padding: 20px 0; text-align: center; cursor: pointer; border: 1px dotted #d9dadc; } .wxsc-add i { font-size: 30px; color: #979797; } .wxsc-nitem { background-color: #ffffff; padding: 10px; position: relative; padding-left: 176px; cursor: pointer; border: 4px solid rgba(255,255,255,1); } .wxsc-nitem::after { position: absolute; left: -4px; right: 0px; width: 103%; height: 1px; content: ''; display: block; background-color: #e7e7eb; bottom: -4px; } .wxsc-nitem.active { border: 4px solid rgba(26,173,25,0.4); } .wxsc-nitem.active::after { display: none; } .wxsc-nitem .nitem-img { width: 50px; height: 50px; background-color: #ececec; background-size: cover; background-repeat: no-repeat; } .wxsc-nitem .nitem-text { width: 150px; position: absolute; left: 10px; padding-top: 10px; cursor: pointer; } .wxsc-nitem .nitem-tool { position: absolute; left: -4px; right: -4px; bottom: -4px; background: rgba(0,0,0,0.5) !important; color: #ffffff; text-align: right; padding: 6px; display: none; } .wxsc-nitem .nitem-tool i { font-size: 20px; cursor: pointer; } .wxsc-nitem:hover .nitem-tool { display: block; } .wxsc-right { padding-left: 278px; height: 607px; width: 621px; border: 1px solid #e7e7eb; border-bottom: none; border-right: none; position: relative; } .wxsc-cover { position: absolute; width: 260px; padding: 20px; top: 0px; right: 0px; bottom: 0px; border-left: 1px solid #e7e7eb; z-index: 1; } .wxsc-cover h5 { font-size: 15px; color: #333; margin-bottom: 15px; } .wxsc-cover h5 span { color: #999; font-size: 13px; } .wxsc-cover p { color: #999; font-size: 13px; } .wxsc-cover .img { background-color: #ececec; background-size: cover; background-repeat: no-repeat; width: 100%; height: 130px; margin-top: 15px; } .wxsc-cover textarea { min-height: 100px; } .wxsc-cover .img-select { margin-bottom: 20px; text-align: center; margin-top: 15px; } .wxsc-right .wx-input { border: none; padding: 10px; font-size: 13px; width: 98%; } .wxsc-right .cell { padding: 2px 15px; } .wxsc-right .cell:first-child { border-bottom: 1px solid #e7e7eb; padding: 15px; } .wxsc-right .cell:first-child .wx-input { font-size: 18px; } .wxsc-right .wxsc-btn { margin-top: 15px; text-align: center; position: absolute; width: 69%; bottom: 0; padding: 20px 0; } .wxsc-right .wxsc-btn .layui-btn { padding: 5px 30px; } .wxsc-nitem:first-child { padding-left: 10px; } .wxsc-nitem:first-child .nitem-text { width: 95%; bottom: -4px; left: -4px; padding: 10px; color: #ffffff; background: rgba(0,0,0,0.5) !important; } .wxsc-nitem:first-child:hover .nitem-tool { display: none; } .wxsc-nitem:first-child:hover .nitem-text { background: rgba(0,0,0,0.5) !important; } .wxsc-nitem:first-child .nitem-img { background-color: #ececec; height: 120px; background-size: cover; background-repeat: no-repeat; width: 100%; } .mce-tinymce { box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 0px; border-width: 0px !important; border-bottom: 1px solid #e7e7eb !important; margin-top: 10px; } .mce-top-part::before { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); } div.mce-edit-area { border-width: 0px 0px 0px !important; } </style> <div class="wxsc-wall" id="wxsc"> <div class="wxsc-left"> <div class="wxsc-nitem" v-for="(item,index) in scList" @@click="itemActive(index,item)" :class="{active:itemClass==index}"> <div class="nitem-text layui-elip">{{item.title}}</div> <div class="nitem-img" :style="'background-image:url('+item.img+')'"></div> <div class="nitem-tool"><i class="layui-icon layui-icon-delete" @@click="del(item,index)"></i></div> </div> <div class="wxsc-add" @@click="addsc" v-show="addBtnShow"> <i class="layui-icon layui-icon-add-1"></i> </div> </div> <div class="wxsc-right"> <div class="cell"> <input type="text" v-model="scModel.title" placeholder="请在这里输入标题" class="wx-input"> </div> <div class="cell"> <input type="text" v-model="scModel.author" placeholder="请输入作者" class="wx-input"> </div> <div class="cell"> <input type="text" v-model="scModel.link" placeholder="原文链接地址,必须以http开头" class="wx-input"> </div> <textarea id="content" v-model="scModel.content" placeholder="请输入内容" class="layui-textarea"></textarea> <div class="wxsc-btn"> <button class="layui-btn" @@click="save" v-bind:disabled="saveDisabled">保存</button> <button class="layui-btn layui-hide">预览</button> <button class="layui-btn" @@click="synchro">保存并同步到公众号</button> </div> </div> <div class="wxsc-cover"> <h5>封面</h5> <p>建议尺寸:</p> <p>大图片:900 * 500(单图文或多图文第一篇)</p> <p>小图片200 * 200(多图文第一篇图文下面)</p> <div class="img" :style="'background-image:url('+scModel.img+')'"></div> <div class="img-select"><button class="layui-btn layui-btn-primary fyt-cloud" data-type="form">选择图片</button></div> <h5>摘要</h5> <textarea name="summary" v-model="scModel.summary" class="layui-textarea" placeholder="选填,如果不填写会默认抓取正文前54个字"></textarea> </div> </div> <script src="~/themes/tinymce/tinymce.min.js"></script> <script src="~/themes/tinymce/langs/zh_CN.js"></script> <script> var os,layer,wxid=@Model.WxId,layindex, wxsc = new Vue({ el: '#wxsc', data: { scModel: {}, saveDisabled:false, scFirstModel: { title: '', img: '', author: '', link: '', content: '', summary: '' }, scList: [], addBtnShow: true, itemClass:0, modelObj: { title: '', img: '', author: '', link: '', content: '', summary:'' } }, created: function () { if (@Model.Id=== 0) { let model = this.initModel(); this.scModel = model; this.scList.push(model); } var that = this; tinymce.init({ selector: '#content', height: 340, width: 610, menubar: false, resize: false, statusbar:false, setup: function (editor) { editor.on('input change undo redo execCommand KeyUp', function (e) { that.scModel.content = editor.getContent(); }) } }); }, methods: { del: function (m,i) { //删除一篇文章 var that = this; layer.confirm('确定删除此篇图文?', function (index) { layer.close(index); that.scList.splice(i, 1); }); }, addsc: function () { //添加一篇文章 let model = this.initModel(); this.scList.push(model); this.scModel = model; tinyMCE.activeEditor.setContent(model.content); if (this.scList.length == 7) { this.addBtnShow = false; } }, initModel: function () { return { title: '', img: '', author: '', link: '', content: '', summary: '' }; }, itemActive: function (index,m) { //选择要编辑的图文 this.itemClass = index; this.scModel = m; tinyMCE.activeEditor.setContent(m.content); }, save: function () { let list = this.scList; for (let i = 0; i < list.length; i++) { if (list[i].title == '') { os.warning('标题不能为空~'); return; } } let that = this; that.saveDisabled = true; os.load(); os.ajax('api/wx/material/add', { Id:@Model.Id, WxId: wxid, TestJson: JSON.stringify(list) }, function (res) { os.loadClose(); that.saveDisabled = false; if (res.statusCode == 200) { parent.layer.close(layindex); } else { os.error(res.message); } }); }, //保存,并同步 synchro: function () { let list = this.scList; for (let i = 0; i < list.length; i++) { if (list[i].title == '') { os.warning('标题不能为空~'); return; } } let that = this; that.saveDisabled = true; os.load(); os.ajax('api/wx/material/synchro', { Id:@Model.Id, WxId: wxid, TestJson: JSON.stringify(list) }, function (res) { os.loadClose(); that.saveDisabled = false; if (res.statusCode == 200) { parent.layer.close(layindex); } else { os.error(res.message); } }); } } }); layui.config({ base: '/themes/js/modules/' }).use(['layer', 'jquery', 'common', 'form'], function () { layer = layui.layer; os = layui.common; var form = layui.form, $ = layui.jquery; os.cloudFile(); oc = { fileSave(v) { wxsc.scModel.img = v; } }; if (@Model.Id!== 0) { os.load(); os.ajax('api/wx/material/get', { id:@Model.Id}, function (res) { os.loadClose(); if (res.statusCode === 200) { //os.log(JSON.parse(res.data.testJson)); //wxsc.scModel = JSON.parse(res.data.testJson)[0]; //wxsc.scList.push(wxsc.scModel); wxsc.itemClass = -1; wxsc.scList = JSON.parse(res.data.testJson); tinyMCE.activeEditor.setContent(wxsc.scModel.content); } else { os.error(res.message); } }); } layindex = parent.layer.getFrameIndex(window.name); }); </script>
the_stack
@{ ViewBag.Title = "Drag and Drop"; } <h2>Drag and Drop Testbed</h2> <p>Based on <a href="https://yuilibrary.com/yui/docs/dd/groups-drag.html">YUI Library example</a></p> <form class="well"> <div style="position: relative; height: 300px;"> <div class="slot" id="t1">1</div> <div class="slot" id="t2">2</div> <div class="slot" id="b1">3</div> <div class="slot" id="b2">4</div> <div class="slot" id="b3">5</div> <div class="slot" id="b4">6</div> <div class="player" id="pt1">1</div> <div class="player" id="pt2">2</div> <div class="player" id="pb1">3</div> <div class="player" id="pb2">4</div> <div class="player" id="pboth1">5</div> <div class="player" id="pboth2">6</div> </div> </form> <script type="text/javascript" src="/scripts/yui/yuiloader-min.js"></script> <script type="text/javascript" src="/scripts/yui/dom-min.js"></script> <script type="text/javascript" src="/scripts/yui/event-min.js"></script> <script type="text/javascript" src="/scripts/yui/dragdrop-min.js"></script> <script type="text/javascript" src="/scripts/yui/element-min.js"></script> <script type="text/javascript" src="/scripts/yui/button-min.js"></script> <script type="text/javascript"> (function () { YAHOO.example.DDPlayer = function (id, sGroup, config) { YAHOO.example.DDPlayer.superclass.constructor.apply(this, arguments); this.initPlayer(id, sGroup, config); }; YAHOO.extend(YAHOO.example.DDPlayer, YAHOO.util.DDProxy, { TYPE: "DDPlayer", initPlayer: function (id, sGroup, config) { if (!id) { return; } var el = this.getDragEl() YAHOO.util.Dom.setStyle(el, "borderColor", "transparent"); YAHOO.util.Dom.setStyle(el, "opacity", 0.76); // specify that this is not currently a drop target this.isTarget = false; this.originalStyles = []; this.type = YAHOO.example.DDPlayer.TYPE; this.slot = null; this.startPos = YAHOO.util.Dom.getXY(this.getEl()); YAHOO.log(id + " startpos: " + this.startPos, "info", "example"); }, startDrag: function (x, y) { YAHOO.log(this.id + " startDrag", "info", "example"); var Dom = YAHOO.util.Dom; var dragEl = this.getDragEl(); var clickEl = this.getEl(); dragEl.innerHTML = clickEl.innerHTML; dragEl.className = clickEl.className; Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color")); Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); Dom.setStyle(clickEl, "opacity", 0.1); var targets = YAHOO.util.DDM.getRelated(this, true); YAHOO.log(targets.length + " targets", "info", "example"); for (var i = 0; i < targets.length; i++) { var targetEl = this.getTargetDomRef(targets[i]); if (!this.originalStyles[targetEl.id]) { this.originalStyles[targetEl.id] = targetEl.className; } targetEl.className = "target"; } }, getTargetDomRef: function (oDD) { if (oDD.player) { return oDD.player.getEl(); } else { return oDD.getEl(); } }, endDrag: function (e) { // reset the linked element styles YAHOO.util.Dom.setStyle(this.getEl(), "opacity", 1); this.resetTargets(); }, resetTargets: function () { // reset the target styles var targets = YAHOO.util.DDM.getRelated(this, true); for (var i = 0; i < targets.length; i++) { var targetEl = this.getTargetDomRef(targets[i]); var oldStyle = this.originalStyles[targetEl.id]; if (oldStyle) { targetEl.className = oldStyle; } } }, onDragDrop: function (e, id) { // get the drag and drop object that was targeted var oDD; if ("string" == typeof id) { oDD = YAHOO.util.DDM.getDDById(id); } else { oDD = YAHOO.util.DDM.getBestMatch(id); } var el = this.getEl(); // check if the slot has a player in it already if (oDD.player) { // check if the dragged player was already in a slot if (this.slot) { // check to see if the player that is already in the // slot can go to the slot the dragged player is in // YAHOO.util.DDM.isLegalTarget is a new method if (YAHOO.util.DDM.isLegalTarget(oDD.player, this.slot)) { YAHOO.log("swapping player positions", "info", "example"); YAHOO.util.DDM.moveToEl(oDD.player.getEl(), el); this.slot.player = oDD.player; oDD.player.slot = this.slot; } else { YAHOO.log("moving player in slot back to start", "info", "example"); YAHOO.util.Dom.setXY(oDD.player.getEl(), oDD.player.startPos); this.slot.player = null; oDD.player.slot = null } } else { // the player in the slot will be moved to the dragged // players start position oDD.player.slot = null; YAHOO.util.DDM.moveToEl(oDD.player.getEl(), el); } } else { // Move the player into the emply slot // I may be moving off a slot so I need to clear the player ref if (this.slot) { this.slot.player = null; } } YAHOO.util.DDM.moveToEl(el, oDD.getEl()); this.resetTargets(); this.slot = oDD; this.slot.player = this; }, swap: function (el1, el2) { var Dom = YAHOO.util.Dom; var pos1 = Dom.getXY(el1); var pos2 = Dom.getXY(el2); Dom.setXY(el1, pos2); Dom.setXY(el2, pos1); }, onDragOver: function (e, id) { }, onDrag: function (e, id) { } }); var slots = [], players = [], Event = YAHOO.util.Event, DDM = YAHOO.util.DDM; Event.onDOMReady(function () { // slots slots[0] = new YAHOO.util.DDTarget("t1", "topslots"); slots[1] = new YAHOO.util.DDTarget("t2", "topslots"); slots[2] = new YAHOO.util.DDTarget("b1", "bottomslots"); slots[3] = new YAHOO.util.DDTarget("b2", "bottomslots"); slots[4] = new YAHOO.util.DDTarget("b3", "bottomslots"); slots[5] = new YAHOO.util.DDTarget("b4", "bottomslots"); // players players[0] = new YAHOO.example.DDPlayer("pt1", "topslots"); players[1] = new YAHOO.example.DDPlayer("pt2", "topslots"); players[2] = new YAHOO.example.DDPlayer("pb1", "bottomslots"); players[3] = new YAHOO.example.DDPlayer("pb2", "bottomslots"); players[4] = new YAHOO.example.DDPlayer("pboth1", "topslots"); players[4].addToGroup("bottomslots"); players[5] = new YAHOO.example.DDPlayer("pboth2", "topslots"); players[5].addToGroup("bottomslots"); DDM.mode = document.getElementById("ddmode").selectedIndex; Event.on("ddmode", "change", function (e) { YAHOO.util.DDM.mode = this.selectedIndex; }); }); })(); </script> <style type="text/css"> .slot { border: 2px solid #aaaaaa; background-color: #dddddd; color: #666666; text-align: center; position: absolute; width: 60px; height: 60px; } .player { border: 2px solid #bbbbbb; color: #eeeeee; text-align: center; position: absolute; width: 60px; height: 60px; } .target { border: 2px solid #574188; background-color: #cccccc; text-align: center; position: absolute; width: 60px; height: 60px; } #t1 { left: 10px; top: 0px; } #t2 { left: 378px; top: 0px; } #b1 { left: 84px; top: 50px; } #b2 { left: 158px; top: 50px; } #b3 { left: 232px; top: 50px; } #b4 { left: 306px; top: 50px; } #pt1 { background-color: #7E695E; left: 84px; top: 150px; } #pt2 { background-color: #7E695E; left: 84px; top: 230px; } #pb1 { background-color: #416153; left: 195px; top: 150px; } #pb2 { background-color: #416153; left: 195px; top: 230px; } #pboth1 { background-color: #552E37; left: 306px; top: 150px; } #pboth2 { background-color: #552E37; left: 306px; top: 230px; } #usercontrols { top: -36px; } #workarea { position: relative; height: 300px; } </style>
the_stack
@using Kooboo.CMS.Common.Runtime; @using Kooboo.CMS.Content.Services; @using Newtonsoft.Json @{ ViewBag.Title = "Start".Localize(); Layout = "~/Views/Shared/Site.cshtml"; } @section Panel{ } <div class="topbar"> <h1 class="title">Relation</h1> </div> <div class="block fixed"> <div class="block relation"> <div class="titlebar"> <h6 class="title">@("Membership".Localize())</h6> <h6 class="title">@("Site".Localize())</h6> <h6 class="title">@("Content database".Localize())</h6> </div> <div id="showRelation"></div> </div> </div> <script> var site = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Sites, Formatting.Indented)); var content = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Databases, Formatting.Indented)); var membership = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Memberships, Formatting.Indented)); var max_length = Math.max(site.length, content.length, membership.length); var bgSite = '#009AD7'; var bgDatabase = '#1F9284'; var bgMembership = '#5496A7'; var w = 1000; var rect_w = w / 100 * 20; var rect_h = 39; var rect_margin_h = w / 100 * 2; var h = max_length * (rect_h + rect_margin_h) + 100; var svg = d3.select('#showRelation').append('svg').attr('width', w).attr('height', h); // rects and texts // Empty case function createEmptyRect(empty_type){ switch (empty_type){ case 'membership': var text = '@("Create new membership".Localize())'; var offset = 0; var url = '@(Url.Action("Create", new { controller = "Membership", area = "Membership", @return = Request.RawUrl }))'; break; case 'site': var text = '@("Create new site".Localize())'; var offset = 1; var url = '@(Url.Action("Create", new { controller = "Site", area = "Sites", @return = Request.RawUrl }))'; break; case 'content': var text = '@("Create new content database".Localize())'; var offset = 2; var url = '@(Url.Action("Create", new { controller = "Repository", area = "Contents", @return = Request.RawUrl }))'; break; } svg.selectAll('rect.none').data([1]).enter().append('rect') .attr('x', offset * 300 + 70) .attr('y', 40) .attr('class', 'empty') .attr('data-url', url) .attr('width', rect_w) .attr('height', rect_h) .attr('fill', '#FFF') .attr('stroke', '#AAA') .attr('style', 'cursor:pointer;') .attr('stroke-dasharray', '5 2'); svg.selectAll('text.none').data([1]).enter().append('text') .attr('x', 70 + w / 100 * 10 + offset * 300) .attr('y', 66) .attr('class', 'empty') .attr('data-url', url) .attr('style', 'font-family: Arial; font-size: 14px; text-anchor: middle;cursor:pointer;') .attr('fill', '#AAA') .text(text); } if(!membership.length){ createEmptyRect('membership'); } if(!site.length){ createEmptyRect('site'); } if(!content.length){ createEmptyRect('content'); } // Full case var siteNode = svg.selectAll().data(site).enter().append('g'); var contentNode = svg.selectAll().data(content).enter().append('g'); var membershipNode = svg.selectAll().data(membership).enter().append('g'); siteNode.attr('class', 'node site') .attr('x', w / 100 * 30 + 70) .attr('y', function (d) { return 40 + d.num * (rect_h + rect_margin_h) }) .attr('data-name', function(d){return d.name}); //Site rect siteNode.append('rect') .attr('x', w / 100 * 30 + 70) .attr('y', function (d) { return 40 + d.num * (rect_h + rect_margin_h) }) .attr('height',rect_h) .attr('width',rect_w) .attr('fill', bgSite); //Site icon siteNode.append('image') .attr('x', w / 100 * 30 + 76) .attr('y', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + 11 }) .attr('width', 17) .attr('height', 17) .attr('xlink:href', '@(Url.Content("~/Images/svg-site.png"))'); //Site line siteNode.append('line') .attr('x1', w / 100 * 30 + 100) .attr('y1', function (d) { return 40 + d.num * (rect_h + rect_margin_h) }) .attr('x2', w / 100 * 30 + 100) .attr('y2', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + 39 }) .attr('stroke-width', 2) .attr('stroke', '#FFF'); //Site text siteNode.append('text') .attr('x', w / 100 * 30 + 106) .attr('y', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + 24 }) .attr('style', 'font-family: Arial; font-size: 14px') .attr('fill', '#FFF') .attr('style','cursor:default') .text(function (d) { return d.text }); //Site arrow siteNode.append('image') .attr('class', 'link') .attr('x', w / 100 * 30 + 250) .attr('y', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + 11 }) .attr('width', 16) .attr('height', 16) .attr('style','cursor:pointer') .attr('data-url', function (d) { return d.url }) .attr('xlink:href', '@(Url.Content("~/Images/svg-view.png"))'); contentNode.attr('class', 'node content') .attr('data-name', function(d){return d.name}); //Content rect contentNode.append('rect') .attr('x', w / 100 * 60 + 70) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) }) .attr('height',rect_h) .attr('width',rect_w) .attr('fill', bgDatabase); //Content icon contentNode.append('image') .attr('x', w / 100 * 60 + 76) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 11 }) .attr('width', 17) .attr('height', 17) .attr('xlink:href', '@(Url.Content("~/Images/svg-content.png"))'); //Content line contentNode.append('line') .attr('x1', w / 100 * 60 + 100) .attr('y1', function (d, i) { return 40 + i * (rect_h + rect_margin_h) }) .attr('x2', w / 100 * 60 + 100) .attr('y2', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 39 }) .attr('stroke-width', 2) .attr('stroke', '#FFF'); //Content text contentNode.append('text') .attr('x', w / 100 * 60 + 106) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 24 }) .attr('style', 'font-family: Arial; font-size: 14px') .attr('fill', '#FFF') .attr('style','cursor:default') .text(function (d) { return d.text }); //Content arrow contentNode.append('image') .attr('class', 'link') .attr('x', w / 100 * 60 + 250) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 11 }) .attr('width', 16) .attr('height', 16) .attr('style','cursor:pointer') .attr('data-url', function (d) { return d.url }) .attr('xlink:href', '@(Url.Content("~/Images/svg-view.png"))'); membershipNode.attr('class', 'node membership') .attr('data-name', function(d){return d.name}); //Membership rect membershipNode.append('rect') .attr('x', 70) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) }) .attr('height',rect_h) .attr('width',rect_w) .attr('fill', bgMembership); //Membership icon membershipNode.append('image') .attr('x', 76) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 11 }) .attr('width', 17) .attr('height', 17) .attr('xlink:href', '@(Url.Content("~/Images/svg-membership.png"))'); //Membership line membershipNode.append('line') .attr('x1', 100) .attr('y1', function (d, i) { return 40 + i * (rect_h + rect_margin_h) }) .attr('x2', 100) .attr('y2', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 39 }) .attr('stroke-width', 2) .attr('stroke', '#FFF'); //Membership text membershipNode.append('text') .attr('x', 106) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 24 }) .attr('style', 'font-family: Arial; font-size: 14px') .attr('fill', '#FFF') .attr('style','cursor:default') .text(function (d) { return d.text }); //Membership arrow membershipNode.append('image') .attr('class', 'link') .attr('x', 250) .attr('y', function (d, i) { return 40 + i * (rect_h + rect_margin_h) + 11 }) .attr('width', 16) .attr('height', 16) .attr('style','cursor:pointer') .attr('data-url', function (d) { return d.url }) .attr('xlink:href', '@(Url.Content("~/Images/svg-view.png"))'); var hasMemberships = _.filter(site,function(d){ return d.membership > -1; }); var hasContents = _.filter(site,function(d){ return d.content > -1; }); // lines var site_member_lines = svg.selectAll('line.site_member').data(hasMemberships).enter().append('line'); var site_content_lines = svg.selectAll('line.site_content').data(hasContents).enter().append('line'); site_member_lines.attr('x1', w / 100 * 30 + 70) .attr('y1', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + rect_h / 2 }) .attr('x2', w / 100 * 20 + 70) .attr('y2', function (d) { return 40 + d.membership * (rect_h + rect_margin_h) + rect_h / 2 }) .attr('class', 'member-line') .attr('stroke', '#BBB'); site_content_lines.attr('x1', w / 100 * 50 + 70) .attr('y1', function (d) { return 40 + d.num * (rect_h + rect_margin_h) + rect_h / 2 }) .attr('x2', w / 100 * 60 + 70) .attr('y2', function (d) { return 40 + d.content * (rect_h + rect_margin_h) + rect_h / 2 }) .attr('class', 'content-line') .attr('stroke', '#BBB'); // Show relation $('g.site').on('mouseenter', function () { $('.block.relation').addClass('hover'); $(this).attr('class',$(this).attr('class')+' hover'); var site_name = $(this).data('name'); for (var i = 0; i < site.length; i++) { if (site[i]['name'] == site_name) { var index = i; break; } else { continue; } } var content_index = site[index]['content']; var membership_index = site[index]['membership']; if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class') + ' hover'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class') + ' hover'); } $(this).on('click', function(){ $('.block.relation').addClass('active'); $('.block.relation .node.active').each(function(){ $(this).attr('class',$(this).attr('class').replace(/active/g,'')) }); $(this).attr('class',$(this).attr('class')+' active'); if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class')+' active'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class')+' active'); } }); }).on('mouseleave', function(){ $('.block.relation').removeClass('hover'); $('.block.relation .node.hover').each(function(){ $(this).attr('class',$(this).attr('class').replace(/hover/g,'')); }); }); $('g.content').on('mouseenter', function () { $('.block.relation').addClass('hover'); $(this).attr('class',$(this).attr('class')+' hover'); var content_name = $(this).data('name'); for(var i=0;i<content.length;i++){ if(content[i].name==content_name){ var index = i; break; } else { continue; } } for (var i = 0; i < site.length; i++) { if (site[i]['content'] == index) { $('g.site').eq(site[i]['num']).attr('class',$('g.site').eq(site[i]['num']).attr('class')+' hover'); var content_index = site[i]['content']; var membership_index = site[i]['membership']; if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class')+' hover'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class')+' hover'); } } } $(this).on('click', function(){ $('.block.relation').addClass('active'); $('.block.relation .node.active').each(function(){ $(this).attr('class',$(this).attr('class').replace(/active/g,'')) }); $(this).attr('class',$(this).attr('class')+' active'); for (var i = 0; i < site.length; i++) { if (site[i]['content'] == index) { $('g.site').eq(site[i]['num']).attr('class',$('g.site').eq(site[i]['num']).attr('class')+' active'); var content_index = site[i]['content']; var membership_index = site[i]['membership']; if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class')+' active'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class')+' active'); } } } }); }).on('mouseleave', function(e){ $('.block.relation').removeClass('hover'); $('.block.relation .node.hover').each(function(){ $(this).attr('class',$(this).attr('class').replace(/hover/g,'')); }); }); $('g.membership').on('mouseenter', function () { $('.block.relation').addClass('hover'); $(this).attr('class',$(this).attr('class')+' hover'); var membership_name = $(this).data('name'); for(var i=0;i<membership.length;i++){ if(membership[i].name==membership_name){ var index = i; break; } else { continue; } } for (var i = 0; i < site.length; i++) { if (site[i]['membership'] == index) { $('g.site').eq(site[i]['num']).attr('class',$('g.site').eq(site[i]['num']).attr('class')+' hover'); var content_index = site[i]['content']; var membership_index = site[i]['membership']; if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class')+' hover'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class')+' hover'); } } } $(this).on('click', function(e){ $('.block.relation').addClass('active'); $('.block.relation .node.active').each(function(){ $(this).attr('class',$(this).attr('class').replace(/active/g,'')) }); $(this).attr('class',$(this).attr('class')+' active'); for (var i = 0; i < site.length; i++) { if (site[i]['membership'] == index) { $('g.site').eq(site[i]['num']).attr('class',$('g.site').eq(site[i]['num']).attr('class')+' active'); var content_index = site[i]['content']; var membership_index = site[i]['membership']; if(content_index > -1){ $('g.content').eq(content_index).attr('class',$('g.content').eq(content_index).attr('class')+' active'); } if(membership_index > -1){ $('g.membership').eq(membership_index).attr('class',$('g.membership').eq(membership_index).attr('class')+' active'); } } } }); }).on('mouseleave', function(){ $('.block.relation').removeClass('hover'); $('.block.relation .node.hover').each(function(){ $(this).attr('class',$(this).attr('class').replace(/hover/g,'')); }); }); $('html').on('click', function(e){ var target = $(e.target); if(target.parents('g').length < 1){ $('.block.relation').removeClass('active'); $('.block.relation .node.active').each(function(){ $(this).attr('class',$(this).attr('class').replace(/active/g,'')); }) } }); $('image.link, rect.empty, text.empty').on('click', function () { location.href= $(this).data('url'); }); </script>
the_stack
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <meta charset="UTF-8"> <title>DrugInfo</title> @*Easyui需要引入的文件*@ <script type="text/javascript" src="~/Content/jquery-easyui-1.4.5/jquery.min.js"></script> <script type="text/javascript" src="~/Content/jquery-easyui-1.4.5/jquery.easyui.min.js"></script> <link href="~/Content/jquery-easyui-1.4.5/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/jquery-easyui-1.4.5/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery.validate.min.js"></script> <script type="text/javascript" src="~/Content/Site.js"></script> <script type="text/javascript"> $(function () { //初始化datagrid InitGrid(); InitDialog(); InitControl(); $('#btnReload').click(function () { $("#grid").datagrid("reload"); }); //ajax提交修改表单 $('#ok').click(function () { $('#errdiv').removeClass('dis'); $('#form').submit(); }); $('#cancel').click(function () { $('#dd').dialog('close'); }); $('#add').click(function () { $('#errdiv').attr('class', 'dis'); $('#form')[0].reset(); $('#key').val(0); $('#PhaCode').removeAttr("disabled"); $('#PhaName').removeAttr("disabled"); $('#dd').dialog('open'); }); $('#del').click(function () { getAjax("../DrugManagement/Del", { id: $('#del_id').val() }, function (data) { if ($('#del_id').val() == null || $('#del_id').val() == "") return false; if (data) { $.messager.alert('提示', '操作失败!'); $('#dd').dialog('close'); $("#grid").datagrid("reload"); return true; } else { $.messager.alert('提示', '操作失败!'); return false; } }); }); }); //实现对DataGird控件的绑定操作 function InitGrid() { $('#grid').datagrid({ url: '../DrugManagement/LoadList', fit: true, nowrap: true,//单行显示 autoRowHeight: false, striped: false, //斑马纹 collapsible: true, //可折叠 singleSelect: true, pagination: true, pageSize: 20, fitColumns: true, //自适应列宽 rownumbers: true, sortName: 'PhaCode', //根据某个字段给easyUI排序 sortOrder: 'asc', remoteSort: true, loadMsg: '加载中,请等待', queryParams: ({ query: $('#itemid').val() }), //异步查询的参数 columns: [[ { title: '药品编号', field: 'PhaCode', hidden: true }, { title: '药品名称', field: 'PhaName', width: 120, sortable: true }, { title: '药品规格', field: 'Spec', width: 80, sortable: true }, { title: '药品单位', field: 'Unit', width: 60, sortable: true, align: 'center' }, { title: '剂型', field: 'DosageName', width: 60, sortable: true, align: 'center' }, { title: '特殊药品', field: 'IsSpecial', width: 60, sortable: true, align: 'center', formatter: function (value, row, index) { if (value) { return "是"; } else { return "否"; } } }, { title: '所属仓库', field: 'RepoName', width: 80, sortable: true, align: 'center' }, { title: '药品属性', field: 'PhaAttrName', width: 80, sortable: true, align: 'center' }, { title: '拼音码', field: 'PinyinCode', width: 90 }, { title: '五笔码', field: 'WubiCode', width: 90 }, ]], toolbar: '#tb', onDblClickRow: function (rowIndex, rowData) { $('#PhaCode').attr('disabled', 'disabled'); $('#PhaName').attr('disabled', 'disabled'); //$('#errdiv').attr('class', 'dis'); getAjax("../DrugManagement/LoadForm", { id: rowData['PhaCode'] }, function (data) { var data = eval("(" + data + ")"); SetWebControls(data); }); $('#key').val(1); $('#dd').window('open'); }, onClickRow: function (index, row) { $('#del_id').val(row['PhaCode']); } }) var p = $('#grid').datagrid('getPager'); $(p).pagination({ pageSize: 20, pageList: [10, 12, 20, 40, 60, 100, 200], beforePageText: '第', afterPageText: '页 共 {pages} 页', displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录', }); }; function InitDialog() { $('#dd').dialog({ title: '修改信息', width: 700, height: 360, top: ($(window).height() - 360) * 0.5, //居中 left: ($(window).width() - 700) * 0.5, closed: true, cache: false, modal: true, buttons: '#dlg-buttons' }); } //绑定下拉框 function InitControl() { var dataJson = ""; getAjax("/DrugManagement/LoadSelectDosageForm", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#DosageForm").append($("<option></option>").val(datajson[i].DosageID).html(datajson[i].DosageName)); }); }) dataJson = ""; getAjax("/DrugManagement/LoadSelectRepo", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#Repo").append($("<option></option>").val(datajson[i].RepoID).html(datajson[i].RepoName)); }); }) dataJson = ""; getAjax("/DrugManagement/LoadSelecDispenseWay", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#DispenseWay").append($("<option></option>").val(datajson[i].DispenseWayID).html(datajson[i].DispenseWayName)); }); }) dataJson = ""; getAjax("/DrugManagement/LoadSelecSc", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#StorageCondition").append($("<option></option>").val(datajson[i].StorageConditionID).html(datajson[i].StorageConditionName)); }); }) dataJson = ""; getAjax("/DrugManagement/LoadSelectPhaAttr", null, function (data) { datajson = eval("(" + data + ")"); $.each(datajson, function (i) { $("#PhaAttr").append($("<option></option>").val(datajson[i].PhaAttrID).html(datajson[i].PhaAttrName)); }); }) } </script> <script> //表单验证和提交 $(function () { $('#form').validate({ rules: { PhaName: { required: true }, PhaCode: { required: true }, Spec: { required: true }, Unit: { required: true }, DosageForm: { required: true } }, messages: { PhaName: "药品名不能为空!", PhaCode: "药品编号不能为空!", Spec: "规格不能为空!", Unit: "单位不能为空!", DosageForm: "剂型不能为空!" }, errorLabelContainer: '#errdiv>ul', wrapper: 'li', submitHandler: function (form) { var postData = GetWebControls("#form"); getAjax("/DrugManagement/AcceptClick?key=" + $('#key').val(), postData, function (data) { if (data) { //此处可以优化,提示消息可更美观。 $.messager.alert('提示', '操作成功!'); $('#dd').dialog('close'); $("#grid").datagrid("reload"); return true; } else if (data == -1) { $.messager.alert('提示', '已存在该记录或单号重复,请重新填写!'); return false; } else { $.messager.alert('提示', '操作失败!'); return false; } }); }, invalidHandler: function (form, validator) { //不通过回调 return false; } }); }); </script> <style> .dis { display: none; } fieldset { border-color: #E0ECFF; } .tb-line { margin-bottom: 5px; } .tb-col-160 { width: 160px; } .tb-col-120 { width: 120px; } .tb-col-80 { width: 80px; } </style> </head> <body style="margin:2px;padding:0"> <div> <div style="position:fixed;width:100%;height:100%"> <table id="grid"></table> </div> <input id="del_id" type="hidden" name="del_id" value="" /> <div id="tb" style="padding:3px"> <a id="add" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a> <a id="del" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-remove'">删除</a> <a id="btnReload" href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-reload'">刷新</a> <span>拼音码:</span> <input id="itemid" style="border:1px solid #ccc"> <a href="#" class="easyui-linkbutton" plain="true" onclick="InitGrid()">查找</a> </div> </div> <div id="dd" class="easyui-dialog" style="position:relative"> <form id="form" name="form" method="post"> <input id="key" type="hidden" value="" /> <fieldset> <legend>基本属性</legend> <div class="tb-line"> <span>药品编码:</span><input type="text" id="PhaCode" class="tb-col-120" name="PhaCode" value="" disabled="disabled" /> <span>药品名:</span><input type="text" id="PhaName" class="tb-col-160" name="PhaName" value="" disabled="disabled" /> <span>常用名:</span><input type="text" id="CommonName" class="tb-col-160" name="CommonName" value="" /> </div> <div class="tb-line"> <span>规 格:</span><input type="text" id="Spec" name="Spec" class="tb-col-80" value="" /> <span>单 位:</span><input type="text" id="Unit" name="Unit" class="tb-col-80" value="" /> <span>剂 型:</span><select id="DosageForm" name="DosageForm" class="tb-col-80"></select> <span>所属药库:</span><select id="Repo" name="Repo" class="tb-col-80"></select> </div> <div class="tb-line"> <span>拼音代码:</span><input type="text" id="PinyinCode" name="PinyinCode" class="tb-col-80" value="" /> <span>五笔代码:</span><input type="text" id="WubiCode" name="WubiCode" class="tb-col-80" value="" /> <span>特殊药品:</span><input type="checkbox" id="IsSpecial" name="IsSpecial" value="" /> <span>抗生素:</span><input type="checkbox" id="IsAntibiotic" name="IsAntibiotic" value="" /> <span>急诊用药:</span><input type="checkbox" id="IsEmergency" name="IsEmergency" value="" /> </div> </fieldset> <fieldset> <legend>药品包装</legend> <div class="tb-line"> <span>最小单位:</span><input type="text" id="MinUnit" class="tb-col-80" name="MinUnit" value="" /> <span>药房规格:</span><input type="text" id="PharmacySpec" class="tb-col-80" name="PharmacySpec" value="" /> <span>药房单位:</span><input type="text" id="PharmacyUnit" class="tb-col-80" name="PharmacyUnit" value="" /> <span>药房包装:</span><input type="text" id="PharmacyPack" class="tb-col-80" name="PharmacyPack" value="" /> </div> <div class="tb-line"> <span>最小包装:</span><input type="text" id="MinPack" class="tb-col-80" name="MinPack" value="" /> <span>病房规格:</span><input type="text" id="WardSpec" class="tb-col-80" name="WardSpec" value="" /> <span>病房单位:</span><input type="text" id="WardUnit" class="tb-col-80" name="WardUnit" value="" /> <span>病房包装:</span><input type="text" id="WardPack" class="tb-col-80" name="WardPack" value="" /> </div> </fieldset> <fieldset> <legend>其他</legend> <div class="tb-line"> <span>发药方式:</span><select id="DispenseWay" name="DispenseWay" class="tb-col-80"></select> <span>药品属性:</span><select id="PhaAttr" name="PhaAttr" class="tb-col-80"></select> <span>贮存条件:</span><select id="StorageCondition" name="StorageCondition" class="tb-col-80"></select> <span>是否有效:</span><input type="checkbox" id="IsValid" name="IsValid" value="" /> </div> </fieldset> <div class="errdiv" id="errdiv"> <ul></ul> </div> <div id="dlg-buttons"> <a id="ok" href="#" class="easyui-linkbutton" iconcls="icon-ok">确定</a> <a id="cancel" href="#" class="easyui-linkbutton" iconcls="icon-cancel">取消</a> </div> </form> </div> </body> </html>
the_stack
@model OCM.API.Common.Model.AddressInfo <div class="row"> <div class="col-md-12"> <!--begin map position editor--> <h3>Map Position</h3> <p class="text-info"> 1. Please begin by placing the marker for this charging location at it's exact position on the map. Alternatively you can fill out the Nearest Address information below and use that to position the map marker. </p> <div class="row" style="margin:1em;"> <div class="col-sm-6"> @if (Model.ID > 0) { <input type="button" class="btn btn-primary" value="Move marker to original position" /> } else { <input type="button" class="btn btn-primary" id="positionMarkerAtUserLocation" value="Use my current location" data-toggle="popover" data-content="Map Marker has been positioned at your current location" /> } </div> <div class="col-sm-6"> <div class="form-group"> <input type="text" class="form-control" id="text-location" placeholder="or find a place e.g. Bond Street, London, UK" /> <button type="button" class="btn btn-outline-primary" id="positionMarkerAtTextLocation"> Find Place </button> </div> </div> </div> <p class="text text-info">2. Drag the map to position the marker at the exact position of this charging equipment. </p> </div> </div> <div class="row"> <div class="col-md-12"> <div id="map-canvas" class="map-box" style="width: 100%; height: 300px; margin-bottom: 1em;"></div> <p class="well well-sm"> <span id="nearest-address"></span> <input type="button" class="btn btn-success" id="copyAddress" value="Use this as the Nearest Address &gt;&gt;" data-toggle="popover" data-content="Address has been copied to Nearest Address details" /> </p> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div> @Html.LabelFor(model => model.Latitude, new { @class = "control-label col-sm-2" }) </div> <div class="col-sm-6"> @Html.EditorFor(model => model.Latitude) @Html.ValidationMessageFor(model => model.Latitude) </div> </div> </div> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div> @Html.LabelFor(model => model.Longitude, new { @class = "control-label col-sm-2" }) </div> <div class="col-sm-6"> @Html.EditorFor(model => model.Longitude) @Html.ValidationMessageFor(model => model.Longitude) </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div id="nearbypoi" style="padding:2em;"></div> <!--end map position editor --> <!--begin nearest address details--> @Html.HiddenFor(model => model.ID) <h3 data-localize="ocm.details.location.sectionTitle">Nearest Address</h3> <p class="text-info"> Please verify the nearest address details which will appear to users who are not using the map view. </p> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.title"> @Html.LabelFor(model => model.Title) </div> <div> @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", placeholder = "General location name e.g. High Street Car Park" } }) @Html.ValidationMessageFor(model => model.Title) </div> </div> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.addressLine1"> @Html.LabelFor(model => model.AddressLine1) </div> <div> @Html.EditorFor(model => model.AddressLine1, new { htmlAttributes = new { @class = "form-control", placeholder = "First line of Address" } }) @Html.ValidationMessageFor(model => model.AddressLine1) </div> </div> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.addressLine2"> @Html.LabelFor(model => model.AddressLine2) </div> <div> @Html.EditorFor(model => model.AddressLine2, new { htmlAttributes = new { @class = "form-control", placeholder = "Second line of Address (if applicable)" } }) @Html.ValidationMessageFor(model => model.AddressLine2) </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.town"> @Html.LabelFor(model => model.Town) </div> <div> @Html.EditorFor(model => model.Town, new { htmlAttributes = new { @class = "form-control", placeholder = "City or Town Name" } }) @Html.ValidationMessageFor(model => model.Town) </div> </div> </div> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.stateOrProvince"> @Html.LabelFor(model => model.StateOrProvince) </div> <div> @Html.EditorFor(model => model.StateOrProvince, new { htmlAttributes = new { @class = "form-control", placeholder = "State, Province or Region" } }) @Html.ValidationMessageFor(model => model.StateOrProvince) </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.postcode"> @Html.LabelFor(model => model.Postcode) </div> <div> @Html.EditorFor(model => model.Postcode, new { htmlAttributes = new { @class = "form-control", placeholder = "Zip/Postal Code (if applicable)" } }) @Html.ValidationMessageFor(model => model.Postcode) </div> </div> </div> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.country"> @Html.LabelFor(model => model.Country) </div> <div> @Html.DropDownListFor(model => model.Country.ID, (SelectList)ViewBag.ReferenceData.CountryList) @Html.ValidationMessageFor(model => model.Country) </div> </div> </div> </div> <div class="form-group"> <input type="button" class="btn btn-warning" value="&lt;&lt; Position map marker at this address" id="positionMarkerFromAddress" data-toggle="popover" data-content="Marker has been moved to this address" /> </div> <!--end nearest address details --> <!--begin additional location details--> <h3>Additional Location Details</h3> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.accessComments"> @Html.LabelFor(model => model.AccessComments) </div> <div> @Html.TextAreaFor(model => model.AccessComments) @Html.ValidationMessageFor(model => model.AccessComments) </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.contactTelephone1"> @Html.LabelFor(model => model.ContactTelephone1) </div> <div> @Html.EditorFor(model => model.ContactTelephone1) @Html.ValidationMessageFor(model => model.ContactTelephone1) </div> </div> </div> <div class="col-sm-6"> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.contactTelephone2"> @Html.LabelFor(model => model.ContactTelephone2) </div> <div> @Html.EditorFor(model => model.ContactTelephone2) @Html.ValidationMessageFor(model => model.ContactTelephone2) </div> </div> </div> </div> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.contactEmail"> @Html.LabelFor(model => model.ContactEmail) </div> <div> @Html.EditorFor(model => model.ContactEmail) @Html.ValidationMessageFor(model => model.ContactEmail) </div> </div> <div class="form-group" data-editormode="core"> <div data-localize="ocm.details.location.addressRelatedURL"> @Html.LabelFor(model => model.RelatedURL) </div> <div> @Html.EditorFor(model => model.RelatedURL) @Html.ValidationMessageFor(model => model.RelatedURL) </div> </div> <!-- end additional location details--> </div> </div> <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.js'></script> <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.css' rel='stylesheet' /> <script src="@Url.Content("~/js/OCM/Editor/LocationEditor.js")?v=200"></script> <script> //go-go-gadget map @{ var scriptContent = "var locationEditor = new LocationEditor(" + Model.Latitude + ", " + Model.Longitude + ", '"+Html.IdFor(m => m.Latitude)+"','"+Html.IdFor(m => m.Longitude)+"');"; } @Html.Raw(scriptContent) var _context = this; function startEditor() { locationEditor.initializeMap('@System.Configuration.ConfigurationManager.AppSettings["MapBoxAPI"]'); @if (Model.ID <= 0 && ViewBag.EnableEditView == false) { //adding new location, get user location as starting pos <text> //for add only, get user current position by default locationEditor.getUserLocation(); </text> } } $(document).ready(function () { $("#positionMarkerAtUserLocation").click(function () { locationEditor.getUserLocation(); //hide popover after click setTimeout(function () { $('#positionMarkerAtUserLocation').popover('hide'); }, 2000); }); $("#positionMarkerAtTextLocation").click(function () { locationEditor.positionMarkerAtTextLocation($("#text-location").val()); }); $("#copyAddress").click(function () { locationEditor.useSuggestedAddress(); //hide popover after click setTimeout(function () { $('#copyAddress').popover('hide'); }, 2000); }); $("#positionMarkerFromAddress").click(function () { locationEditor.lookupAddressPosition(); //hide popover after click setTimeout(function () { $('#positionMarkerFromAddress').popover('hide'); }, 2000); }); //init popovers & button visibility $('#positionMarkerAtUserLocation').popover(); $('#copyAddress').popover(); $('#copyAddress').hide(); $('#positionMarkerFromAddress').popover(); _context.startEditor(); }); </script>
the_stack
// Install Tools #tool NuGet.CommandLine&version=5.3.1 ////////////////////////////////////////////////////////////////////// // ARGUMENTS & INITIALISATION ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var productVersion = Argument("productVersion", "3.13.0"); var ErrorDetail = new List<string>(); var installedNetCoreRuntimes = GetInstalledNetCoreRuntimes(); ////////////////////////////////////////////////////////////////////// // SET PACKAGE VERSION ////////////////////////////////////////////////////////////////////// var dash = productVersion.IndexOf('-'); var version = dash > 0 ? productVersion.Substring(0, dash) : productVersion; var isAppveyor = BuildSystem.IsRunningOnAppVeyor; ////////////////////////////////////////////////////////////////////// // DEFINE RUN CONSTANTS ////////////////////////////////////////////////////////////////////// var PROJECT_DIR = Context.Environment.WorkingDirectory.FullPath + "/"; var PACKAGE_DIR = Argument("artifact-dir", PROJECT_DIR + "package") + "/"; var BIN_DIR = PROJECT_DIR + "bin/" + configuration + "/"; var NET35_BIN_DIR = BIN_DIR + "net35/"; var NETCOREAPP21_BIN_DIR = BIN_DIR + "netcoreapp2.1/"; var NETCOREAPP31_BIN_DIR = BIN_DIR + "netcoreapp3.1/"; var CHOCO_DIR = PROJECT_DIR + "choco/"; var TOOLS_DIR = PROJECT_DIR + "tools/"; var IMAGE_DIR = PROJECT_DIR + "images/"; var MSI_DIR = PROJECT_DIR + "msi/"; var CURRENT_IMG_DIR = IMAGE_DIR + $"NUnit-{productVersion}/"; var CURRENT_IMG_NET20_BIN_DIR = CURRENT_IMG_DIR + "bin/net20/"; var EXTENSION_PACKAGES_DIR = PROJECT_DIR + "extension-packages/"; var ZIP_IMG = PROJECT_DIR + "zip-image/"; var SOLUTION_FILE = PROJECT_DIR + "NUnitConsole.sln"; var ENGINE_CSPROJ = PROJECT_DIR + "src/NUnitEngine/nunit.engine/nunit.engine.csproj"; var AGENT_CSPROJ = PROJECT_DIR + "src/NUnitEngine/nunit-agent/nunit-agent.csproj"; var ENGINE_API_CSPROJ = PROJECT_DIR + "src/NUnitEngine/nunit.engine.api/nunit.engine.api.csproj"; var ENGINE_TESTS_CSPROJ = PROJECT_DIR + "src/NUnitEngine/nunit.engine.tests/nunit.engine.tests.csproj"; var CONSOLE_CSPROJ = PROJECT_DIR + "src/NUnitConsole/nunit3-console/nunit3-console.csproj"; var CONSOLE_TESTS_CSPROJ = PROJECT_DIR + "src/NUnitConsole/nunit3-console.tests/nunit3-console.tests.csproj"; var MOCK_ASSEMBLY_CSPROJ = PROJECT_DIR + "src/NUnitEngine/mock-assembly/mock-assembly.csproj"; var NETFX_FRAMEWORKS = new [] { "net20", "net35" }; //Production code targets net20, tests target nets35 // Test Runners var NET20_CONSOLE = BIN_DIR + "net20/" + "nunit3-console.exe"; var NETCORE31_CONSOLE = BIN_DIR + "netcoreapp3.1/" + "nunit3-console.dll"; // Test Assemblies var ENGINE_TESTS = "nunit.engine.tests.dll"; var CONSOLE_TESTS = "nunit3-console.tests.dll"; // Package sources for nuget restore var PACKAGE_SOURCE = new string[] { "https://www.nuget.org/api/v2", "https://www.myget.org/F/nunit/api/v2" }; var EXTENSION_PACKAGES = new [] { "NUnit.Extension.VSProjectLoader", "NUnit.Extension.NUnitProjectLoader", "NUnit.Extension.NUnitV2Driver", "NUnit.Extension.NUnitV2ResultWriter", "NUnit.Extension.TeamCityEventListener" }; ////////////////////////////////////////////////////////////////////// // SETUP AND TEARDOWN TASKS ////////////////////////////////////////////////////////////////////// Setup(context => { if (BuildSystem.IsRunningOnAppVeyor) { var buildNumber = AppVeyor.Environment.Build.Number.ToString("00000"); var branch = AppVeyor.Environment.Repository.Branch; var isPullRequest = AppVeyor.Environment.PullRequest.IsPullRequest; if (branch == "master" && !isPullRequest) { productVersion = version + "-dev-" + buildNumber; } else { var suffix = "-ci-" + buildNumber; if (isPullRequest) suffix += "-pr-" + AppVeyor.Environment.PullRequest.Number; else if (AppVeyor.Environment.Repository.Branch.StartsWith("release", StringComparison.OrdinalIgnoreCase)) suffix += "-pre-" + buildNumber; else suffix += "-" + System.Text.RegularExpressions.Regex.Replace(branch, "[^0-9A-Za-z-]+", "-"); // NuGet limits "special version part" to 20 chars. Add one for the hyphen. if (suffix.Length > 21) suffix = suffix.Substring(0, 21); productVersion = version + suffix; } AppVeyor.UpdateBuildVersion(productVersion); } // Executed BEFORE the first task. Information("Building {0} version {1} of NUnit Console/Engine.", configuration, productVersion); }); Teardown(context => { // Executed AFTER the last task. CheckForError(ref ErrorDetail); }); ////////////////////////////////////////////////////////////////////// // CLEAN ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Cleans directories.") .Does(() => { CleanDirectory(PROJECT_DIR + "bin/"); CleanDirectory(PROJECT_DIR + "packages/"); CleanDirectory(IMAGE_DIR); CleanDirectory(EXTENSION_PACKAGES_DIR); CleanDirectory(ZIP_IMG); CleanDirectory(PACKAGE_DIR); }); ////////////////////////////////////////////////////////////////////// // INITIALIZE FOR BUILD ////////////////////////////////////////////////////////////////////// Task("UpdateAssemblyInfo") .Description("Sets the assembly versions to the calculated version.") .Does(() => { PatchAssemblyInfo("src/NUnitConsole/ConsoleVersion.cs", productVersion, version); PatchAssemblyInfo("src/NUnitEngine/EngineApiVersion.cs", productVersion, assemblyVersion: null); PatchAssemblyInfo("src/NUnitEngine/EngineVersion.cs", productVersion, version); }); ////////////////////////////////////////////////////////////////////// // BUILD ENGINE AND CONSOLE ////////////////////////////////////////////////////////////////////// MSBuildSettings CreateMSBuildSettings(string target) { var settings = new MSBuildSettings() .SetConfiguration(configuration) .SetVerbosity(Verbosity.Minimal) .WithProperty("PackageVersion", productVersion) .WithTarget(target) // Workaround for https://github.com/Microsoft/msbuild/issues/3626 .WithProperty("AddSyntheticProjectReferencesForSolutionDependencies", "false"); if (IsRunningOnWindows()) { // The fallback is in case only a preview of VS is installed. var vsInstallation = VSWhereLatest(new VSWhereLatestSettings { Requires = "Microsoft.Component.MSBuild" }) ?? VSWhereLatest(new VSWhereLatestSettings { Requires = "Microsoft.Component.MSBuild", IncludePrerelease = true }); if (vsInstallation != null) { var msBuildPath = vsInstallation.CombineWithFilePath(@"MSBuild\Current\Bin\MSBuild.exe"); if (!FileExists(msBuildPath)) msBuildPath = vsInstallation.CombineWithFilePath(@"MSBuild\15.0\Bin\MSBuild.exe"); if (FileExists(msBuildPath)) settings.ToolPath = msBuildPath; } } return settings; } Task("Build") .Description("Builds the engine and console") .IsDependentOn("CheckHeaders") .IsDependentOn("UpdateAssemblyInfo") .Does(() => { MSBuild(SOLUTION_FILE, CreateMSBuildSettings("Build").WithRestore()); Information("Publishing .NET Core & Standard projects so that dependencies are present..."); foreach(var framework in new [] { "netstandard2.0", "netcoreapp3.1" }) MSBuild(ENGINE_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", framework) .WithProperty("PublishDir", BIN_DIR + framework)); foreach (var framework in new[] { "netcoreapp3.1" }) MSBuild(AGENT_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", framework) .WithProperty("PublishDir", BIN_DIR + "agents/" + framework)); foreach (var framework in new[] { "netstandard2.0" }) MSBuild(ENGINE_API_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", framework) .WithProperty("PublishDir", BIN_DIR + framework)); foreach (var framework in new [] { "netcoreapp2.1", "netcoreapp3.1" }) MSBuild(ENGINE_TESTS_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", framework) .WithProperty("PublishDir", BIN_DIR + framework)); MSBuild(CONSOLE_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", "netcoreapp3.1") .WithProperty("PublishDir", BIN_DIR + "netcoreapp3.1")); MSBuild(CONSOLE_TESTS_CSPROJ, CreateMSBuildSettings("Publish") .WithProperty("TargetFramework", "netcoreapp3.1") .WithProperty("PublishDir", BIN_DIR + "netcoreapp3.1")); }); ////////////////////////////////////////////////////////////////////// // BUILD C++ TESTS ////////////////////////////////////////////////////////////////////// Task("BuildCppTestFiles") .Description("Builds the C++ mock test assemblies") .WithCriteria(IsRunningOnWindows) .Does(() => { MSBuild( "./src/NUnitEngine/mock-cpp-clr/mock-cpp-clr-x86.vcxproj", CreateMSBuildSettings("Build").WithProperty("Platform", "x86")); MSBuild( "./src/NUnitEngine/mock-cpp-clr/mock-cpp-clr-x64.vcxproj", CreateMSBuildSettings("Build").WithProperty("Platform", "x64")); }); ////////////////////////////////////////////////////////////////////// // TEST ////////////////////////////////////////////////////////////////////// Task("CheckForError") .Description("Checks for errors running the test suites") .Does(() => CheckForError(ref ErrorDetail)); ////////////////////////////////////////////////////////////////////// // TEST ENGINE ////////////////////////////////////////////////////////////////////// Task("TestNet20Engine") .Description("Tests the engine") .IsDependentOn("Build") .OnError(exception => { ErrorDetail.Add(exception.Message); }) .Does(() => { RunTest(NET20_CONSOLE, NET35_BIN_DIR, ENGINE_TESTS, "net35", ref ErrorDetail); }); ////////////////////////////////////////////////////////////////////// // TEST .NET 2.0 CONSOLE ////////////////////////////////////////////////////////////////////// Task("TestNet20Console") .Description("Tests the .NET 2.0 console runner") .IsDependentOn("Build") .OnError(exception => { ErrorDetail.Add(exception.Message); }) .Does(() => { RunTest(NET20_CONSOLE, NET35_BIN_DIR, CONSOLE_TESTS, "net35", ref ErrorDetail); }); ////////////////////////////////////////////////////////////////////// // TEST .NET CORE 3.1 CONSOLE ////////////////////////////////////////////////////////////////////// Task("TestNetCore31Console") .Description("Tests the .NET Core 3.1 console runner") .IsDependentOn("Build") .OnError(exception => { ErrorDetail.Add(exception.Message); }) .Does(() => { var runtimes = new[] { "3.1", "5.0" }; foreach (var runtime in runtimes) { RunDotnetCoreTests( NETCORE31_CONSOLE, NETCOREAPP31_BIN_DIR, CONSOLE_TESTS, runtime, ref ErrorDetail); } }); ////////////////////////////////////////////////////////////////////// // TEST NETSTANDARD 2.0 ENGINE ////////////////////////////////////////////////////////////////////// Task("TestNetStandard20Engine") .Description("Tests the .NET Standard Engine") .IsDependentOn("Build") .OnError(exception => { ErrorDetail.Add(exception.Message); }) .Does(() => { RunDotnetCoreNUnitLiteTests( NETCOREAPP21_BIN_DIR + ENGINE_TESTS, NETCOREAPP21_BIN_DIR, "netcoreapp2.1", ref ErrorDetail); }); ////////////////////////////////////////////////////////////////////// // TEST NETCORE 3.1 ENGINE ////////////////////////////////////////////////////////////////////// Task("TestNetCore31Engine") .Description("Tests the .NET Core 3.1 Engine") .IsDependentOn("Build") .OnError(exception => { ErrorDetail.Add(exception.Message); }) .Does(() => { var runtimes = new[] { "3.1", "5.0" }; foreach (var runtime in runtimes) { RunDotnetCoreTests( NETCORE31_CONSOLE, NETCOREAPP31_BIN_DIR, ENGINE_TESTS, runtime, ref ErrorDetail); } }); ////////////////////////////////////////////////////////////////////// // PACKAGE ////////////////////////////////////////////////////////////////////// var RootFiles = new FilePath[] { "LICENSE.txt", "NOTICES.txt", "CHANGES.txt", "nunit.ico" }; Task("CreateImage") .Description("Copies all files into the image directory") .Does(() => { CleanDirectory(CURRENT_IMG_DIR); CopyFiles(RootFiles, CURRENT_IMG_DIR); CopyDirectory(BIN_DIR, CURRENT_IMG_DIR + "bin/"); }); Task("BuildNuGetPackages") .Description("Creates NuGet packages of the engine/console") .IsDependentOn("CreateImage") .Does(() => { CreateDirectory(PACKAGE_DIR); NuGetPack("nuget/engine/nunit.engine.api.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/engine/nunit.engine.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/runners/nunit.console-runner.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/runners/nunit.console-runner-with-extensions.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/runners/nunit.console-runner.netcore.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/deprecated/nunit.runners.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); NuGetPack("nuget/deprecated/nunit.engine.netstandard.nuspec", new NuGetPackSettings() { Version = productVersion, BasePath = CURRENT_IMG_DIR, OutputDirectory = PACKAGE_DIR, NoPackageAnalysis = true }); }); Task("TestNuGetPackages") .Does(() => { new NuGetNetFXPackageTester(Context, productVersion).RunTests(); new NuGetNetCorePackageTester(Context, productVersion).RunTests(); }); Task("BuildChocolateyPackages") .Description("Creates chocolatey packages of the console runner") .Does(() => { EnsureDirectoryExists(PACKAGE_DIR); ChocolateyPack("choco/nunit-console-runner.nuspec", new ChocolateyPackSettings() { Version = productVersion, OutputDirectory = PACKAGE_DIR, Files = new [] { new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "LICENSE.txt", Target = "tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "NOTICES.txt", Target = "tools" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "VERIFICATION.txt", Target = "tools" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit.choco.addins", Target = "tools" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit.agent.addins", Target = "tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit.agent.addins", Target = "tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit.agent.addins", Target = "tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit-agent.exe", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit-agent.exe.config", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit-agent.exe.ignore", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit-agent-x86.exe", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit-agent-x86.exe.config", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit-agent-x86.exe.ignore", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit.engine.api.dll", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit.engine.api.xml", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/nunit.engine.core.dll", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net20/testcentric.engine.metadata.dll", Target="tools/agents/net20" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit-agent.exe", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit-agent.exe.config", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit-agent.exe.ignore", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit-agent-x86.exe", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit-agent-x86.exe.config", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit-agent-x86.exe.ignore", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit.engine.api.dll", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit.engine.api.xml", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/nunit.engine.core.dll", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/net40/testcentric.engine.metadata.dll", Target="tools/agents/net40" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit-agent.dll", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit-agent.dll.config", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit-agent.deps.json", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit-agent.runtimeconfig.json", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "nunit-agent.exe.ignore", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit.engine.api.dll", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit.engine.api.xml", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/nunit.engine.core.dll", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "bin/agents/netcoreapp3.1/testcentric.engine.metadata.dll", Target="tools/agents/netcoreapp3.1" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit3-console.exe", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit3-console.exe.config", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit.engine.api.dll", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit.engine.api.xml", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit.engine.core.dll", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "nunit.engine.dll", Target="tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_NET20_BIN_DIR + "testcentric.engine.metadata.dll", Target="tools" } } }); ChocolateyPack("choco/nunit-console-with-extensions.nuspec", new ChocolateyPackSettings() { Version = productVersion, OutputDirectory = PACKAGE_DIR, Files = new [] { new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "LICENSE.txt", Target = "tools" }, new ChocolateyNuSpecContent { Source = CURRENT_IMG_DIR + "NOTICES.txt", Target = "tools" }, new ChocolateyNuSpecContent { Source = CHOCO_DIR + "VERIFICATION.txt", Target = "tools" } } }); }); Task("TestChocolateyPackage") .Does(() => { new ChocolateyPackageTester(Context, productVersion).RunTests(); }); ////////////////////////////////////////////////////////////////////// // PACKAGE COMBINED DISTRIBUTIONS ////////////////////////////////////////////////////////////////////// Task("FetchExtensions") .Does(() => { CleanDirectory(EXTENSION_PACKAGES_DIR); foreach(var package in EXTENSION_PACKAGES) { NuGetInstall(package, new NuGetInstallSettings { OutputDirectory = EXTENSION_PACKAGES_DIR, Source = new [] { "https://www.nuget.org/api/v2" } }); } }); Task("CreateCombinedImage") .IsDependentOn("CreateImage") .IsDependentOn("FetchExtensions") .Does(() => { foreach(var framework in NETFX_FRAMEWORKS) { var addinsImgDir = CURRENT_IMG_DIR + "bin/" + framework +"/addins/"; CopyDirectory(MSI_DIR + "resources/", CURRENT_IMG_DIR); CleanDirectory(addinsImgDir); foreach(var packageDir in GetAllDirectories(EXTENSION_PACKAGES_DIR)) CopyPackageContents(packageDir, addinsImgDir); } }); Task("BuildMsiPackage") .IsDependentOn("CreateCombinedImage") .Does(() => { MSBuild(MSI_DIR + "nunit/nunit.wixproj", new MSBuildSettings() .WithTarget("Rebuild") .SetConfiguration(configuration) .WithProperty("Version", version) .WithProperty("DisplayVersion", version) .WithProperty("OutDir", PACKAGE_DIR) .WithProperty("Image", CURRENT_IMG_DIR) .SetMSBuildPlatform(MSBuildPlatform.x86) .SetNodeReuse(false) ); }); Task("TestMsiPackage") .Does(() => { new MsiPackageTester(Context, version).RunTests(); }); Task("BuildZipPackage") .IsDependentOn("CreateCombinedImage") .Does(() => { CleanDirectory(ZIP_IMG); CopyDirectory(CURRENT_IMG_DIR, ZIP_IMG); foreach(var framework in NETFX_FRAMEWORKS) { //Ensure single and correct addins file (.NET Framework only) var netfxZipImg = ZIP_IMG + "bin/" + framework + "/"; DeleteFiles(ZIP_IMG + "*.addins"); DeleteFiles(netfxZipImg + "*.addins"); CopyFile(CURRENT_IMG_DIR + "nunit.bundle.addins", netfxZipImg + "nunit.bundle.addins"); } var zipPath = string.Format("{0}NUnit.Console-{1}.zip", PACKAGE_DIR, productVersion); Zip(ZIP_IMG, zipPath); }); Task("TestZipPackage") .Does(() => { new ZipPackageTester(Context, productVersion).RunTests(); }); Task("InstallSigningTool") .Does(() => { var result = StartProcess("dotnet.exe", new ProcessSettings { Arguments = "tool install SignClient --global" }); }); Task("SignPackages") .IsDependentOn("InstallSigningTool") .IsDependentOn("Package") .Does(() => { // Get the secret. var secret = EnvironmentVariable("SIGNING_SECRET"); if(string.IsNullOrWhiteSpace(secret)) { throw new InvalidOperationException("Could not resolve signing secret."); } // Get the user. var user = EnvironmentVariable("SIGNING_USER"); if(string.IsNullOrWhiteSpace(user)) { throw new InvalidOperationException("Could not resolve signing user."); } var signClientPath = Context.Tools.Resolve("SignClient.exe") ?? Context.Tools.Resolve("SignClient") ?? throw new Exception("Failed to locate sign tool"); var settings = File("./signclient.json"); // Get the files to sign. var files = GetFiles(string.Concat(PACKAGE_DIR, "*.nupkg")) + GetFiles(string.Concat(PACKAGE_DIR, "*.msi")); foreach(var file in files) { Information("Signing {0}...", file.FullPath); // Build the argument list. var arguments = new ProcessArgumentBuilder() .Append("sign") .AppendSwitchQuoted("-c", MakeAbsolute(settings.Path).FullPath) .AppendSwitchQuoted("-i", MakeAbsolute(file).FullPath) .AppendSwitchQuotedSecret("-s", secret) .AppendSwitchQuotedSecret("-r", user) .AppendSwitchQuoted("-n", "NUnit.org") .AppendSwitchQuoted("-d", "NUnit is a unit-testing framework for all .NET languages.") .AppendSwitchQuoted("-u", "https://nunit.org/"); // Sign the binary. var result = StartProcess(signClientPath.FullPath, new ProcessSettings { Arguments = arguments }); if(result != 0) { // We should not recover from this. throw new InvalidOperationException("Signing failed!"); } } }); Task("CheckPackageContent") .Description("Check content of all the packages we build") .Does(() => { CheckAllPackages(); }); Task("ListInstalledNetCoreRuntimes") .Description("Lists all installed .NET Core Runtimes") .Does(() => { var runtimes = GetInstalledNetCoreRuntimes(); foreach (var runtime in runtimes) { Information(runtime); } }); ////////////////////////////////////////////////////////////////////// // HELPER METHODS - GENERAL ////////////////////////////////////////////////////////////////////// bool CheckIfDotNetCoreInstalled() { try { Information("Checking if .NET Core SDK is installed..."); StartProcess("dotnet", new ProcessSettings { Arguments = "--info" }); } catch(Exception) { Warning(".NET Core SDK is not installed. It can be installed from https://www.microsoft.com/net/core"); return false; } return true; } void CheckForError(ref List<string> errorDetail) { if(errorDetail.Count != 0) { var copyError = new List<string>(); copyError = errorDetail.Select(s => s).ToList(); errorDetail.Clear(); throw new Exception("One or more unit tests failed, breaking the build.\n" + copyError.Aggregate((x,y) => x + "\n" + y)); } } ////////////////////////////////////////////////////////////////////// // HELPER METHODS - TEST ////////////////////////////////////////////////////////////////////// FilePath GetResultXmlPath(string testAssembly, string framework) { var assemblyName = System.IO.Path.GetFileNameWithoutExtension(testAssembly); // Required for test suites running under NUnitLite CreateDirectory($@"test-results\{framework}"); return MakeAbsolute(new FilePath($@"test-results\{framework}\{assemblyName}.xml")); } void RunTest(FilePath exePath, DirectoryPath workingDir, string testAssembly, string framework, ref List<string> errorDetail) { int rc = StartProcess( MakeAbsolute(exePath), new ProcessSettings() { Arguments = new ProcessArgumentBuilder() .Append(testAssembly) .AppendSwitchQuoted("--result", ":", GetResultXmlPath(testAssembly, framework).FullPath) .Render(), WorkingDirectory = workingDir }); if (rc > 0) errorDetail.Add(string.Format("{0}: {1} tests failed", framework, rc)); else if (rc < 0) errorDetail.Add(string.Format("{0} returned rc = {1}", exePath, rc)); } void RunDotnetCoreNUnitLiteTests(FilePath exePath, DirectoryPath workingDir, string framework, ref List<string> errorDetail) { RunDotnetCoreTests(exePath, workingDir, arguments: null, framework, ref errorDetail); } void RunDotnetCoreTests(FilePath exePath, DirectoryPath workingDir, string arguments, string framework, ref List<string> errorDetail) { //Filename is first arg if running on NUnit Console, or exePath if running NUnitLite tests var fileName = arguments ?? exePath.GetFilename(); //Find most suitable runtime var fxVersion = new string(framework.SkipWhile(c => !char.IsDigit(c)).ToArray()); //Select latest runtime matching requested major/minor version var selectedFramework = installedNetCoreRuntimes.Where(v => v.StartsWith(fxVersion)).OrderByDescending(Version.Parse).FirstOrDefault(); if (selectedFramework == null) { var msg = $"No suitable runtime found to run tests under {framework}"; if (!BuildSystem.IsLocalBuild) throw new Exception(msg); Warning(msg); return; } else { Information($"Runtime framework version {selectedFramework} selected to run {fileName} for {framework}."); } //Run Tests var args = new ProcessArgumentBuilder() .AppendSwitch("--fx-version", " ", selectedFramework) .AppendQuoted(exePath.FullPath) .Append(arguments) .AppendSwitchQuoted("--result", ":", GetResultXmlPath(exePath.FullPath, framework).FullPath) .Render(); int rc = StartProcess( "dotnet", new ProcessSettings { Arguments = args, WorkingDirectory = workingDir }); if (rc > 0) errorDetail.Add(string.Format("{0}: {1} tests failed", framework, rc)); else if (rc < 0) errorDetail.Add(string.Format("{0} returned rc = {1}", exePath, rc)); } public List<string> GetInstalledNetCoreRuntimes() { var list = new List<string>(); var process = StartProcess("dotnet", new ProcessSettings { Arguments = "--list-runtimes", RedirectStandardOutput = true, RedirectedStandardOutputHandler = s => { if (s == null || !s.StartsWith("Microsoft.NETCore.App")) return s; var version = s.Split(' ')[1]; list.Add(version); return s; } }); return list; } ////////////////////////////////////////////////////////////////////// // HELPER METHODS - PACKAGE ////////////////////////////////////////////////////////////////////// public string[] GetAllDirectories(string dirPath) { return System.IO.Directory.GetDirectories(dirPath); } public void CopyPackageContents(DirectoryPath packageDir, DirectoryPath outDir) { var files = GetFiles(packageDir + "/tools/*").Concat(GetFiles(packageDir + "/tools/net20/*")); CopyFiles(files.Where(f => f.GetExtension() != ".addins"), outDir); } ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Rebuild") .Description("Rebuilds the engine and console runner") .IsDependentOn("Clean") .IsDependentOn("Build"); Task("TestConsole") .Description("Builds and tests the console runner") .IsDependentOn("TestNet20Console") .IsDependentOn("TestNetCore31Console"); Task("TestEngine") .Description("Builds and tests the engine") .IsDependentOn("TestNet20Engine") .IsDependentOn("TestNetStandard20Engine") .IsDependentOn("TestNetCore31Engine"); Task("Test") .Description("Builds and tests the engine") .IsDependentOn("TestEngine") .IsDependentOn("TestConsole"); Task("BuildPackages") .Description("Builds all packages for distribution") .IsDependentOn("BuildNuGetPackages") .IsDependentOn("BuildChocolateyPackages") .IsDependentOn("BuildMsiPackage") .IsDependentOn("BuildZipPackage"); Task("TestPackages") .Description("Tests the packages") .IsDependentOn("TestNuGetPackages") .IsDependentOn("TestChocolateyPackage") .IsDependentOn("TestMsiPackage") .IsDependentOn("TestZipPackage"); Task("Package") .Description("Builds and tests all packages") .IsDependentOn("CheckForError") .IsDependentOn("BuildPackages") .IsDependentOn("CheckPackageContent") .IsDependentOn("TestPackages"); Task("Appveyor") .Description("Builds, tests and packages on AppVeyor") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Package"); Task("Default") .Description("Builds the engine and console runner") .IsDependentOn("Build"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
the_stack
@model ZLMediaServerManagent.Models.ViewDto.StreamProxyDataSourceDto <link rel="stylesheet" href="/assets/js/vendor/owl-carousel/css/owl.carousel.css"> <link rel="stylesheet" href="/assets/js/vendor/owl-carousel/css/owl.theme.css"> <!-- tile --> <section class="tile color transparent-black"> <!-- tile header --> <div class="tile-header"> <h1><strong>拉流</strong> 列表</h1> <div class="controls"> <!-- <a href="#" class="refresh"><i class="fa fa-refresh"></i></a> --> <!-- <a href="#" class="remove"><i class="fa fa-times"></i></a> --> </div> </div> <!-- /tile header --> <!-- tile body --> <div class="tile-body"> <form class="layui-form" role="form" onsubmit="return false;"> <div class="row"> <div class="col-md-3"> <div class="layui-inline layui-col-md12"> <label class="layui-form-label" style="color: #FFF;">域名:</label> <div class="layui-input-block"> <select name="Sel_Domain" id="Sel_Domain" lay-search lay-filter="Sel_Domain" style="height: 40px !important;"> <option value="">全部</option> </select> </div> </div> </div> <div class="col-md-3"> <div class="layui-inline layui-col-md12"> <label class="layui-form-label" style="color: #FFF;">应用:</label> <div class="layui-input-block"> <select name="Sel_Application" id="Sel_Application" lay-search lay-filter="Sel_Application" style="height: 40px !important;"> <option value="">全部</option> </select> </div> </div> </div> <div class="col-md-4"> <div class="layui-inline layui-col-md12"> <label class="layui-form-label" style="color: #FFF;">Id/名称:</label> <div class="layui-input-block"> <input type="text" name="txt_keyword" id="txt_keyword" placeholder="请输入关键字" class="layui-input"> </div> </div> </div> <div class="col-md-2"> <div class="layui-inline" style="line-height: 0px;margin-bottom: 12px; "> <button class="layui-btn layui-btn-normal" data-type="reload" lay-submit lay-filter="LAY-app-contlist-search" onclick="reload()"> <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i> </button> </div> </div> </div> </form> <div class="layui-form layui-card-header layuiadmin-card-header-auto" style="border-bottom:1px solid rgba(0, 0, 0, 0.2)"></div> <table class="layui-hide" id="streamProxyList" lay-filter="streamProxyList"></table> </div> <!-- /tile body --> <!-- 主页内容 --> <div class="row"> </div> <!-- 主页内容 --> </section> <script src="/assets/js/vendor/owl-carousel/owl.carousel.min.js"></script> <!-- /tile --> @if(Model.Power.Add) { <button class="mdui-fab mdui-fab-fixed mdui-ripple" style="color:#FFF;background-color: #EC5281; margin-right: 30px;" onclick="addStreamProxy()"><i class="fa fa-plus" aria-hidden="true"></i></button> } <script> var domains = JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Domains.Select(p=>new {Id=p.Id+"",Name=p.DomainName}).ToList()))'); var applications = JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Applications.Select(p=>new {Id=p.Id+"",Name=p.AppName,DomainId=p.DomainId+""}).ToList()))'); var canAddDomainAndApp =@Model.Power.Audit.ToString().ToLower(); domains.forEach(v => $("#Sel_Domain").append("<option value='" + v.Id + "'>" + v.Name + "</option>")); var streamProxyId=''; layui.use(['form', 'layedit', 'laydate', 'table'], function () { var form = layui.form , layer = layui.layer , layedit = layui.layedit , laydate = layui.laydate , table = layui.table; form.render(); table.render({ elem: '#streamProxyList' , url: '/ZLServer/StreamProxy/' , method: 'post' , cellMinWidth: 80 , autoSort: true , cols: [[ { type: 'checkbox' } , { field: 'Id', title: 'Id', hide: true, } , { field: 'DomainId', title: 'DomainId', hide: true, } , { field: 'ApplicationId', title: 'ApplicationId', hide: true } , { field: 'StreamName', title: '流名称', sort: true } , { field: 'EnableHLS', title: '转HLS', sort: true, templet: '#tfHLSTemp' } , { field: 'EnableMP4', title: '录MP4', templet: '#tfMP4Temp' } , { field: 'ShowState', title: '状态', sort: true, templet: '#statusTemp' } , { field: 'Description', title: '描述', sort: true } , { field: 'DomainName', title: '域名', sort: true } , { field: 'ApplicationName', title: '应用', sort: true } , { field: 'CreateTs', title: '创建时间', sort: true } , { field: '', title: '操作', toolbar: '#bar' } ]] , where: { DomainId: $('#Sel_Domain').val(), ApplicationId: $('#ApplicationId').val(), keyword: $('#txt_keyword').val(), } , page: true }); //监听搜索 form.on('submit(LAY-app-contlist-search)', function (data) { //执行重载 table.reload('streamProxyList', { where: { DomainId: $('#Sel_Domain').val(), ApplicationId: $('#ApplicationId').val(), keyword: $('#txt_keyword').val(), } }); }); table.on('row(streamProxyList)', function (obj) { var data = obj.data; $(obj.tr).siblings().css("background-color", ""); obj.tr.css("background-color", "rgba(0, 0, 0, 0.2)"); // obj.tr.css("background-color", "#a3cf62"); streamProxyId = data.Id; }); table.on('rowDouble(streamProxyList)', function (obj) { var data = obj.data; $(obj.tr).siblings().css("background-color", ""); obj.tr.css("background-color", "rgba(0, 0, 0, 0.2)"); // obj.tr.css("background-color", "#a3cf62"); streamProxyId = data.Id; play(streamProxyId,data.StreamName); }); table.on('sort(streamProxyList)', function (obj) { //注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值" //console.log(obj.field); //当前排序的字段名 //console.log(obj.type); //当前排序类型:desc(降序)、asc(升序)、null(空对象,默认排序) //console.log(this); //当前排序的 th 对象 //尽管我们的 table 自带排序功能,但并没有请求服务端。 //有些时候,你可能需要根据当前排序的字段,重新向服务端发送请求,从而实现服务端排序,如: table.reload('streamProxyList', { initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。 , where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式) field: obj.field //排序字段 , order: obj.type //排序方式 , DomainId: $('#Sel_Domain').val(), ApplicationId: $('#ApplicationId').val(), keyword: $('#txt_keyword').val(), } }); }); form.on('select(Sel_Domain)', function (data) { if (isEmpty(data.value)) { //清空应用选择框 $("#Sel_Application").empty(); $("#Sel_Application").append("<option value=''>全部</option>") form.render(); } else { applications.forEach(v => { if (v.DomainId === data.value) { $("#Sel_Application").append("<option value='" + v.Id + "'>" + v.Name + "</option>") } }); form.render(); } }); //监听提交 form.on('submit(submitForm)', function (data) { // showLoader('保存中....',60); // $.post("/Menu/Add", data.field, function (result) { // closeLoader(); // if (result.Flag) { // showGrowl('保存成功!', 'success', 3000); // reload(); // layer.close(layuiWindow['editMenu' + menuId]); //再执行关闭 // } // else { // showGrowl(result.Msg,'danger',4000); // } // }); // return false; }); }); function addStreamProxy() { if (!canAddDomainAndApp) { showGrowl('请先添加域名和应用再添加拉流代理!', 'danger', 4000); return; } get('/ZLServer/AddStreamProxy', function (data, status, xhr) { if (xhr.status === 200) { var index = layer.open({ type: 1 , title: '添加拉流代理' , closeBtn: false , shade: 0 , area: ['590px', '600px'] , id: 'addAddStreamProxy' //设定一个id,防止重复弹出 , btnAlign: 'c' , closeBtn: 1 , moveType: 1 //拖拽模式,0或者1 , content: data , shadeClose: false //点击遮罩区域是否关闭页面 , zIndex: 1000 }); layuiWindow['addAddStreamProxy'] = index; } else { showGrowl('请求失败,错误码:' + xhr.status + "," + xhr.statusText, 'danger', 4000) } }, function () { showGrowl('GET请求异常。', 'danger', 3000) } ); } function editStreamProxy(id) { get('/ZLServer/EditStreamProxy?streamProxyId=' + id, function (data, status, xhr) { if (xhr.status === 200) { var index = layer.open({ type: 1 , title: '添加拉流代理' , closeBtn: false , shade: 0 , area: ['590px', '600px'] , id: 'editStreamProxy' + id //设定一个id,防止重复弹出 , btnAlign: 'c' , closeBtn: 1 , moveType: 1 //拖拽模式,0或者1 , content: data , shadeClose: false //点击遮罩区域是否关闭页面 , zIndex: 99999 }); layuiWindow['editStreamProxy' + id] = index; } else { showGrowl('请求失败,错误码:' + xhr.status + "," + xhr.statusText, 'danger', 4000) } }, function () { showGrowl('GET请求异常。', 'danger', 3000) } ); } function rePullStreamProxy(id) { //重新拉流 // alert('重新拉流:' + id); } function play(id, name) { layer.open({ type: 2 , title: name , closeBtn: false , shade: 0 , area: ['590px', '600px'] , id: 'play' + id //设定一个id,防止重复弹出 , btnAlign: 'c' , closeBtn: 1 , moveType: 1 //拖拽模式,0或者1 , content: ['/ZLServer/Play?id=' + id, 'yes'] , shadeClose: false //点击遮罩区域是否关闭页面 , zIndex: 999999 }); return;//下面的代码停用 get('/ZLServer/Play?id=' + id, function (data, status, xhr) { if (xhr.status === 200) { var index = layer.open({ type: 1 , title: name , closeBtn: false , shade: 0 , area: ['590px', '600px'] , id: 'play' + id //设定一个id,防止重复弹出 , btnAlign: 'c' , closeBtn: 1 , moveType: 1 //拖拽模式,0或者1 , content: data , shadeClose: false //点击遮罩区域是否关闭页面 , zIndex: 1000 }); layuiWindow['play' + id] = index; } else { showGrowl('请求失败,错误码:' + xhr.status + "," + xhr.statusText, 'danger', 4000) } }, function () { showGrowl('GET请求异常。', 'danger', 3000) } ); } //启用停用 function changeStreamPullState(sender, id) { alert('启用,停用'); } //录制Mp4 function changeEnableMp4(sender, id) { // alert('changeEnableMp4'); } //转HLS function changeEnableHLS(sender, id) { // alert('changeEnableHLS'); } function deleteStreamProxy(id) { var index = layer.confirm('确定要删除吗?', { title: '警告', btn: ['确定', '取消'] } , function () { showLoader('删除中....', 60); $.post("/ZLServer/DeleteStreamProxy", { ids: [id] }, function (result) { layer.close(index); closeLoader(); if (result.Flag) { reload(); layer.close(index); showGrowl('删除成功!', 'success', 3000); } else { showGrowl(result.Msg, 'danger', 4000); } }, "json"); }, function () { closeLoader(); layer.close(index); }); } </script> <script type="text/html" id="tfHLSTemp"> {{#  if(d.EnableHLS==true){ }} <font color="#abe879">是</font> {{#  } else if(d.EnableHLS==false) { }} <font color="red">否</font> {{#  } }} </script> <script type="text/html" id="tfMP4Temp"> {{#  if(d.EnableHLS==true){ }} <font color="#abe879">是</font> {{#  } else if(d.EnableHLS==false) { }} <font color="red">否</font> {{#  } }} </script> <script type="text/html" id="statusTemp"> {{ d.ShowStatus }} </script> <script type="text/html" id="bar"> {{#  if(d.ShowStatus.indexOf('正常')>0){ }} <button class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit" onclick="play('{{d.Id}}','{{d.StreamName}}')">播放</button> {{#  } else { }} {{#  } }} <button class="layui-btn layui-btn-xs" lay-event="update" onclick="editStreamProxy('{{d.Id}}')">编辑</button> </script>
the_stack
@{ Layout = "~/_ContentLayout.cshtml"; } @section headerBody { <h1>Testing Packages</h1> <p class="lead">Boxstarter can detect which packages have changed and test their installations on one or more deployment targets. Boxstarter can automate publishing successful packages to their feed.</p> } <p> The Boxstarter TestRunner module can test <a href="https://chocolatey.org">Chocolatey</a> package installs on one or more deployment targets and evaluate whether the installation was successful. The TestRunner module can also be used to automate the publishing of Chocolatey packages to a <a href="https://nuget.org">NuGet</a> feed. That may be the public Chocolatey community feed or a private feed. </p> <p>The TestRunner module can be downloaded and installed via Chocolatey by running:</p> <pre>cinst Boxstarter.TestRunner</pre> <h3>Configuring the Local Boxstarter Repository</h3> <p> Boxstarter needs to know where your repository of Chocolatey packages is located. The Boxstarter repository is a single directory on disk that contains one subdirectory per package. By default, Boxstarter maintains this directory in a directory called <code>BuildPackages</code> inside the same root directory where the Boxstarter modules reside. See <a href="CreatingPackages.cshtml">Creating Packages</a> for detailed information on using Boxstarter commands to simplify package creation. All Boxstarter commands that create and build packages act within this directory. The repository location can be found using the <code>$boxstarter</code> settings variable in <code>$Boxstarter.LocalRepo</code>. </p> <img class="img-responsive" src="Images/repoDir.png" /> <p>This location can be changed using the <code>Set-BoxstarterConfig</code> command.</p> <pre>Set-BoxStarterConfig -LocalRepo "c:\dev\Chocolatey-Packages"</pre> <p> By changing the location of the boxstarter repository with <code>Set-BoxstarterConfig</code> all future interactions with the Boxstarter repository will act on this location. To temporarily change the repository location just for the current PowerShell session, one can change the value of <code>$Boxstarter.LocalRepo</code> directly. </p> <pre>$Boxstarter.LocalRepo = "c:\dev\Chocolatey-Packages"</pre> <h3>Configuring Boxstarter Testing Options</h3> <p> Boxstarter tests Chocolatey packages by deploying and installing the package to one or more deployment targets. The deployment options include settings that control what computers to use to test the packages, the credentials to use, VM checkpoints to restore as well as NuGet feed and API key for publishing successful packages. </p> <p> To read the current settings for these options, use <code>Get-BoxstarterDeploymentOptions</code>. To set these options use <code>Set-BoxstarterDeploymentOptions</code>. </p> <pre> $cred=Get-Credential Admin Set-BoxstarterDeployOptions -DeploymentTargetCredentials $cred ` -DeploymentTargetNames "testVM1","testVM2" ` -DeploymentVMProvider Azure -DeploymentCloudServiceName ServiceName ` -RestoreCheckpoint clean ` -DefaultNugetFeed https://www.myget.org/F/mywackyfeed/api/v2 ` -DefaultFeedAPIKey 5cbc38d9-1a94-430d-8361-685a9080a6b8 </pre> <p> This configures package deployments for Azure VMs testVM1 and testVM2 hosted in the ServiceName cloud service using the Admin credential. Prior to testing a package install, the VM will be restored to the clean checkpoint. If packages are published using <code>Publish-BoxstarterPackage</code> and are not associated with a NuGet feed, they will publish to the mywackyfeed on <a href="https://myget.org">myget.org</a> using API Key 5cbc38d9-1a94-430d-8361-685a9080a6b8. </p> <p> Currently the available Boxstarter VM providers are Azure and HyperV. Any VM regardless of hypervisor implementation can be used by passing in the names of the computers as the deployment targets. However, use of Boxstarter VM providers are necessary in order to take advantage of checkpoints. </p> <p> The default deployment options deploy locally using the credentials of the current user and publish to the public Chocolatey community feed. </p> <p> Individual packages in a Boxstarter repository can be published to different feeds. The NuGet feed and API Key configured using <code>Set-BoxstarterDeploymentOptions</code> are default settings used if a package has not been individually assigned to its own feed. </p> <p> To assign a package to an individual feed, use <code>Set-BoxstarterPackageNugetFeed</code>. </p> <pre> Set-BoxstarterPackageNugetFeed -PackageName MyPackage -NugetFeed https://www.myget.org/F/myotherfeed/api/v2 </pre> <p> When using multiple feeds, if one needs to use the <code>Publish-BoxstarterPackage</code> command to publish the package to its feed, an API key for each feed must be set. This can be accomplished by using the <code>Set-BoxstarterFeedAPIKey</code>. </p> <pre> Set-BoxstarterFeedAPIKey -NugetFeed https://www.myget.org/F/myotherfeed/api/v2 -APIKey 5cbc38d9-1a94-430d-8361-685a9080a6b8 </pre> <h3>Testing Chocolatey Packages</h3> <p> <code>Test-BoxstarterPackage</code> can be called with an array of packages. </p> <pre> Test-BoxstarterPackage -PackageName "MyPackage1","MyPackage2" </pre> <p> Boxstarter will build their .nupkg files and attempt to install them on the deployment targets specified with <code>Set-BoxstarterDeploymentOptions</code>. Boxstarter will use the credentials provided in the deployment options. You can provide several targets to <code>Set-BoxstarterDeploymentOptions</code>. One may wish to supply different machines running different versions of windows. If a package install runs to completion with no exceptions or returned error codes, Boxstarter considers the install a PASSED test. If <code>Test-BoxstarterPackage</code> is called with no packages specified, Boxstarter will iterate over each package in its local repository. It will build the nupkg and compare its version to the version on the package published feed. If the version in the repo is greater than the published version, Boxstarter will initiate a test on the deployment targets otherwise the package test will be skipped. </p> <img class="img-responsive" src="Images/CI.png" /> <h3>Publishing Successful Packages</h3> <p> <code>Test-BoxstarterPackage</code> will return a set of test results. One can then use <code>Select-BoxstarterResultsToPublish</code> to consume these results and return the package IDs of the packages who had all deployment targets pass the package install. These IDs can then be passed to <code>Publish-BoxstarterPackage</code> to publish those packages to their associated feeds. </p> <pre> Test-BoxstarterPackage | Select-BoxstarterResultsToPublish | Publish-BoxstarterPackage </pre> <h3>Conserving Cloud Resources</h3> <p> If the Azure Boxstarter module is used as a VM provider and any of the Azure VMs are not running when the tests begin, Boxstarter will shut down each VM that was not initially running once the testing is completed. </p> <h3>Including Testing and Publishing in Continuous Integration</h3> <p> The Boxstarter TestRunner can be plugged into modern Build systems and respond to source control commits. The Boxstarter local repo can be setup under a source control system like GIT, Mercurial, TFS, SVN etc. Build servers like TeamCity, TFS, Jenkins and others can be configured to listen for changes to the Boxstarter repo. For instance, if the repository is under git source control and pushed to a remote server monitored by a build server, the build server can execute the Boxstarter TestRunner commands to test the packages that have been changed and publish them to their feeds if the tests pass. </p> <p> The TestRunner module includes an Install-BoxstarterScripts command that embeds a MSBuild file, a bootstrapper and a PowerShell script into a repository that can run the tests and publish successful packages. </p> <pre> PS C:\dev> git clone https://github.com/mwrock/Chocolatey-Packages.git Cloning into 'Chocolatey-Packages'... remote: Reusing existing pack: 2963, done. Receiving objects: 100% (2963/2963), 3.93 MiB | Resolving deltas: 100% (961/961), done. Checking connectivity... done. Checking out files: 100% (2491/2491), done. PS C:\dev> Install-BoxstarterScripts -RepoRootPath .\Chocolatey-Packages Boxstarter: Copying Boxstarter TestRunner scripts to .\Chocolatey-Packages\BoxstarterScripts PS C:\dev> dir .\Chocolatey-Packages\BoxstarterScripts Directory: C:\dev\Chocolatey-Packages\BoxstarterScripts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 3/30/2014 11:02 PM 32 .gitignore -a--- 3/30/2014 10:53 PM 3471 bootstrap.ps1 -a--- 3/30/2014 10:53 PM 887 boxstarter.proj -a--- 3/30/2014 10:53 PM 1305 BoxstarterBuild.ps1 </pre> <p> There are two primary usage patterns for running tests from a build server: </p> <h4>Dedicated Build Server</h4> <p> Here, tests are run in a build environment on a server that is under your direct ownership and full control. The key differentiator here is that you can set your deployment options on this machine and be confident that they will remain on every build from build to build. </p> <h4>Hosted or Shared Build Server</h4> <p> This is often a build server that you do not own or control outside of your individual builds. If you set your deployment options on the server, they may likely be gone on your next build. The Visual Studio Online build services would land in this category. </p> <h3>Configuring a Dedicated Build Server</h3> <p> If you administer your own build server, there is some one time setup that you need to perform to integrate Boxstarter TestRunner tests and automatic package publishing. This must be performed on the build machine that will run the builds (a remote PowerShell session is acceptable). In many build systems, this may be a different machine from the central server, in TFS it would be the build "controller" or in TeamCity the build "agent." Also, these steps must be performed using the credentials of the SAME USER ACCOUNT that your build server runs under. </p> <ol> <li> Install the Boxstarter TestRunner module on the build machine. You can use Chocolatey and run <code>cinst Boxstarter.TestRunner</code> or launch https://boxstarter.org/package/nr/boxstarter.testrunner from IE. </li> <li> <p> Although many of the deployment options are stored in a file inside the repository and will be available when your build server gets the latest repository code, the "secret" options are not kept in source control to prevent this information from being publicly disclosed. These secrets include the deployment target credentials and feed API keys. So you can use Set-BoxstarterDeployOptions and Set-BoxstarterFeedAPIKey to set these secrets. The Credential passwords are encrypted and can only be unencrypted on the same build server by the same user account setting the options. You may also add these settings as msbuild parameters in step 4 described below. </p> <pre> $cred=Get-Credential Admin Set-BoxstarterDeployOptions -DeploymentTargetCredentials $cred ` -DefaultFeedAPIKey 5cbc38d9-1a94-430d-8361-685a9080a6b8 </pre> </li> <li> If you will be performing the package test installations on Azure VMs, you will need to configure your Azure subscription. Run <pre>Get-AzurePublishSettingsFile</pre> to download your subscription file from Azure and then <pre>Import-AzurePublishSettingsFile -PublishSettingsFile "C:\saved\subscription\file.publishsettings"</pre> You may also add the Azure management key as a MSBuild parameter described next. See <a href="VMIntegration.cshtml#azure">these instructions</a> for setting up an Azure subscription for more details. </li> <li> <p> Configure the build configuration of your build server to call the Boxstarter.proj MSBuild file as a step in your build. This file is located in the BoxstarterScripts directory of your repo which Boxstarter creates when you run Install-BoxstarterScripts. This script will invoke a bootstrapper which will install everything needed for the TestRunner to run including the TestRunner itself if not present. On dedicated build servers, where the TestRunner is preinstalled, the bootstrapper will be skipped. </p> <p> The script can take the following parameters: </p> <ul> <li> <code>PublishSuccesfulPackages</code> - Set this to true if you would like successful packages published. </li> <li> <code>DeploymentTargetUserName</code> - Username to use when initiating connections to the deployment targets. </li> <li> <code>DeploymentTargetPassword</code> - Password to use when initiating connections to the deployment targets. </li> <li> <code>FeedAPIKey</code> - API key to use when publishing packages. AzureSubscriptionName - Name of the azure subscription to use when using Azure VMs as deployment targets. </li> <li> <code>AzureSubscriptionId</code> - The Azure subscription ID Guid to use when using Azure VMs as deployment targets. </li> <li> <code>AzureSubscriptionCertificate</code> - The Azure subscription certificate to use when using Azure VMs as deployment targets. This is the Base64 encoded content of the certificate and can be found in the ManagementCertificate attribute of your Azure publish settings file. </li> </ul> <img class="img-responsive" src="Images/tfs.png"/> <p> NOTE: All of these MSBuild script parameters are optional for dedicated builds as long as the values were provided in steps 2 and 3 above which may be preferable over having plain text parameter values fed to your build. </p> </li> </ol> <h3>Configuring a Hosted or Shared Build Server</h3> <p> If your build server environment is shared and may be built from scratch on every build then you cannot preinstall the TestRunner and configure necessary settings up front. Instead the runner must be installed during the build process and the settings passed via MSBuild parameters. When you run <code>Install-BoxstarterScripts</code> on your Chocolatey repository, a bootstrapper is added to your repo that can take care of installing the Test Runner and its dependencies. Additionally, you can pass the following MSBuild parameters to the BoxstarterBuild.proj script: </p> <ul> <li> <code>PublishSuccesfulPackages</code> - Set this to true if you would like successful packages published. </li> <li> <code>DeploymentTargetUserName</code> - Username to use when initiating connections to the deployment targets. </li> <li> <code>DeploymentTargetPassword</code> - Password to use when initiating connections to the deployment targets. </li> <li> <code>FeedAPIKey</code> - API key to use when publishing packages. AzureSubscriptionName - Name of the azure subscription to use when using Azure VMs as deployment targets. </li> <li> <code>AzureSubscriptionId</code> - The Azure subscription ID Guid to use when using Azure VMs as deployment targets. </li> <li> <code>AzureSubscriptionCertificate</code> - The Azure subscription certificate to use when using Azure VMs as deployment targets. This is the Base64 encoded content of the certificate and can be found in the ManagementCertificate attribute of your Azure publish settings file. </li> </ul>
the_stack
@model WebApp.Models.Employee <script type="text/javascript"> //初始化 Employee datagrid var $employeesdg = $('#employees_datagrid'); $(() => { $employeesdg.datagrid({ rownumbers: true, iconCls: 'fa fa-list', idField: 'Id', sortName: 'Id', sortOrder: 'asc', remoteFilter: true, singleSelect: true, method: 'get', onClickCell: employees_onClickCell, pagination: true, striped: true, columns: [[ /*{field:'Id',width:80 ,sortable:true,resizable:true }*/ { field:'Name', title:'<span class="required">@Html.DisplayNameFor(model => model.Name)</span>', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Name)',required:true ,validType:'length[0,20]' } }, sortable:true, resizable:true }, { field:'Title', title:'@Html.DisplayNameFor(model => model.Title)', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Title)',required:false ,validType:'length[0,30]' } }, sortable:true, resizable:true }, { field:'Sex', title:'<span class="required">@Html.DisplayNameFor(model => model.Sex)</span>', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Sex)',required:true ,validType:'length[0,10]' } }, sortable:true, resizable:true }, { field:'Age', title:'<span class="required">@Html.DisplayNameFor(model => model.Age)</span>', width:100, align:'right', editor:{ type:'numberbox', options:{prompt:'@Html.DisplayNameFor(model => model.Age)', required:true ,precision:0 } }, sortable:true, resizable:true, formatter:numberformatter }, { field:'Brithday', title:'<span class="required">@Html.DisplayNameFor(model => model.Brithday)</span>', width:120, align:'right', editor:{ type:'datebox', options:{prompt:'@Html.DisplayNameFor(model => model.Brithday)',required:true} }, sortable:true, resizable:true, formatter:dateformatter } , { field:'IsDeleted', title:'<span class="required">@Html.DisplayNameFor(model => model.IsDeleted)</span>', width:100, align:'right', editor:{ type:'numberbox', options:{prompt:'@Html.DisplayNameFor(model => model.IsDeleted)', required:true ,precision:0 } }, sortable:true, resizable:true, formatter:numberformatter }, { field:'CompanyId', title:'<span class="required">@Html.DisplayNameFor(model => model.CompanyId)</span>', width:160, sortable:true, resizable:true, formatter:function(value,row) { return row.CompanyName; }, editor:{ type:'combobox', options:{ prompt:'@Html.DisplayNameFor(model => model.CompanyId)' , mode: 'remote', valueField:'Id', textField:'Name', method:'get', url:'/Companies/GetCompaniesAsync', required:true } } }, ]] }); //初始化 datagrid filter $employeesdg.datagrid("enableFilter",[ { field: "Id", type: "numberbox", op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: "Age", type: "numberbox", op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: "IsDeleted", type: "numberbox", op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: "Brithday", type: "dateRange", options: { onChange: function (value) { $employeesdg.datagrid("addFilterRule", { field: "Brithday", op: "between", value: value }); $employeesdg.datagrid("doFilter"); } } }, { field: "CompanyId", type:"combobox", options:{ valueField:"Id", textField:"Name", method:"get", url:"/Companies/GetCompaniesAsync", onChange: function (value) { if (value == "") { $employeesdg.datagrid("removeFilterRule", "CompanyId"); } else { $employeesdg.datagrid("addFilterRule", { field: "CompanyId", op: "equal", value: value }); } $employeesdg.datagrid("doFilter"); } } }, ]); }); //datagrid CRUD method var employees_editIndex = undefined; //取消 function employees_reject() { $employeesdg.datagrid("rejectChanges"); employees_editIndex = undefined; } //重新加载数据 function employees_reload() { if (endEditing()) { $employeesdg.datagrid("reload"); } } //关闭编辑状态 function employees_endEditing() { if (employees_editIndex === undefined) { return true; } if ($employeesdg.datagrid("validateRow", employees_editIndex)) { var ed = $employeesdg.datagrid("getEditor", { index: employees_editIndex, field: "CompanyId" }); var companyname = $(ed.target).combobox("getText"); var companyid = $(ed.target).combobox("getValue"); $employeesdg.datagrid("getRows")[employees_editIndex]["CompanyName"] = companyname; $employeesdg.datagrid("getRows")[employees_editIndex]["CompanyId"] = companyid; $employeesdg.datagrid("endEdit", employees_editIndex); employees_editIndex = undefined; return true; } else { return false; } } //单击列开启编辑功能 function employees_onClickCell(index, field) { var _operates = ["_operate1", "_operate2", "_operate3", "ck"]; if ($.inArray(field, _operates) >= 0) { return false; } if (employees_editIndex !== index) { if (employees_endEditing()) { $employeesdg.datagrid("selectRow", index) .datagrid("beginEdit", index); employees_editIndex = index; var ed = $employeesdg.datagrid("getEditor", { index: index, field: field }); if (ed) { ($(ed.target).data("textbox") ? $(ed.target).textbox("textbox") : $(ed.target)).focus(); } } else { $employeesdg.datagrid("selectRow", employees_editIndex); } } } //新增记录 function employees_append() { if (employees_endEditing()) { //对必填字段进行默认值初始化 $employeesdg.datagrid("insertRow", { index: 0, row: { CompanyId:companyid } }); employees_editIndex = 0; $employeesdg.datagrid("selectRow", employees_editIndex) .datagrid("beginEdit", employees_editIndex); } } //删除编辑的行 function employees_removeit() { if (employees_editIndex !== undefined) { $employeesdg.datagrid("cancelEdit", employees_editIndex) .datagrid("deleteRow", employees_editIndex); employees_editIndex = undefined; } } //删除选中的行 function employees_deletechecked() { var rows = $employeesdg.datagrid("getChecked"); if (rows.length > 0) { var id = rows.map(item => { return item.Id; }); $.messager.confirm("确认", "你确定要删除这些记录?",result => { if (result) { $.post("/Employees/DeleteCheckedAsync", { id: id }) .done(response => { if (response.success) { $employeesdg.datagrid("reload"); } else { $.messager.alert("错误", response.err,"error"); } }); } }); } else { $.messager.alert("提示", "请先选择要删除的记录!"); } } //提交保存后台数据库 function employees_accept() { if (employees_endEditing()) { if ($employeesdg.datagrid("getChanges").length) { var inserted = $employeesdg.datagrid("getChanges", "inserted"); var deleted = $employeesdg.datagrid("getChanges", "deleted"); var updated = $employeesdg.datagrid("getChanges", "updated"); var item = new Object(); if (inserted.length) { item.inserted = inserted; } if (deleted.length) { item.deleted = deleted; } if (updated.length) { item.updated = updated; } //console.log(JSON.stringify(item)); $.post("/Employees/SaveDataAsync", item) .done(response => { //console.log(response); if (response.success) { $.messager.alert("提示", "提交成功!"); $employeesdg.datagrid("acceptChanges"); $employeesdg.datagrid("reload"); } else { $.messager.alert("错误", response.err ,"error"); } }) .fail((jqXHR, textStatus, errorThrown) => { //console.log(errorThrown); $.messager.alert("错误", "提交错误了!" + errorThrown,"error"); }); } } } </script>
the_stack
@page @model WebVella.Erp.Web.Pages.JsAdminImageFinderModel @using System.Collections.Generic; <!DOCTYPE html> <html lang="en" ng-app="wvApp" ng-controller="ApplicationController as appData"> <head> <meta charset="utf-8" /> <meta name="referrer" content="origin" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title ng-bind="appData.pageTitle"></title> <!-- library > css --> @foreach (var cssFile in Model.LibraryCssFileList) { <link href="@cssFile" rel="stylesheet" /> } <!-- module > css --> @foreach (var cssFile in Model.ModuleCssFileList) { <link href="@cssFile" rel="stylesheet" /> } </head> <body ng-cloak style="background-color:#f2f2f2;"> <toast></toast> <div ng-controller="ImageFinderViewController as pluginCtrl" ng-cloak> <div class="panel panel-white" style="margin:0;padding:10px"> <div class="panel-body" style="overflow:hidden"> <div class="row"> <div class="col-xs-4"> <a class="btn btn-default" ng-click="pluginCtrl.uploadFile()"> <i class="fa fa-upload"></i> @if ((string)ViewBag.FinderType == "image") { <span>Upload image</span> } else { <span>Upload file</span> } </a> </div> <div class="col-xs-4"> <form class="form" name="submitForm" ng-submit="pluginCtrl.searchFiles()" style="margin:0;"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-search"></i></span> <input class="form-control" ng-model="pluginCtrl.search" /> </div> <button type="submit" class="ng-hide">Find</button> </form> </div> <div class="col-xs-4 text-right"> <div class="btn-group"> <a class="btn btn-default" ng-click="pluginCtrl.changeSort(1)" ng-class="{'active': pluginCtrl.sort == 1}" title="sort by upload date"><i class="fa fa-fw fa-clock"></i></a> <a class="btn btn-default" ng-click="pluginCtrl.changeSort(2)" ng-class="{'active': pluginCtrl.sort == 2}" title="sort alphabetically"><i class="fa fa-fw fa-sort-alpha-asc"></i></a> </div> </div> </div> </div> </div> <div class="panel panel-default loading-bar ng-hide" ng-show="pluginCtrl.loading" style="margin-top:15px;"> <div class="panel-body"> <i class="fa fa-loading fa-spin"></i> </div> </div> <div ng-show="pluginCtrl.errorMessage" class="alert alert-danger ng-hide" style="margin-top:15px;"> {{pluginCtrl.errorMessag}} </div> <div class="file-manager ng-hide" ng-show="!pluginCtrl.loading && !pluginCtrl.errorMessage"> <ul class="list-inline"> <li style="" ng-repeat="file in pluginCtrl.files track by file.id"> <a ng-click="pluginCtrl.selectFile(file)"> <!--"--> <div class="block image" ng-if="file.type == 'image'"> <div class="centered"> <img ng-src="/fs{{file.path}}?width=150&height=150&action=resize&mode=boxpad" /> </div> <div class="filename"> <div ng-bind="file.name"></div> </div> </div> <div class="block image" ng-if="file.type == 'document'"> <div class="centered"> <i class="fa fa-file-text fa-4x"></i> </div> <div class="filename"> <div ng-bind="file.name"></div> </div> </div> <div class="block image" ng-if="file.type == 'audio'"> <div class="centered"> <i class="fa fa-volume-up fa-4x"></i> </div> <div class="filename"> <div ng-bind="file.name"></div> </div> </div> <div class="block image" ng-if="file.type == 'video'"> <div class="centered"> <i class="fa fa-video-camera fa-4x"></i> </div> <div class="filename"> <div ng-bind="file.name"></div> </div> </div> </a> </li> </ul> <div class="alert alert-info ng-hide" ng-show="pluginCtrl.files.length == 0">No files are found matching your search criteria</div> </div> </div> <script type="text/ng-template" id="uploadFileModal.html"> <div class="modal-header"> @if ((string)ViewBag.FinderType == "image") { <span>Upload image</span>} else { <span>Upload file</span>} </div> <div class="modal-body"> <div class="form-group" ng-class="{'has-error':popupCtrl.validation.errors.path.isInvalid}"> <label class="control-label">File</label> <div> <a ng-if="!popupCtrl.file.path && popupCtrl.progress == 0" href="javascript:void(0)" class="btn btn-default btn-outline" ngf-select="upload(popupCtrl.uploadedFile)" ngf-max-size="20MB" ngf-multiple='false' ng-model="popupCtrl.uploadedFile" translate="{{::'BROWSE'}}"></a> <div class="progress" ng-if="!popupCtrl.file.path && popupCtrl.progress > 0 && popupCtrl.progress <= 100"> <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" ng-style="{'width': popupCtrl.progress +'%'}"> <span ng-if="popupCtrl.progress < 100">{{popupCtrl.progress || '0'}}%</span> <span ng-if="popupCtrl.progress == 100" translate="{{::'FILE_UPLOAD_ALMOST_DONE'}}"></span> </div> </div> <div class="editable-wrapper input-group file-upload" ng-if='popupCtrl.file.path'> <span class="form-control" ng-bind-html="popupCtrl.renderFieldValue()"></span> <a class="input-group-addon delete" href="javascript:void(0)" confirmed-click="popupCtrl.deleteFile()" ng-confirm-click="{{'DELETE_CONFIRMATION_ALERT_MESSAGE' | translate}}" title="{{'DELETE_FILE' | translate}}"><i class="fa fa-fw fa-trash-o"></i></a> </div> </div> <div class="go-red" ng-if="popupCtrl.validation.errors.path.isInvalid">{{popupCtrl.validation.errors.path.message}}</div> </div> </div> <div class="modal-footer" style="text-align:center;"> <button class="btn btn-primary" type="button" ng-click="popupCtrl.save()" ng-class="{'disabled':popupCtrl.loading}"><i class="fa fa-fw" ng-class="{'fa-upload':!popupCtrl.loading,'fa-spin fa-spinner':popupCtrl.loading}"></i> Upload file</button> <button class="btn btn-default" type="button" ng-click="popupCtrl.cancel()">cancel</button> </div> </script> <!-- library > js --> @foreach (var jsFile in Model.LibraryJsFileList) { <script src="@jsFile"></script> } @* Core Application module definition *@ <script> @*In order to dynamically add plug-in modules, the appCore definition should be with server side aspect*@ (function () { 'use strict'; angular .module('wvApp', [ // Angular modules 'ngAnimate', 'ngCookies', 'ngSanitize', //'ngTouch' // 3rd Party Modules 'ui.router', 'ngMessages','ngToast', 'xeditable', 'ui.bootstrap', 'as.sortable', 'checklist-model','ui.tree', 'ngCkeditor', 'ngFileUpload', 'ngStorage', 'ui.bootstrap.datetimepicker','RecursionHelper','angular-loading-bar', 'doubleScrollBars','angular-bind-html-compile','oc.lazyLoad','ui.ace','pascalprecht.translate', //Plug-in app injects @foreach(var appInjection in Model.AppDependencyInjections) { @:"@appInjection", } ]) .config(config) .run(run); // Configuration /////////////////////////////////// config.$inject = ['$httpProvider', '$urlRouterProvider', '$logProvider', 'wvAppConstants', 'ngToastProvider']; function config($httpProvider,$urlRouterProvider, $logProvider, wvAppConstants, ngToastProvider) { //$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; $urlRouterProvider.otherwise('/login'); $httpProvider.useApplyAsync("true"); $logProvider.debugEnabled(wvAppConstants.debugEnabled); moment.locale('@Model.Lang'); ngToastProvider.configure({ animation: 'fade', horizontalPosition: 'center', timeout: 2000, maxNumber: 1 }); }; // Run ////////////////////////////////////// run.$inject = ['editableOptions', 'editableThemes']; function run(editableOptions, editableThemes) { editableOptions.theme = 'bs3'; editableThemes.bs3.buttonsClass = 'btn-sm'; }; })(); </script> <script src="/jsadmin/application.controller.js?v=@Model.CacheBreaker"></script> <script src="/jsadmin/application.constants.js?v=@Model.CacheBreaker"></script> <!-- Server generated global variables --> <script> var htmlCacheBreaker = @Model.CacheBreaker; var GlobalLanguage = '@Model.Lang'; var GlobalCompanyName = '@Model.CompanyName'; var GlobalCompanyLogo = '@Model.CompanyLogo'; </script> <script src="@Model.LanguageFile"></script> <!-- module > js --> @foreach (var jsFile in Model.ModuleJsFileList) { <script src="@jsFile"></script> } <script> var FilesServerLoad = @Html.WvJsonRaw(Model.JsonFiles); var CurrentType = "@Html.WvJsonRaw(Model.CurrentType)"; var CurrentSort = @Html.Raw(Model.CurrentSort); var CurrentPage = @Html.Raw(Model.CurrentPage); var CurrentPageSize = @Html.Raw(Model.CurrentPageSize); </script> <script> angular.module('webvellaAdmin').controller('ImageFinderViewController', ImageFinderViewController); ImageFinderViewController.$inject = ['$scope', '$uibModal', '$http', '$location']; function ImageFinderViewController($scope, $uibModal, $http, $location) { $scope.pluginCtrl = {}; $scope.pluginCtrl.files = fastCopy(FilesServerLoad); $scope.pluginCtrl.type = CurrentType; $scope.pluginCtrl.sort = CurrentSort; $scope.pluginCtrl.page = CurrentPage; $scope.pluginCtrl.pageSize = CurrentPageSize; $scope.pluginCtrl.search = null; $scope.pluginCtrl.loading = false; $scope.pluginCtrl.errorMessage = null; $scope.pluginCtrl.searchFiles = function () { $scope.pluginCtrl.page = 1; loadFiles(); } $scope.pluginCtrl.changeSort = function (sort) { $scope.pluginCtrl.sort = sort; loadFiles(); } function loadFiles() { $scope.pluginCtrl.loading = true; $scope.pluginCtrl.errorMessage = null; var paramsObject = {}; if ($scope.pluginCtrl.page) { paramsObject.page = $scope.pluginCtrl.page }; if ($scope.pluginCtrl.pageSize) { paramsObject.pageSize = $scope.pluginCtrl.pageSize }; if ($scope.pluginCtrl.type) { paramsObject.type = $scope.pluginCtrl.type }; if ($scope.pluginCtrl.sort) { paramsObject.sort = $scope.pluginCtrl.sort }; if ($scope.pluginCtrl.search) { paramsObject.search = $scope.pluginCtrl.search }; $http({ url: '/api/v3/en_US/user_file', method: "GET", params: paramsObject }) .then(function (res) { //success $scope.pluginCtrl.files = res.data.object; $scope.pluginCtrl.loading = false; }, function (res) { //error $scope.pluginCtrl.errorMessage = res.data.message; $scope.pluginCtrl.loading = false; }); } function getUrlParam(paramName) { var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i'); var match = window.location.search.match(reParam); return (match && match.length > 1) ? match[1] : null; } $scope.pluginCtrl.selectFile = function (selectedFile) { var funcNum = getUrlParam('CKEditorFuncNum'); window.opener.CKEDITOR.tools.callFunction(funcNum, "/fs" + selectedFile.path); window.close(); } $scope.pluginCtrl.uploadFile = function () { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'uploadFileModal.html', windowClass: "centered ", controller: function ($scope, $sce, $filter, $state, $uibModalInstance, webvellaCoreService, parentCtrl, ngToast, $timeout) { $scope.popupCtrl = {}; $scope.popupCtrl.validation = webvellaCoreService.initValidationObject(); $scope.popupCtrl.loading = false; $scope.popupCtrl.file = {}; $scope.popupCtrl.file.alt = null; $scope.popupCtrl.file.caption = null; $scope.popupCtrl.file.path = null; $scope.popupCtrl.uploadedFile = null; $scope.popupCtrl.progress = 0; $scope.popupCtrl.uploadedFileName = ""; $scope.upload = function (file) { if (file != null) { $scope.popupCtrl.validation = webvellaCoreService.initValidationObject(); $scope.popupCtrl.uploadSuccessCallback = function (response) { $scope.popupCtrl.file.path = response.object.url; $scope.popupCtrl.uploadedFileName = response.object.filename; } $scope.popupCtrl.uploadErrorCallback = function (response) { ngToast.create({ className: 'error', content: '<span class="go-red">Error:</span> ' + response.message, timeout: 7000 }); } $scope.popupCtrl.uploadProgressCallback = function (response) { $timeout(function () { $scope.popupCtrl.progress = parseInt(100.0 * response.loaded / response.total); }, 0); } webvellaCoreService.uploadFileToTemp(file, $scope.popupCtrl.uploadProgressCallback, $scope.popupCtrl.uploadSuccessCallback, $scope.popupCtrl.uploadErrorCallback); } }; $scope.popupCtrl.deleteFile = function () { var filePath = $scope.popupCtrl.file.path; function deleteSuccessCallback(response) { $timeout(function () { $scope.popupCtrl.file.path = null; $scope.popupCtrl.uploadedFile = null; $scope.popupCtrl.progress = 0; $scope.popupCtrl.uploadedFileName = ""; }, 0); return true; } function deleteFailedCallback(response) { ngToast.create({ className: 'error', content: '<span class="go-red">Error:</span> ' + response.message, timeout: 7000 }); return "validation error"; } webvellaCoreService.deleteFileFromFS(filePath, deleteSuccessCallback, deleteFailedCallback); } $scope.popupCtrl.renderFieldValue = function () { return webvellaCoreService.renderFieldValue($scope.popupCtrl.file.path, { fieldType: 7 }); } $scope.popupCtrl.save = function () { function uploadSuccessCallback(response) { $timeout(function () { $scope.popupCtrl.file.path = null; $scope.popupCtrl.uploadedFile = null; $scope.popupCtrl.progress = 0; $scope.popupCtrl.uploadedFileName = ""; parentCtrl.files.unshift(response.object); $scope.popupCtrl.loading = false; $uibModalInstance.close('dismiss'); }, 0); return true; } function uploadFailedCallback(response) { ngToast.create({ className: 'error', content: '<span class="go-red">Error:</span> ' + response.message, timeout: 7000 }); $scope.popupCtrl.loading = false; return "validation error"; } $scope.popupCtrl.validation = webvellaCoreService.initValidationObject(); if (isStringNullOrEmptyOrWhiteSpace($scope.popupCtrl.file.path)) { $scope.popupCtrl.validation = webvellaCoreService.setValidationError($scope.popupCtrl.validation, "Validation error", "path", "* required"); } if (!$scope.popupCtrl.validation.isInvalid) { $scope.popupCtrl.loading = true; var submitObject = {}; submitObject.path = $scope.popupCtrl.file.path; submitObject.caption = $scope.popupCtrl.file.caption; submitObject.alt = $scope.popupCtrl.file.alt; webvellaCoreService.uploadUserFile(submitObject, uploadSuccessCallback, uploadFailedCallback); } }; $scope.popupCtrl.cancel = function () { $uibModalInstance.close('dismiss'); }; }, resolve: { parentCtrl: function () { return $scope.pluginCtrl; } } }); } } </script> </body> </html>
the_stack
@{ ViewBag.Title = "jquery.fileDownload.js Demo"; Layout = "~/Views/Shared/_Layout.cshtml"; Func<int, int> fibCalc = n => { int a = 0; int b = 1; for (int i = 0; i < n; i++) { int temp = a; a = b; b = temp + b; } return a; }; } <script type="text/javascript"> $(function () { // // Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog // uses the optional "options" argument // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // <a class="fileDownload..."/> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(document).on("click", "a.fileDownloadSimpleRichExperience", function () { $.fileDownload($(this).prop('href'), { preparingMessageHtml: "We are preparing your report, please wait...", failMessageHtml: "There was a problem generating your report, please try again." }); return false; //this is critical to stop the click event which will trigger a normal file download! }); // //With jquery.fileDownload.js //Promise use allows for a very customized experience easily // $(document).on("click", "a.fileDownloadPromise", function () { $.fileDownload($(this).prop('href')) .done(function () { alert('File download a success!'); }) .fail(function () { alert('File download failed!'); }); return false; //this is critical to stop the click event which will trigger a normal file download }); // // POST Request: Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog // uses data "options" argument to create a POST request from a form to initiate a file download // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // <form class="fileDownloadForm"> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js instead of the defualt form submit behavior // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(document).on("submit", "form.fileDownloadForm", function (e) { $.fileDownload($(this).prop('action'), { preparingMessageHtml: "We are preparing your report, please wait...", failMessageHtml: "There was a problem generating your report, please try again.", httpMethod: "POST", data: $(this).serialize() }); e.preventDefault(); //otherwise a normal form submit would occur }); //Custom rich user experience - jquery.fileDownload.js & jQuery UI Dialog //uses the optional "options" argument // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // <a class="fileDownload..."/> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(function () { $(document).on("click", "a.fileDownloadCustomRichExperience", function () { var $preparingFileModal = $("#preparing-file-modal"); $preparingFileModal.dialog({ modal: true }); $.fileDownload($(this).prop('href'), { successCallback: function (url) { $preparingFileModal.dialog('close'); }, failCallback: function (responseHtml, url) { $preparingFileModal.dialog('close'); $("#error-modal").dialog({ modal: true }); } }); return false; //this is critical to stop the click event which will trigger a normal file download! }); }); }) </script> @*"fancy" razor helper, good stuff: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx*@ @helper ReportTable(string linkCssClass) { <table> <tr> <th>File Name</th> <th>Description</th> </tr> @for (int i = 0; i < 5; i++) { <tr> <td> @Html.ActionLink(string.Format("Report{0}.pdf", i), "DownloadReport", new { id = i }, new { @class = linkCssClass }) </td> <td> @if (i % 2 == 0) { <text>This file download will succeed</text> } else { <text>This file download will fail</text> } </td> </tr> } </table> <br/> } jQuery File Download is a cross server platform compatible jQuery plugin that allows for an Ajax-like file download experience that isn’t normally possible using the web. For more information and documentation please visit: <a href="http://johnculviner.com/category/jQuery-File-Download.aspx">http://johnculviner.com/category/jQuery-File-Download.aspx</a> <br/><br/> <b>Note: In order for this plugin to work you must also write a cookie in an http header "Set-Cookie: fileDownload=true; path=/" as mentioned in the original blog post: <a href="http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx">http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx</a></b> <br /><br /> The source can be found on GitHub: <a href="http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js">http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js</a> <h2>Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog</h2> With jquery.fileDownload.js, uses the optional "options" argument to create a simple richer user experience using jQuery UI Dialog <br/><br/> @ReportTable("fileDownloadSimpleRichExperience") <a class="toggle-source" >Toggle Source</a> <div class="source"> <pre class="brush: js;"> // // Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog // uses the optional "options" argument // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // &lt;a class="fileDownload..."/&gt; that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(document).on("click", "a.fileDownloadSimpleRichExperience", function () { $.fileDownload($(this).prop('href'), { preparingMessageHtml: "We are preparing your report, please wait...", failMessageHtml: "There was a problem generating your report, please try again." }); return false; //this is critical to stop the click event which will trigger a normal file download! }); </pre> </div> <h2>Custom use with Promises - jquery.fileDownload.js</h2> With jquery.fileDownload.js, uses promises to allow for a very customized experience easily<br/><br/> @ReportTable("fileDownloadPromise") <a class="toggle-source">Toggle Source</a> <div class="source"> <pre class="brush: js;"> // //With jquery.fileDownload.js //custom use with promises // $(document).on("click", "a.fileDownloadPromise", function () { $.fileDownload($(this).prop('href')) .done(function () { alert('File download a success!'); }) .fail(function () { alert('File download failed!'); }); return false; //this is critical to stop the click event which will trigger a normal file download }); </pre> </div> <h2>POST Request: Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog</h2> With jquery.fileDownload.js, uses data "options" argument to create a POST request to initiate a file download<br/><br/> @using (Html.BeginForm("DownloadReportPost", "FileDownload", FormMethod.Post, new { @class = "fileDownloadForm" })) { <text> <input type="text" name="foo" value="42"/> Setting foo to an odd number will cause the file download to fail <br/> <input type="text" name="bar" value="Some text"/><br/> Yes<input type="radio" name="yesno" value="Yes" checked="checked"/> No <input type="radio" name="yesno" value="No"/> <br/> </text> <select name="fib"> @for (int i = 0; i < 15; i++) { int j = fibCalc(i); <option value="@j">@j</option> } </select> <br/> <input type="submit"/> } <br/> <a class="toggle-source" >Toggle Source</a> <div class="source"> <pre class="brush: js;"> // // POST Request: Simple rich user experience - jquery.fileDownload.js & jQuery UI Dialog // uses data "options" argument to create a POST request from a form to initiate a file download // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // &lt;form class="fileDownloadForm" ... that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js instead of the defualt form submit behavior // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(document).on("submit", "form.fileDownloadForm", function (e) { $.fileDownload($(this).prop('action'), { preparingMessageHtml: "We are preparing your report, please wait...", failMessageHtml: "There was a problem generating your report, please try again.", httpMethod: "POST", data: $(this).serialize() }); e.preventDefault(); //otherwise a normal form submit would occur }); </pre> </div> <h2>Custom rich user experience - jquery.fileDownload.js & jQuery UI Dialog</h2> With jquery.fileDownload.js, uses the optional "options" argument to create a custom richer user experience using jQuery UI Dialog <br/><br/> @ReportTable("fileDownloadCustomRichExperience") <a class="toggle-source">Toggle Source</a> <div class="source"> <pre class="brush: js;"> //Custom rich user experience - jquery.fileDownload.js & jQuery UI Dialog //uses the optional "options" argument // // the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any // &lt;a class="fileDownload..."/&gt; that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js // if you are using "on": // you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it // works for possible dynamic manipulation in the entire DOM // $(function () { $(document).on("click", "a.fileDownloadCustomRichExperience", function () { var $preparingFileModal = $("#preparing-file-modal"); $preparingFileModal.dialog({ modal: true }); $.fileDownload($(this).prop('href'), { successCallback: function (url) { $preparingFileModal.dialog('close'); }, failCallback: function (responseHtml, url) { $preparingFileModal.dialog('close'); $("#error-modal").dialog({ modal: true }); } }); return false; //this is critical to stop the click event which will trigger a normal file download! }); }); </pre> <pre class="brush: xml;"> <div id="preparing-file-modal" title="Preparing report..." style="display: none;"> We are preparing your report, please wait... <div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div> </div> <div id="error-modal" title="Error" style="display: none;"> There was a problem generating your report, please try again. </div> </pre> </div> <h2>Stock Browser Behavior</h2> Normal file download experience without using jquery.fileDownload.js. Ick!<br/><br/> @ReportTable("") <div id="preparing-file-modal" title="Preparing report..." style="display: none;"> We are preparing your report, please wait... <div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div> </div> <div id="error-modal" title="Error" style="display: none;"> There was a problem generating your report, please try again. </div> <script> if (document.referrer.indexOf("stackoverflow") !== -1) { $.extend($.gritter.options, { position: 'bottom-right' }); setTimeout(function() { $.gritter.add({ title: 'Welcome StackOverflow user!', text: 'It looks like you came here from <a href="'+document.referrer+'" style="color:#ccc">this question</a>. If you think this helped you please upvote the answer to help others as well.', sticky: true }); }, 15000); } </script>
the_stack
@{ Layout = "_LayoutH"; @model Sys_user } @*<div id="app" v-cloak> <form class="form-horizontal" onsubmit="return false"> <div class="box-body"> <div class="form-group"> <label class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input v-model="UserName" type="text" class="input-text" v-focus> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">昵称</label> <div class="col-sm-10"> <input type="text" class="input-text" v-model="UserNickname"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">昵称</label> <div class="col-sm-10"> <input type="text" class="input-text" v-model="UserNickname"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">备注</label> <div class="col-sm-10"> <textarea v-model="Remark" class="form-control" rows="3" placeholder="备注...100个字符以内"></textarea> <p class="textarea-numberbar"><em class="textarea-length">{{count}}</em>/100</p> </div> </div> </div> <div class="box-footer"> <div class="pull-right box-tools"> <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit"> </div> </div> </form> </div>*@ <div id="app" v-cloak> <form class="form-horizontal" onsubmit="return false"> <div class="box-body"> @*<div class="form-group"> <label for="starttime" class="col-sm-2 control-label">实际开始时间</label> <div class="col-md-4"> <input class="form-control" type="text" id="starttime" /> </div> <label for="endtime" class="col-sm-2 control-label">实际结束时间</label> <div class="col-md-4"> <input class="form-control" type="text" id="endtime" /> </div> </div>*@ <table class="table table-bordered"> <tr> <td> <div class="form-group"> <label class="col-sm-2 control-label"><span class="c-red">*</span>用户名:</label> <div class="col-sm-10"> <input v-model="UserName" type="text" class="form-control" v-focus> </div> </div> </td> <td> <div class="form-group"> <label class="control-label col-sm-2"><span class="c-red">*</span>昵称:</label> <div class="col-sm-10"> <input type="text" class="form-control" v-model="UserNickname"> </div> </div> </td> </tr> <tr> <td> <div class="form-group" v-if="UserId<=0"> <label class="control-label col-sm-2"><span class="c-red">*</span>初始密码:</label> <div class="col-sm-10"> <input type="password" class="form-control" autocomplete="off" value="" placeholder="密码" v-model="Pwd1"> </div> </div> </td> <td> <div class="form-group" v-if="UserId<=0"> <label class="control-label col-sm-2"><span class="c-red">*</span>确认密码:</label> <div class=" col-sm-10"> <input type="password" class="form-control" autocomplete="off" placeholder="确认新密码" v-model="Pwd2"> </div> </div> </td> </tr> <tr> <td colspan="2"> <div class="form-group"> <label class="control-label col-sm-2"><span class="c-red">*</span>性别:</label> <div class="col-sm-10 "> <label class="radio-inline"> <input type="radio" value="1" v-model="sex">男 </label> <label class="radio-inline"> <input type="radio" value="0" v-model="sex">女 </label> </div> </div> </td> </tr> <tr> <td> <div class="form-group"> <label class="control-label col-sm-2"><span class="c-red">*</span>手机:</label> <div class="col-sm-10"> <input type="text" class="form-control" v-model="Tel"> </div> </div> </td> <td> <div class="form-group"> <label class="col-sm-2 control-label"><span class="c-red">*</span>邮箱:</label> <div class="col-sm-10"> <input type="text" class="form-control" v-model="Email"> </div> </div> </td> </tr> <tr> <td> @await Component.InvokeAsync("Dept") @*<div class="form-group"> <label class="col-sm-2 control-label">部门:</label> <div class="col-sm-10"> <select class="form-control" v-model="DeptId"> <option value="">请选择</option> @{ if (ViewBag.Dept != null || ViewBag.Dept.Count > 0) { foreach (var item in ViewBag.Dept) { <option value="@item.DeptId">@item.DeptName</option> } } } </select> </div> </div>*@ </td> <td> <div class="form-group"> <label class="col-sm-2 control-label">角色:</label> <div class="col-sm-10"> <select class="form-control" v-model="RoleId"> <option value="">请选择</option> @{ if (ViewBag.Role != null || ViewBag.Role.Count > 0) { foreach (var item in ViewBag.Role) { <option value="@item.RoleId">@item.RoleName</option> } } } </select> </div> </div> </td> </tr> <tr> <td colspan="2"> <div class="form-group"> <label class="col-sm-2 control-label">备注:</label> <div class="col-sm-10"> <textarea v-model="Remark" class="form-control" rows="3" placeholder="备注...100个字符以内"></textarea> <p class="textarea-numberbar"><em class="textarea-length">{{count}}</em>/100</p> </div> </div> </td> </tr> </table> <div class="box-footer"> <div class="pull-right box-tools"> <input v-on:click="addL" class="btn btn-primary radius" type="submit" v-model="submit"> </div> </div> </div> </form> </div> @section scripts{ <script> $(function () { parent.$("span[class='layui-layer-setwin']")[0].childNodes[1].onclick = function () { //var iframeH = parent.$("div[type='iframe']")[0].clientHeight; //parent.$("div[class='layui-layer-content']")[0].childNodes[0].style.height = 1000; var index = parent.layer.getFrameIndex(window.name); //console.info(parent.$("#layui-layer" + index)[0].style["height"]); parent.$("#layui-layer-iframe" + index)[0].style.height = parent.document.body.clientHeight + "px"; }; }); var app = new Vue({ el: "#app", data: { submit: "添加", sex: "@Model.Sex", Remark: "@Model.Remark", Tel: "@Model.Tel", Email: "@Model.Email", UserName: "@Model.UserName", UserNickname: "@Model.UserNickname", Pwd1: "", Pwd2: "", RoleId: "@Model.RoleId", DeptId: "@Model.DeptId", UserId: "@Model.UserId" }, computed: { count: function () { return this.strLength(this.Remark, false); } }, methods: { addL: function () { var _self = this; if (_self.UserName.length <= 0) { layer.msg("姓名不能为空", { icon: 2 }); return false; } if (_self.UserNickname.length <= 0) { layer.msg("昵称不能为空", { icon: 2 }); return false; } if (_self.UserId.length<=0) { if (_self.Pwd1.length <= 0) { layer.msg("密码不能为空", { icon: 2 }); return false; } if (_self.Pwd2 !== _self.Pwd1) { layer.msg("两次输入密码不一致", { icon: 2 }); return false; } } if (_self.DeptId.length <= 0) { layer.msg("请选择部门", { icon: 2 }); return false; } if (_self.RoleId.length <= 0) { layer.msg("请选择角色", { icon: 2 }); return false; } var index = layer.load(1, { shade: [0.1, '#fff'] //0.1透明度的白色背景 }); var data = { id: _self.UserId, UserName: _self.UserName, UserNickname: _self.UserNickname, Pwd: _self.Pwd2, Remark: _self.Remark, Tel: _self.Tel, RoleId: _self.RoleId, sex: _self.sex, Email: _self.Email, DeptId: _self.DeptId }; yui.$axiospostform('/User/AddOrUpdate', data) .then(function (response) { if (response.data.Item1 === 101) { layer.tips(response.data.Item2, '.layui-layer-setwin', { tips: [1, '#3595CC'], time: 3000 }); layer.close(index); return false; } if (response.data.Item1) { layer.msg(response.data.Item2, { icon: 1, time: 1000 }); setTimeout(function () { yui.layer_close3(); }, 500); } else { layer.msg(response.data.Item2, { icon: 5 }); } layer.close(index); }) .catch(function (error) { layer.close(index); }); } } }); </script> }
the_stack
@model WebApp.Models.MenuItem @{ ViewBag.Title = "系统菜单"; } <!-- MAIN CONTENT --> <div id="content"> <!-- quick navigation bar --> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"> <i class="fa fa-table fa-fw "></i> 系统管理 <span> > 系统菜单 </span> </h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> </div> </div> <!-- end quick navigation bar --> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-table"></i> </span> <h2>系统菜单</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body no-padding"> <div class="widget-body-toolbar"> <div class="row"> <div class="col-sm-8 "> <div class="btn-group"> <a href="javascript:createWithController()" class="btn btn-sm btn-primary"> <i class="fa fa-sitemap"></i> 生成菜单 </a> </div> <div class="btn-group"> <a href="javascript:append()" class="btn btn-sm btn-default"> <i class="fa fa-plus"></i> 新增 </a> </div> <div class="btn-group"> <a href="javascript:removeit()" class="btn btn-sm btn-default"> <i class="fa fa-trash-o"></i> 删除 </a> </div> <div class="btn-group"> <a href="javascript:accept()" class="btn btn-sm btn-default"> <i class="fa fa-floppy-o"></i> 保存 </a> </div> <div class="btn-group"> <a href="javascript:reload()" class="btn btn-sm btn-default"> <i class="fa fa-refresh"></i> 刷新 </a> </div> <div class="btn-group"> <a href="javascript:reject()" class="btn btn-sm btn-default"> <i class="fa fa-window-close-o"></i> 取消 </a> </div> <div class="btn-group"> <button type="button" onclick="importexcel()" class="btn btn-default"><i class="fa fa-upload"></i> 导入数据 </button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a href="javascript:importexcel()"><i class="fa fa-upload"></i> 上传Excel </a></li> <li role="separator" class="divider"></li> <li><a href="javascript:downloadtemplate()"><i class="fa fa-download"></i> 下载模板 </a></li> </ul> </div> <div class="btn-group"> <a href="javascript:exportexcel()" class="btn btn-sm btn-default"> <i class="fa fa-file-excel-o"></i> 导出Excel </a> </div> <div class="btn-group"> <a href="javascript:print()" class="btn btn-sm btn-default"> <i class="fa fa-print"></i> 打印 </a> </div> <div class="btn-group"> <a href="javascript:dohelp()" class="btn btn-sm btn-default"> <i class="fa fa-question-circle-o"></i> 帮助 </a> </div> </div> <div class="col-sm-4 text-align-right"> <div class="btn-group"> <a href="javascript:window.history.back()" class="btn btn-sm btn-success"> <i class="fa fa-chevron-left"></i> 返回 </a> </div> </div> </div> </div> <div class="alert alert-warning no-margin fade in"> <button class="close" data-dismiss="alert"> × </button> <i class="fa-fw fa fa-info"></i> 注意事项: </div> <!--begin datagrid-content --> <div class="table-responsive"> <table id="menuitems_datagrid"></table> </div> <!--end datagrid-content --> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> </section> <!-- end widget grid --> <!-- file upload partial view --> @Html.Partial("_ImportWindow", new ViewDataDictionary { { "EntityName", "MenuItem" } }) <!-- end file upload partial view --> <!-- detail popup window --> @Html.Partial("_PopupDetailFormView", new WebApp.Models.MenuItem()) <!-- end detail popup window --> </div> <!-- END MAIN CONTENT --> @section Scripts { <script type="text/javascript"> var entityname = "MenuItem"; var menuitem = {}; //生成菜单 function createWithController() { $.messager.progress({ title: '正在处理请耐心等待!' }); $.post('/MenuItems/CreateWithController').done(res => { $.messager.progress('close'); if (res.success) { $.messager.alert("提示", "成功创建菜单!", 'info', function () { $dg.datagrid('reload'); }); } else { $.messager.alert("错误", "生成异常!" + res.err, 'error', function () { }); } }); } //下载Excel导入模板 function downloadtemplate() { //默认模板路径存放位置 var url = "/ExcelTemplate/MenuItem.xlsx"; $.fileDownload(url) .done(() => { console.log('file download a success!'); }) .fail(() => { $.messager.alert("错误","没有找到模板文件! {" + url + "}","error"); }); } //打印 function print() { $dg.datagrid('print', 'DataGrid'); } //打开Excel上传导入 function importexcel() { $("#importwindow").window("open"); } //执行导出下载Excel function exportexcel() { var filterRules = JSON.stringify($dg.datagrid("options").filterRules); //console.log(filterRules); $.messager.progress({ title: "正在执行导出!" }); var formData = new FormData(); formData.append("filterRules", filterRules); formData.append("sort", "Id"); formData.append("order", "asc"); $.postDownload("/MenuItems/ExportExcel", formData).then(res => { $.messager.progress("close"); }).catch(err => { //console.log(err); $.messager.progress("close"); $.messager.alert("错误", err.statusText, "error"); }); } //显示帮助信息 function dohelp() { } var editIndex = undefined; //选中记录 function onSelect(index, row) { menuitem = row; } //重新加载数据 function reload() { if (endEditing()) { $dg.datagrid("reload"); $dg.datagrid("uncheckAll"); $dg.datagrid("unselectAll"); } } //关闭编辑状态 function endEditing() { if (editIndex === undefined) { return true; } if ($dg.datagrid("validateRow", editIndex)) { var ed = $dg.datagrid("getEditor", { index: editIndex, field: "ParentId" }); var parenttitle = $(ed.target).combobox("getText"); var parentid = $(ed.target).combobox("getValue"); $dg.datagrid("getRows")[editIndex]["ParentTitle"] = parenttitle; $dg.datagrid("getRows")[editIndex]["ParentId"] = parentid; $dg.datagrid("endEdit", editIndex); editIndex = undefined; return true; } else { return false; } } //单击列开启编辑功能 function onClickCell(index, field) { menuitem = $dg.datagrid('getRows')[index]; var _operates = ["_operate1", "_operate2", "_operate3", "ck"]; if ($.inArray(field, _operates) >= 0) { return; } if (editIndex !== index) { if (endEditing()) { $dg.datagrid("selectRow", index) .datagrid("beginEdit", index); editIndex = index; var ed = $dg.datagrid("getEditor", { index: index, field: field }); if (ed) { ($(ed.target).data("textbox") ? $(ed.target).textbox("textbox") : $(ed.target)).focus(); } } else { $dg.datagrid("selectRow", editIndex); } } } //新增记录 function append() { if (endEditing()) { //对必填字段进行默认值初始化 $dg.datagrid("insertRow", { index: 0, row: { } }); editIndex = 0; $dg.datagrid("selectRow", editIndex) .datagrid("beginEdit", editIndex); } } //删除编辑的行 function removeit() { if($dg.datagrid("getChecked").length > 0 ){ deletechecked(); } else { if (editIndex !== undefined) { $dg.datagrid("cancelEdit", editIndex) .datagrid("deleteRow", editIndex); editIndex = undefined; } } } //删除选中的行 function deletechecked() { var rows = $dg.datagrid("getChecked"); if (rows.length > 0) { var id = rows.map(item => { return item.Id; }); $.messager.confirm("确认", "你确定要删除这些记录?", result => { if (result) { $.post("/MenuItems/DeleteCheckedAsync", { id: id }) .done(response => { if (response.success) { reload(); } else { $.messager.alert("错误", response.err,"error"); } }) .fail((jqXHR, textStatus, errorThrown)=> { //console.log(errorThrown); $.messager.alert("错误", "提交错误了!" + errorThrown,"error"); }); } }); } else { $.messager.alert("提示", "请先选择要删除的记录!"); } } //提交保存后台数据库 function accept() { if (endEditing()) { if ($dg.datagrid("getChanges").length) { var inserted = $dg.datagrid("getChanges", "inserted"); var deleted = $dg.datagrid("getChanges", "deleted"); var updated = $dg.datagrid("getChanges", "updated"); var item = new Object(); if (inserted.length) { item.inserted = inserted; } if (deleted.length) { item.deleted = deleted; } if (updated.length) { item.updated = updated; } //console.log(JSON.stringify(item)); $.post("/MenuItems/SaveDataAsync", item) .done(response => { //console.log(response); if (response.success) { $.messager.alert("提示", "提交成功!"); $dg.datagrid("acceptChanges"); $dg.datagrid("reload"); } else { $.messager.alert("错误", response.err ,"error"); } }) .fail(function (jqXHR, textStatus, errorThrown) { //console.log(errorThrown); $.messager.alert("错误", "提交错误了!" + errorThrown,"error"); }); } } } function reject() { $dg.datagrid("rejectChanges"); editIndex = undefined; } function getChanges() { var rows = $dg.datagrid("getChanges"); console.log(rows.length + " rows are changed!"); } //弹出明细信息 function showDetailsWindow(id) { //console.log(index, row); $.get("/MenuItems/PopupEditAsync/" + id) .done(data => { //console.log(data); loadData(id,data); }) .fail(function (jqXHR, textStatus, errorThrown) { $.messager.alert("错误", "获取数据异常!" + errorThrown,"error"); }); } //初始化定义datagrid var $dg = $("#menuitems_datagrid"); $(() => { //定义datagrid结构 $dg.datagrid({ rownumbers:true, checkOnSelect:true, selectOnCheck:true, idField:'Id', sortName:'Id', sortOrder:'desc', remoteFilter: true, singleSelect: true, onSelect: onSelect, url: '/MenuItems/GetDataAsync', method: 'get', onClickCell: onClickCell, pagination: true, striped:true, columns: [[ /*开启CheckBox选择功能*/ /*{ field: 'ck', checkbox: true },*/ { field: '_operate1', title:'操作', width: 120, sortable: false, resizable: true, formatter: function showdetailsformatter(value, row, index) { return '<a onclick="showDetailsWindow(' + row.Id + ')" class="text-info" href="javascript:void(0)"><i class="fa fa-list"></i> 查看明细</a>'; } }, /*{field:'Id',width:80 ,sortable:true,resizable:true }*/ { field:'Title', title:'<span class="required">@Html.DisplayNameFor(model => model.Title)</span>', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Title)',required:true ,validType:'length[0,50]' } }, sortable:true, resizable:true }, { field:'Description', title:'@Html.DisplayNameFor(model => model.Description)', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Description)',required:false ,validType:'length[0,100]' } }, sortable:true, resizable:true }, { field:'Code', title:'<span class="required">@Html.DisplayNameFor(model => model.Code)</span>', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Code)',required:true ,validType:'length[0,20]' } }, sortable:true, resizable:true }, { field:'Url', title:'<span class="required">@Html.DisplayNameFor(model => model.Url)</span>', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Url)',required:true ,validType:'length[0,100]' } }, sortable:true, resizable:true }, { field:'Controller', title:'@Html.DisplayNameFor(model => model.Controller)', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Controller)',required:false ,validType:'length[0,100]' } }, sortable:true, resizable:true }, { field:'Action', title:'@Html.DisplayNameFor(model => model.Action)', width:260, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.Action)',required:false ,validType:'length[0,100]' } }, sortable:true, resizable:true }, { field:'IconCls', title:'@Html.DisplayNameFor(model => model.IconCls)', width:140, editor:{ type:'textbox', options:{ prompt:'@Html.DisplayNameFor(model => model.IconCls)',required:false } }, sortable:true, resizable:true }, { field:'IsEnabled', title:'<span class="required">@Html.DisplayNameFor(model => model.IsEnabled)</span>', width:120, align:'center', editor:{ type:'booleaneditor', options:{ prompt:'@Html.DisplayNameFor(model => model.IsEnabled)', required:true } }, formatter:booleanformatter, sortable:true, resizable:true }, { field:'ParentId', title:'@Html.DisplayNameFor(model => model.ParentId)', width:160, sortable:true, resizable:true, formatter:function(value,row) { return row.ParentTitle; }, editor:{ type:'combobox', options:{ prompt:'@Html.DisplayNameFor(model => model.ParentId)' , mode: 'remote', valueField:'Id', textField:'Title', method:'get', url:'/MenuItems/GetMenuItemsAsync', required:false } } }, ]] }); $dg.datagrid("enableFilter",[ { field: "Id", type: "numberbox", op:['equal','notequal','less','lessorequal','greater','greaterorequal'] }, { field: "IsEnabled", type: "booleanfilter" }, { field: "ParentId", type:"combobox", options:{ valueField:"Id", textField:"Title", method:"get", url:"/MenuItems/GetMenuItemsAsync", onChange: function (value) { if (value === "" || value === null) { $dg.datagrid("removeFilterRule", "ParentId"); } else { $dg.datagrid("addFilterRule", { field: "ParentId", op: "equal", value: value }); } $dg.datagrid("doFilter"); } } }, ]); }); </script> @Html.Partial("_menuitemdatagridjsview", new WebApp.Models.MenuItem()) <script type="text/javascript"> //load data by foreign key var menuitemid = 0; function loadData(id, data) { $("#detailswindow").window("open"); menuitemid = id; $('#menuitem_form').form('load', data); var url = '/MenuItems/GetDataByParentIdAsync?parentid=' + id; $menuitemsdg.datagrid('load', url); $menuitemsdg.datagrid('resize'); } var $editform = $('#menuitem_form'); // save item function saveitem() { if ($editform.form('enableValidation').form('validate')) { var menuitem = $editform.serializeJSON(); var token = $('input[name="__RequestVerificationToken"]', $editform).val(); $.ajax({ type: "POST", url: "/MenuItems/EditAsync", data: { __RequestVerificationToken: token, menuitem: menuitem }, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=utf-8' }) .done(response => { if (response.success) { $dg.datagrid('reload'); $.messager.alert("提示", "保存成功!"); $('#detailswindow').window("close"); } else { $.messager.alert("错误", "保存失败!" + response.err, "error"); } }) .fail((jqXHR, textStatus, errorThrown) => { $.messager.alert("错误", "保存失败!" + errorThrown, "error"); }); } } // close window function closewindow() { $('#detailswindow').window('close'); } // print form function printitem() { console.log('print.....'); } $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var target = $(e.target).attr("href"); if (target === "#tab-menuitems") $menuitemsdg.datagrid("resize"); }); </script> <script src="~/Scripts/jquery.filerupload.min.js"></script> }
the_stack
@using System.Dynamic; @model dynamic @{ var count = 0; var guid = Guid.NewGuid(); var displayAttribute = ViewData.ModelMetadata.GetPropertyAttribute<System.ComponentModel.DataAnnotations.DisplayAttribute>(); var settings = this.PuckEditorSettings<puck.core.Models.EditorSettings.Attributes.ListEditorSettingsAttribute>(attributeOnly: true) ?? new puck.core.Models.EditorSettings.Attributes.ListEditorSettingsAttribute(); var validationDummyGuid = Guid.NewGuid(); } <div data-guid="@guid.ToString()" class="listeditor listeditor_@ViewData.TemplateInfo.HtmlFieldPrefix listeditor_@ViewData.TemplateInfo.HtmlFieldPrefix.Replace("[","_").Replace("]","_").Replace(".","_")"> <div style="display:none;" class="propName" data-propName="@ViewData.TemplateInfo.HtmlFieldPrefix"></div> <div style="display:none;" class="nameQuery" data-query="@Html.Raw(displayAttribute?.ShortName??"")"></div> @if (ViewData.ModelMetadata.IsRequired) { <span class="field-validation-valid validationDummySummary" data-valmsg-for="v@(validationDummyGuid.ToString().Replace("-",""))" data-valmsg-replace="true"></span> } <div class="addContainer"> <button type="button" class="btn-light btn"><i class="fas fa-plus" /></button> </div> <ul class="selected_content"> @if (Model != null) { foreach (var m in Model) { if (m == null) { continue; } string templateName = null; if (!string.IsNullOrEmpty(settings.EditorTemplate)) { templateName = settings.EditorTemplate; } else if (m.GetType().Equals(typeof(string))) { templateName = "String"; } else if (m.GetType().Equals(typeof(Single)) || m.GetType().Equals(typeof(Single?))) { templateName = "Single"; } else if (m.GetType().Equals(typeof(Char))) { templateName = "Char"; } else if (m.GetType().Equals(typeof(Decimal)) || m.GetType().Equals(typeof(Decimal?))) { templateName = "Decimal"; } else if (m.GetType().Equals(typeof(Double)) || m.GetType().Equals(typeof(Double?))) { templateName = "Double"; } else if (m.GetType().Equals(typeof(Int16)) || m.GetType().Equals(typeof(Int16?))) { templateName = "Int16"; } else if (m.GetType().Equals(typeof(Int32)) || m.GetType().Equals(typeof(Int32?))) { templateName = "Int32"; } else if (m.GetType().Equals(typeof(Int64)) || m.GetType().Equals(typeof(Int64?))) { templateName = "Int64"; } else if (m.GetType().Equals(typeof(bool)) || m.GetType().Equals(typeof(bool?))) { templateName = "Boolean"; } else if (m.GetType().Equals(typeof(DateTime)) || m.GetType().Equals(typeof(DateTime?))) { templateName = "DateTime"; } <li class="itemContainer"> <div class="titleContainer"><i class="sortHandle fas fa-arrows-alt" /><i class="expand fas fa-chevron-down" /> <span>item @(count + 1)</span> <i class="fas fa-minus-circle remove" /></div> <div class="editorContainer"> @Html.EditorFor(x => m, templateName, $"[{count}]", null) </div> </li> count++; } } </ul> @if (ViewData.ModelMetadata.IsRequired) { <input class="validationDummy" type="hidden" data-val="true" value="@(count>0?"1":"")" data-val-required="The @ViewData.TemplateInfo.HtmlFieldPrefix field is required." id="@validationDummyGuid.ToString()" name="v@(validationDummyGuid.ToString().Replace("-",""))" /> } </div> <script type="text/javascript"> onAfterDom(function () { var guid = "@guid.ToString()"; var modelType = "@Html.Raw(ViewBag.Level0Type.Name)"; var nameQuery = "@Html.Raw(displayAttribute?.ShortName??"")"; var propname = "@Html.Raw(ViewData.TemplateInfo.HtmlFieldPrefix)"; var shouldBindListEditor = '@ViewBag.ShouldBindListEditor' == 'True'; var maxTitleLength = 50; //debugger; var jqueryEscape = function (str) { return str.replace("[","\\\\[").replace("]","\\\\]"); } var escapePropname = function (str) { return str.replace(/\[/g, "_").replace(/\]/g,"_").replace(/\./g,"_"); } var container = null; container = $("[data-guid='"+guid+"']"); var validationDummy = container.find(".validationDummy:last"); validationDummy.attr("data-val-required", "The " + container.parents(".fieldwrapper:first").find(".editor-label label").html() + " field is required."); container.find(".validationDummySummary").attr("data-valmsg-for",validationDummy.attr("name")); //if (shouldBindListEditor) // cright.find(".listeditor_" + escapePropname(propname)); //else // container = cinterfaces.find("div[data-type='" + modelType + "'] .listeditor_" + escapePropname(propname)) var selected_container = container.find(".selected_content:first"); var getPropName = function () { return container.find("div:hidden.propName:first").attr("data-propName"); } var whenTemplateReady = function (f) { var el = cinterfaces.find("div[data-type='" + modelType + "']"); if (el.length == 0) setTimeout(function () { whenTemplateReady(f); }, 500); else f(el); } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } var toZeroIndex = function (str) { str = str.replace(/\[\d+\]/g, "[0]"); return str; } if (shouldBindListEditor || true) { whenTemplateReady(function (template) { afterDom(); //console.log("templateReady:" + getPropName()); container.find(".addContainer:first button").click(function () { template = cinterfaces.find("div[data-type='" + modelType + "']"); if (window.debug) debugger; var el = $(this); var validationDummy = el.parents(".listeditor:first").find(".validationDummy:last"); if (validationDummy.length > 0) { validationDummy.val("1"); validationDummyCounter++; if (((validationDummy.attr("name")||"").match(/_/g) || []).length < 2) validationDummy.attr("name", validationDummy.attr("name") + "_" + validationDummyCounter); el.parents(".listeditor:first").find(".validationDummySummary:first").attr("data-valmsg-for",validationDummy.attr("name")); } var _selected_container = el.parents(".listeditor:first").find(".selected_content:first"); var elToCopy = template.find(".listeditor_" + escapePropname(toZeroIndex(getPropName())) + " .itemContainer:first"); //console.log("el to copy", elToCopy); var index = _selected_container.find(">.itemContainer").length; var copy = elToCopy.clone(true, true); copy.find("input[type=text][value=' ']").val(""); copy.find(".validationDummy").val(""); copy.find(".listeditor .selected_content").each(function () { $(this).empty(); }); var _propName = _selected_container.parents(".listeditor:first").find("div:hidden.propName:first").attr("data-propName"); copy.find("div:hidden.propName").each(function () { //debugger; var div = $(this); var name = div.attr("data-propName") || ""; //var oldPropName = getPropName(); //var regex = new RegExp("^" + escapeRegExp(oldPropName + "[0]")); //name = name.replace(regex, _propName + "[" + index + "]"); var regex = new RegExp("^" + escapeRegExp(toZeroIndex(_propName)) + "\\[\\d+\\]"); var newName = name.replace(regex, _propName + "[" + index + "]"); div.attr("data-propName", newName).attr("data-touched", "true"); }); copy.find(":input:not(.validationDummy)").each(function () { //debugger; var input = $(this); var name = input.attr("name") || ""; if (!name) return; var newName = _propName + "["+index+"]"; var oldPropName = name.substring(0, name.lastIndexOf(".")); //name.replace(/\[0\]$/,""); var regex = new RegExp("^" + escapeRegExp(oldPropName /*+ "[0]"*/)); name = name.replace(regex, _propName + "[" + index + "]"); if (name[name.length - 1] == "]") input.attr("name", newName); else input.attr("name",name); }); copy.find(".editorContainer").show(); copy.find("i.expand").removeClass("fa-chevron-right").addClass("fa-chevron-down"); copy.find(".selected_content").each(function () { var container = $(this); bindSortable(container); }); _selected_container.append(copy); bindTitleContainerClick(_selected_container); setTitle(copy); var form = _selected_container.parents("form:first"); form.removeData("validator"); form.removeData("unobtrusiveValidation"); //trigger container update copy.find(".containerTrigger").click(); //re-initialize copy.find(".editor_container").each(function () { var editorContainer = $(this); editorContainer.trigger("puckListEditorUpdate",[editorContainer]); }); $.validator.unobtrusive.parse(form); }); }); var bindTitleContainerClick = function (elSelected_container) { elSelected_container.off("click.tc").on("click.tc", ".titleContainer .expand", function (e) { e.stopPropagation(); //debugger; //if (!$(e.currentTarget).hasClass("titleContainer")) // return; var el = $(this); if (!$(this).hasClass("expand")) return; var parent = el.parents(".itemContainer:first"); if (parent.find(".editorContainer:first").is(":visible")) { parent.find(".editorContainer:first").hide(); el/*.find("i.expand")*/.removeClass("fa-chevron-down").addClass("fa-chevron-right"); } else { el/*.find("i.expand")*/.removeClass("fa-chevron-right").addClass("fa-chevron-down"); parent.find(".editorContainer:first").show(); } }); elSelected_container.off("click.minus").on("click.minus", ".titleContainer i.remove", function (e) { if (!$(e.currentTarget).hasClass("remove")) return; var el = $(this); var _selected_container = el.parents(".selected_content:first"); var container = el.parents(".itemContainer:first"); var _index = _selected_container.find(">.itemContainer").length; if (_index == 1) { el.parents(".listeditor:first").find(".validationDummy:last").val(""); } container.remove(); setIndexesForInputs(_selected_container); }); /* if (elSelected_container.data('sortable') || elSelected_container.hasClass("ui-sortable")) elSelected_container.sortable("destroy") elSelected_container.sortable({ handle: ".sortHandle", items: ">.itemContainer", stop: function (event, ui) { sortStop(event, ui); } }); */ } bindTitleContainerClick(selected_container); var sortStop = function (event,ui) { //debugger; var el = ui.item; var _selected_container = el.parents(".selected_content:first"); setIndexesForInputs(_selected_container); //re-initialize _selected_container.find(".editor_container").each(function () { var editorContainer = $(this); editorContainer.trigger("puckListEditorUpdate",[editorContainer]); }); } var setIndexesForInputs = function (_selected_container) { var _propName = _selected_container.parents(".listeditor:first").find("div:hidden.propName:first").attr("data-propName"); _selected_container.find(">.itemContainer").each(function () { var itemContainer = $(this); var index = itemContainer.index(); itemContainer.find("div:hidden.propName").each(function () { //debugger; var div = $(this); var name = div.attr("data-propName") || ""; var regex = new RegExp("^" + escapeRegExp(_propName) + "\\[\\d+\\]"); var newName = name.replace(regex, _propName + "[" + index + "]"); div.attr("data-propName", newName).attr("data-touched","true"); }); itemContainer.find(":input").each(function () { //debugger; var input = $(this); var name = input.attr("name") || ""; if (!name) return; var regexStr = "^" + escapeRegExp(_propName) + "\\[\\d+\\]"; var regex = new RegExp("^" + escapeRegExp(_propName) + "\\[\\d+\\]"); var newName = name.replace(regex, _propName + "[" + index + "]"); input.attr("name", newName); }); }); } var bindSortable = function (_selected_container) { _selected_container.disableSelection().sortable({ handle:".sortHandle", axis: "y", /*handle: ">.itemContainer>.titleContainer .sortHandle",*/ items: ">.itemContainer", start: function (event, ui) { if (tinyMCE != undefined) { tinyMCE.triggerSave(); } }, stop: function (event, ui) { sortStop(event, ui); } }); } if (shouldBindListEditor) bindSortable(selected_container); //selected_container.disableSelection().sortable({ axis: "y", handle: ".sortHandle", items: ">.itemContainer", stop: function (event, ui) { sortStop(event, ui); } }); var setTitle = function (itemContainer) { var index = itemContainer.index(); var title = "item " + (index+1); var _nameQuery = itemContainer.parents(".listeditor:first").find("div:hidden.nameQuery").attr("data-query"); var elTitle = itemContainer.find(_nameQuery); if (elTitle.length > 0) { if (elTitle.first().is(":input")) { title = elTitle.val(); title = $("<div/>").html(title).text(); } else title = elTitle.text(); } if (title.replace(/\s/g, "") == "") title = "item " + (index + 1); else if (title.length > maxTitleLength) title = title.substring(0,maxTitleLength)+"..."; itemContainer.find(".titleContainer:first span").html(title); } //collapse selected content by default selected_container.find(".titleContainer").each(function () { var el = $(this); var parent = el.parent(); parent.find(".editorContainer").hide(); el.find("i.expand").removeClass("fa-chevron-down").addClass("fa-chevron-right"); setTitle(parent); }); //set list item title on input change selected_container.on("change.listeditor", ":input", function () { var el = $(this); var itemContainer = el.parents(".itemContainer:first"); setTitle(itemContainer); }); } }); </script> <style> .listeditor .titleContainer { cursor:pointer; } </style>
the_stack
@{ Layout = "~/Views/Shared/_FormGray.cshtml"; } <div class="wrapper wrapper-content"> <div class="col-sm-12"> <div class="row"> <div class="col-sm-12"> <blockquote class="text-warning" style="font-size:14px"> <p> 领取阿里云通用云产品最高2000元优惠券(仅限新用户)<br /> <a target="_blank" href="https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=8lbflttm">https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=8lbflttm</a> </p> <p> 腾讯云产品优惠采购<br /> <a target="_blank" href="https://curl.qcloud.com/2eG1xiw8">https://curl.qcloud.com/2eG1xiw8</a> </p> <p> UCloud全球大促<br /> <a target="_blank" href="https://www.ucloud.cn/site/active/kuaijie.html?invitation_code=C1x021080B8D32A">https://www.ucloud.cn/site/active/kuaijie.html?invitation_code=C1x021080B8D32A</a> </p> </blockquote> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>框架介绍</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"> <i class="fa fa-times"></i> </a> </div> </div> <div class="ibox-content"> <div class="row"> <div class="col-sm-12" style="font-size:14px"> <p> YiShaAdmin 借鉴了很多开源项目的优点,让你开发Web管理系统和移动端Api更简单,所以我也把她开源了(前端<code>CSS</code>样式主要参考<a href="http://demo.ruoyi.vip/" target="_blank">若依</a>,在此表示感谢 :)。<br /> 她适用于开发 <b>网站管理后台</b>、<b>CMS</b>、<b>CRM</b>、<b>ERP</b>、<b>OA</b> 这类的系统和开发<a href="/api/api-doc" target="_blank"><b>移动端Api</b></a>。<br /> 代码完全免费开源,易读易懂、界面简洁美观,给你的项目多一种选择与参考。 </p> <p>当前版本:@YiSha.Util.GlobalContext.GetVersion() &nbsp;&nbsp;<span class="label label-warning">¥免费开源</span></p> <p></p> <p> <a class="btn btn-success btn-outline" href="https://github.com/liukuo362573/YiShaAdmin" target="_blank"> <i class="fa fa-github"> </i> 访问 github </a> @*<a class="btn btn-white btn-bitbucket" href="#" target="_blank"> <i class="fa fa-home"></i> 访问主页 </a>*@ </p> </div> </div> </div> </div> </div> <div class="col-sm-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>技术选型</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i class="fa fa-times"></i></a> </div> </div> <div class="ibox-content" style="font-size:14px"> <ul> <li>1. 前端: Bootstrap 3.3.7</li> <li>2. 核心框架:.Net Core MVC</li> <li>3. 缓存层:Memory、Redis</li> <li>4. 持久层框架:Entity Framework Core</li> <li>5. 数据库支持:SqlServer,MySql,Oracle</li> <li>6. 定时任务:Quartz.Net</li> </ul> </div> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>联系信息</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i class="fa fa-times"></i></a> </div> </div> <div class="ibox-content"> @*<p> <i class="fa fa-send-o"></i> 官网:<a href="#" target="_blank"></a> </p>*@ <p> <i class="fa fa-qq"></i> QQ群:<s>满 428703155</s> <a href="https://jq.qq.com/?_wv=1027&k=MQ6OdF8v" target="_blank">851661600</a> </p> </div> </div> </div> <div class="col-sm-4"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>更新日志</h5> <div class="ibox-tools"> <a class="collapse-link"><i class="fa fa-chevron-up"></i></a> <a class="close-link"><i class="fa fa-times"></i></a> </div> </div> <div class="ibox-content no-padding"> <div class="panel-body"> <div class="panel-group" id="version"> <div class="panel panel-default"> <div class="panel-heading"> <h5 class="panel-title"> <a data-toggle="collapse" data-parent="#version" href="#v310">v3.1.0</a><code class="pull-right">2020.02.20</code> </h5> </div> <div id="v310" class="panel-collapse collapse in"> <div class="panel-body"> <ol> <li>1. 框架由.NET Core 2.2升级到.NET Core 3.1</li> <li>2. 导入文件支持xlsx格式</li> <li>3. 菜单支持打开外部链接</li> <li>4. 修复读取cookie样式bug</li> <li>5. 部门和用户的数据权限修改,只能看到自己及以下</li> <li>6. 菜单新增或编辑之后,显示对应的数据</li> <li>7. 定时任务支持暂停和更新任务周期</li> <li>8. 数据库和实体之间映射约定修改</li> <li>9. 支持移动端</li> </ol> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h5 class="panel-title"> <a data-toggle="collapse" data-parent="#version" href="#v220">v2.2.0</a><code class="pull-right">2019.09.27</code> </h5> </div> <div id="v220" class="panel-collapse collapse"> <div class="panel-body"> <ol> <li>1. 正式开源YiShaAdmin 2.2</li> <li>2. 代码自动生成的时候,根据配置,生成对应菜单</li> <li>3. 修复bootstrap tree table的expandFirst为true,tree展开的问题</li> <li>4. 修复头像上传报错</li> <li>5. 增加多个基类实体,根据业务按需继承</li> <li>6. 调整项目文件结构,使代码结构更加清晰</li> <li>7. 增加NUnit测试项目</li> <li>8. 增加常用的前端组件示例</li> <li>9. 增加用户导入示例</li> </ol> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-sm-4"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>捐赠</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="close-link"><i class="fa fa-times"></i></a> </div> </div> <div class="ibox-content"> <div class="alert alert-warning"> 请作者喝杯咖啡(点击图片放大) </div> <p id="pay-qrcode"> <a> <img src="~/image/pay.png" width="100%" alt="请使用手机支付宝或者微信扫码支付" class="img-responsive"> </a> </p> </div> </div> </div> </div> </div> </div> <script> $(function () { $(".modal").appendTo("body"), $("[data-toggle=popover]").popover(), $(".collapse-link").click(function () { var div_ibox = $(this).closest("div.ibox"), e = $(this).find("i"), i = div_ibox.find("div.ibox-content"); i.slideToggle(200), e.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down"), div_ibox.toggleClass("").toggleClass("border-bottom"), setTimeout(function () { div_ibox.resize(); }, 50); }), $(".close-link").click(function () { var div_ibox = $(this).closest("div.ibox"); div_ibox.remove() }); $('#pay-qrcode').click(function () { var html = $(this).html(); ys.openDialogContent({ content: html, width: '600px', height: '321px' }); }); }); </script>
the_stack
@model sBlog.Net.Areas.Admin.Models.AdminSettingsViewModel @{ ViewBag.Title = string.Format("Update Settings || {0}", Model.Title); } <style type="text/css"> #disqusShortName { display: none } .seperator { float: right; color: black } #disqus-akiemet { display: none } #error { display: none } #error span { font-weight: bold } #error ul { padding: 20px; list-style-type: square } </style> <script type="text/javascript"> $(function () { if ($('#DisqusEnabled').is(':checked')) { $('#disqusShortName').show(); if ($('#DisqusShortName').val().trim() != '') { $('#disqus-akiemet').show(); $('#disqusAkismet').attr('href', 'http://' + $('#DisqusShortName').val() + '.disqus.com/admin/settings/advanced/'); } } $('.setting-content').first().show(); $('#DisqusEnabled').change(function () { if ($(this).is(':checked')) { $('#disqusShortName').show(); if ($('#DisqusShortName').val().trim() != '') { $('#disqus-akiemet').show(); $('#disqusAkismet').attr('href', 'http://' + $('#DisqusShortName').val() + '.disqus.com/admin/settings/advanced/'); } } else { $('#disqusShortName').hide(); $('#disqus-akiemet').hide(); } }); $('.setting-header ').live('click', function () { var content = $(this).next().next(); $(content).toggle('fast'); }); $("form").submit(function (e) { if ($(this).valid() == false) { if ($('.input-validation-error').length > 0) { $('#error').show(); var tabId = $('.input-validation-error:eq(0)').parent().prop('id'); $('#myTab a[href="#' + tabId + '"]').tab('show'); } } }); }); </script> @Html.Partial("UpdateStatus", Model.UpdateStatus) <div> @using (Html.BeginForm()) { @Html.ValidationSummary(false, "Please correct the following errors", new { @class = "alert alert-danger", @id = "error" }) <ul id="myTab" class="nav nav-tabs"> <li class="active"><a href="#main" data-toggle="tab">Main</a></li> <li><a href="#editor" data-toggle="tab">Blog Editor</a></li> <li><a href="#email" data-toggle="tab">Email</a></li> <li><a href="#social_sharing" data-toggle="tab">Sharing & Social</a></li> <li><a href="#per_page" data-toggle="tab">Per Page</a></li> <li><a href="#errors" data-toggle="tab">Site Errors</a></li> <li><a href="#disqus" data-toggle="tab">Disqus</a></li> <li><a href="#akismet" data-toggle="tab">Akismet</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade in active" id="main"> <br/> @Html.Partial("ThemeWarning", Model) <span class="sub-title">@Html.LabelFor(model => model.BlogName)</span> <br /> @Html.TextBoxFor(model => model.BlogName, new {@class = "inputBoxBig"}) <br /><br /> <span class="sub-title">@Html.LabelFor(model => model.BlogCaption)</span> <br /> @Html.TextBoxFor(model => model.BlogCaption, new {@class = "inputBoxBig"}) <br /><br /> <span class="sub-title">@Html.LabelFor(model => model.BlogTheme)</span> <br /> @Html.DropDownListFor(model => model.BlogTheme, Model.BlogThemes, new {@class = "dropDownBox"}) </div> <div class="tab-pane fade" id="editor"> <br/> <span class="sub-title">@Html.LabelFor(model => model.EditorType)</span> <br /> @Html.DropDownListFor(model => model.EditorType, Model.EditorTypes, new {@class = "dropDownBox"}) &nbsp;<a id="markdownHelp" target="_blank" href="https://daringfireball.net/projects/markdown/basics">what is markdown?</a> </div> <div class="tab-pane fade" id="email"> <br/> <span class="sub-title">@Html.LabelFor(model => model.AdminEmailAddress)</span> <br /> @Html.TextBoxFor(model => model.AdminEmailAddress, new {@class = "inputBoxBig"})<br/> <span class="settings-info">(will be used as the from address in emails sent, and also as the user name for the smtp server if a password is specified)</span><br/> <br/> <span class="sub-title">@Html.LabelFor(model => model.BlogSmtpAddress)</span> <br /> @Html.TextBoxFor(model => model.BlogSmtpAddress, new {@class = "inputBoxBig"})<br /> <span class="settings-info">(without a valid smtp address, sending emails [site errors & forgotten password] would fail)</span> <br /><br /> <span class="sub-title">@Html.LabelFor(model => model.BlogSmtpPassword)</span> <br /> @Html.PasswordFor(model => model.BlogSmtpPassword, new {@class = "inputBoxBig"})<br /> <span class="settings-info">(some email servers might require a password, enter if any [not shown, if you have entered already])</span><br /> <span class="settings-info">(the smtp password won't be updated if you leave this field blank. so after you enter the password for the first time, you don't have to enter it every time)</span><br/> </div> <div class="tab-pane fade" id="social_sharing"> <br/> <span class="sub-title">Social sharing options</span> <br /> @Html.CheckBoxFor(model => model.BlogSocialSharing) @Html.LabelFor(model => model.BlogSocialSharing) <br /><br/> <span class="sub-title">Syntax highlighting</span> <br /> @Html.CheckBoxFor(model => model.BlogSyntaxHighlighting) @Html.LabelFor(model => model.BlogSyntaxHighlighting) </div> <div class="tab-pane fade" id="per_page"> <br/> <span class="sub-title">@Html.LabelFor(model => model.PostsPerPage)</span> <br /> @Html.TextBoxFor(model => model.PostsPerPage, new {@class = "inputBoxBig"}) <br /><br /> <span class="sub-title">@Html.LabelFor(model => model.ManageItemsPerPage)</span> <br /> @Html.TextBoxFor(model => model.ManageItemsPerPage, new {@class = "inputBoxBig"}) </div> <div class="tab-pane fade" id="errors"> <br/> @Html.CheckBoxFor(model => model.BlogErrorAction) @Html.LabelFor(model => model.BlogErrorAction) </div> <div class="tab-pane fade" id="disqus"> <br/> <span class="sub-title">Enable Disqus?</span> <br /><br /> @Html.CheckBoxFor(model => model.DisqusEnabled) @Html.LabelFor(model => model.DisqusEnabled) <span id="disqus-akiemet">(<a href="#" target="_blank" id="disqusAkismet">akismet settings</a>)</span> <br/> <span class="settings-info">(enabling disqus will disable the default commenting system. to enable akismet go to the disqus admin page)</span> <br /><br /> <div id="disqusShortName"> <span class="sub-title">@Html.LabelFor(model => model.DisqusShortName)</span> <br /> @Html.TextBoxFor(model => model.DisqusShortName, new {@class = "inputBoxBig"}) </div> </div> <div class="tab-pane fade" id="akismet"> <br/> @Html.CheckBoxFor(model => model.AkismetEnabled) @Html.LabelFor(model => model.AkismetEnabled) <br/> <span class="settings-info">(not required if you are planning to use disqus)</span> <br/><br/> <div class="panel panel-default akismetAdvancedOptions"> <div class="panel-heading"> <h3 class="panel-title">Akismet Advanced Options</h3> </div> <div class="panel-body"> <span class="sub-title">Akismet Spam Message Handling</span> <br /> @Html.CheckBoxFor(model => model.AkismetDeleteSpam) @Html.LabelFor(model => model.AkismetDeleteSpam) <br /><br /> <span class="sub-title" title="you will have to register in the akismet's site (http://akismet.com/) by specifying your blog's url to obtain this key"> @Html.LabelFor(model => model.AkismetKey) </span> <br /> @Html.TextBoxFor(model => model.AkismetKey, new {@class = "inputBoxBig"}) <br /><br /> <span class="sub-title" title="by default, this field is populated with the root site address identified by the url in the address bar"> @Html.LabelFor(model => model.AkismetUrl) </span> <br /> @Html.TextBoxFor(model => model.AkismetUrl, new {@class = "inputBoxBig"}) </div> </div> </div> </div> <p class="pull-right"> <input type="submit" value="Update Settings" class="btn btn-lg btn-primary" /> </p> } </div>
the_stack
using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Globalization; using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; var Params = new Dictionary<string, string>(); const string ParamSeparator = ":"; foreach (var arg in Args) { var index = @arg.IndexOf(ParamSeparator); if (index > -1){ Params.Add(arg.Substring(0, index).ToLowerInvariant(), arg.Substring(index + 1)); } } var options = new PocosGeneratorOptions { Output = Params.ContainsKey("output") ? Params["output"] : "DbModels.cs", ConfigFilePath = Params.ContainsKey("config") ? Params["config"] : "appsettings.json", ConnectionStringName = Params.ContainsKey("connectionstring") ? Params["connectionstring"] : "ConnectionStrings:DefaultConnection", Namespace = Params.ContainsKey("namespace") ? Params["namespace"] : "Models", SpClass = Params.ContainsKey("spclass") ? Params["spclass"] : null, TvpClass = Params.ContainsKey("tvpclass") ? Params["tvpclass"] : null, DapperContribAttributes = Params.ContainsKey("dapper") && Params["dapper"] == "true", ClassPrefix = Params.ContainsKey("classprefix") ? Params["classprefix"] : null, ClassSuffix = Params.ContainsKey("classsufix") ? Params["classsufix"] : null, GeneratePocos = Params.ContainsKey("pocos") && Params["pocos"] == "false" ? false : true, IncludeViews = Params.ContainsKey("views") && Params["views"] == "false" ? false : true, SchemaName = Params.ContainsKey("schema") ? Params["schema"] : null }; public class PocosGenerator { private readonly PocosGeneratorOptions _options; private readonly SchemaReader reader; private DbConnection _connection; private StringBuilder builder; public Tables Tables = null; private List<string> splist = null; private Dictionary<string, List<string>> tvplist = null; public string ConnectionString; public PocosGenerator(PocosGeneratorOptions options){ _options = options; reader = GetSchemaReader(); ConnectionString = GetConnectionString(); builder = new StringBuilder(); } public void GenerateClass(){ builder.AppendLine("// <auto-generated />"); builder.AppendLine("//"); builder.AppendLine("// This file was automatically generated by PocosGenerator.csx, inspired from the PetaPoco T4 Template"); builder.AppendLine("// Do not make changes directly to this file - edit the PocosGenerator.GenerateClass() method in the PocosGenerator.Core.csx file instead"); builder.AppendLine("// "); builder.AppendLine(""); builder.AppendLine("using System;"); if (_options.DapperContribAttributes) builder.AppendLine("using Dapper.Contrib.Extensions;"); builder.AppendLine("using System.Collections.Generic;"); builder.AppendLine(""); builder.AppendLine($"namespace {_options.Namespace}"); builder.AppendLine("{"); builder.AppendLine(" // ReSharper disable InconsistentNaming"); if (_options.GeneratePocos){ foreach (Table tbl in from t in Tables where !t.Ignore select t){ builder.AppendLine(""); if (_options.DapperContribAttributes) builder.AppendLine($" [Table(\"{tbl.Name}\")]"); builder.AppendLine($" public partial class {tbl.ClassName}"); builder.AppendLine(" {"); foreach(Column col in from c in tbl.Columns where !c.Ignore select c) { // Column bindings if (_options.DapperContribAttributes && col.IsPK){ builder.AppendLine(" [Key]"); } builder.AppendLine($" public {col.PropertyType}{CheckNullable(col)} {col.PropertyName} {{ get; set; }}"); } builder.AppendLine(" }"); } } if (!string.IsNullOrWhiteSpace(_options.SpClass)){ builder.AppendLine(""); builder.AppendLine(" /// <summary>"); builder.AppendLine($" /// {_options.SpClass} is a static class holding the list of stored procedures of the {_options.ConnectionStringName} database."); builder.AppendLine(" /// This makes passing paramaters clearer and at the same time will prevent typos and the resulting runtime errors."); builder.AppendLine(" /// </summary>"); builder.AppendLine(" /// <remarks>"); builder.AppendLine(" /// The class is dynamically generated by running our poco generator"); builder.AppendLine(" /// </remarks>"); builder.AppendLine($" public static partial class {_options.SpClass} {{"); foreach (string sp in splist){ builder.AppendLine($" public const string {CleanUpStoredProcName(sp)} = \"{sp}\";"); } builder.AppendLine(" }"); } if (!string.IsNullOrWhiteSpace(_options.TvpClass)){ builder.AppendLine(""); builder.AppendLine(" /// <summary>"); builder.AppendLine($" /// {_options.TvpClass} is a static class holding the list of Table Valued Parameters of the {_options.ConnectionStringName} database."); builder.AppendLine(" /// This makes calling stored procedures clearer and at the same time will prevent typos and the resulting runtime errors."); builder.AppendLine(" /// </summary>"); builder.AppendLine(" /// <remarks>"); builder.AppendLine(" /// The class is dynamically generated by running our poco generator"); builder.AppendLine(" /// </remarks>"); builder.AppendLine($" public static partial class {_options.TvpClass} {{"); foreach (var tvp in tvplist){ builder.AppendLine($" public static class {CleanUpTVPName(tvp.Key)} {{"); builder.AppendLine($" public const string Name = \"{tvp.Key}\";"); builder.AppendLine($" public static List<string> Columns = new List<string> {{"); foreach (var column in tvp.Value) { builder.AppendLine($" \"{column}\","); } builder.AppendLine(" };"); builder.AppendLine(" }"); } builder.AppendLine(" }"); } builder.AppendLine("}"); } public bool ReadSchema(){ using (DbConnection conn = InitDbConnection()){ Tables = LoadTables(); splist = LoadStoredProcedures(); tvplist = LoadTVPs(); } return Tables.Any() || splist.Any() || tvplist.Any(); } public string Content {get => builder.ToString();} private SchemaReader GetSchemaReader(){ switch (_options.DbType){ case DatabaseType.MySql: return new MySqlSchemaReader(); case DatabaseType.Oracle: return new OracleSchemaReader(); case DatabaseType.PostgreSQL: return new PostGreSqlSchemaReader(); case DatabaseType.SQL_CE: return new SqlServerCeSchemaReader(); default: return new SqlServerSchemaReader(); } } //Todo: add connection types for other Db's private DbConnection GetDbConnection(){ switch (_options.DbType){ case DatabaseType.MySql: case DatabaseType.Oracle: case DatabaseType.PostgreSQL: case DatabaseType.SQL_CE: default: return new SqlConnection(ConnectionString); } } public DbConnection InitDbConnection(){ _connection = GetDbConnection(); return _connection; } private string GetConnectionString() { string separator1 = Path.DirectorySeparatorChar.ToString(); string separator2 = Path.AltDirectorySeparatorChar.ToString(); var path = Directory.GetCurrentDirectory().TrimEnd(); if (!path.EndsWith(separator1) || !path.EndsWith(separator2)){ if (path.Contains(separator2)){ path = path + separator2; } else { path = path + separator1; } } var fullPath = Path.GetFullPath(path + _options.ConfigFilePath); var appSettings = new ConfigurationBuilder().AddJsonFile(fullPath, optional: false).Build(); var connStr = appSettings[_options.ConnectionStringName]; return connStr; } private Tables LoadTables() { try { Tables result; try { _connection.ConnectionString=ConnectionString; _connection.Open(); result=reader.ReadSchema(_connection); // Remove unrequired tables/views for (int i=result.Count-1; i>=0; i--) { if (_options.SchemaName!=null && string.Compare(result[i].Schema, _options.SchemaName, true)!=0) { result.RemoveAt(i); continue; } if (!_options.IncludeViews && result[i].IsView) { result.RemoveAt(i); continue; } } _connection.Close(); var rxClean = new Regex("^(Equals|GetHashCode|GetType|ToString|repo|Save|IsNew|Insert|Update|Delete|Exists|SingleOrDefault|Single|First|FirstOrDefault|Fetch|Page|Query)$"); foreach (var t in result) { t.ClassName = _options.ClassPrefix + t.ClassName + _options.ClassSuffix; foreach (var c in t.Columns) { c.PropertyName = rxClean.Replace(c.PropertyName, "_$1"); // Make sure property name doesn't clash with class name if (c.PropertyName == t.ClassName) c.PropertyName = "_" + c.PropertyName; } } } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); WriteLine(string.Format("Failed to load data `{0}`", error)); builder.AppendLine(""); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine($"// Failed to load data `{error}`"); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine(""); return new Tables(); } return result; } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); WriteLine(string.Format("Failed to read database schema - {0}", error)); builder.AppendLine(""); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine("// Failed to read database schema - {error}"); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine(""); return new Tables(); } } private List<string> LoadStoredProcedures() { try { List<string> result; _connection.ConnectionString = ConnectionString; _connection.Open(); result=reader.GetStoredProcedures(_connection); _connection.Close(); return result; } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); WriteLine(string.Format("Failed to read database schema - {0}", error)); builder.AppendLine(""); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine($"// Failed to read database schema - {error}"); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine(""); return new List<string>(); } } private Dictionary<string, List<string>> LoadTVPs() { try { Dictionary<string, List<string>> result; _connection.ConnectionString = ConnectionString; _connection.Open(); result=reader.GetTVPs(_connection); _connection.Close(); return result; } catch (Exception x) { var error=x.Message.Replace("\r\n", "\n").Replace("\n", " "); WriteLine(string.Format("Failed to read database schema - {0}", error)); builder.AppendLine(""); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine($"// Failed to read database schema - {error}"); builder.AppendLine("// -----------------------------------------------------------------------------------------"); builder.AppendLine(""); return new Dictionary<string, List<string>>(); } } private static string CheckNullable(Column col) { string result=""; if(col.IsNullable && col.PropertyType !="byte[]" && col.PropertyType !="string" && col.PropertyType !="Microsoft.SqlServer.Types.SqlGeography" && col.PropertyType !="Microsoft.SqlServer.Types.SqlGeometry" ) result="?"; return result; } private static Func<string, string> CleanUpStoredProcName = (str) => { if (str.StartsWith("sp_", StringComparison.OrdinalIgnoreCase)) { str = str.Remove(0, 3); } else if (str.StartsWith("sp", StringComparison.OrdinalIgnoreCase)) { str = str.Remove(0, 2); } return str.Replace('.','_'); }; private static Func<string, string> CleanUpTVPName = (str) => { return str.Replace('.','_'); }; } public enum DatabaseType { MySql, SQL_CE, PostgreSQL, Oracle, SQLServer } public class PocosGeneratorOptions { public string Output {get;set;} public string ConnectionStringName {get;set;} /// Namespace for the generated class public string Namespace {get;set;} public string ClassPrefix {get;set;} public string ClassSuffix {get;set;} public string SchemaName {get;set;} public bool IncludeViews {get;set;} public bool GeneratePocos {get;set;} public bool DapperContribAttributes {get;set;} /// If left blank, class with stored procedure names won't be generated public string SpClass {get;set;} /// If left blank, class with Table Valued Parameters won't be generated public string TvpClass {get;set;} public DatabaseType DbType {get;set;} = DatabaseType.SQLServer; /// Relative path to script public string ConfigFilePath {get;set;} } public class Table { public List<Column> Columns; public string Name; public string Schema; public bool IsView; public string CleanName; public string ClassName; public string SequenceName; public bool Ignore; public Column PK { get { return this.Columns.SingleOrDefault(x=>x.IsPK); } } public Column GetColumn(string columnName) { return Columns.Single(x=>string.Compare(x.Name, columnName, true)==0); } public Column this[string columnName] { get { return GetColumn(columnName); } } } public class Column { public string Name; public string PropertyName; public string PropertyType; public bool IsPK; public bool IsNullable; public bool IsAutoIncrement; public bool Ignore; } public class Tables : List<Table> { public Tables() { } public Table GetTable(string tableName) { return this.Single(x=>string.Compare(x.Name, tableName, true)==0); } public Table this[string tableName] { get { return GetTable(tableName); } } } static Regex rxCleanUp = new Regex(@"[^\w\d_]", RegexOptions.Compiled); static Func<string, string> CleanUp = (str) => { str = rxCleanUp.Replace(str, "_"); if (char.IsDigit(str[0])) str = "_" + str; return str; }; static string zap_password(string connectionString) { var rx = new Regex("password=.*;", RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase); return rx.Replace(connectionString, "password=**zapped**;"); } public abstract class SchemaReader { public abstract Tables ReadSchema(DbConnection connection); public abstract List<string> GetStoredProcedures(DbConnection connection); public abstract Dictionary<string, List<string>> GetTVPs(DbConnection connection); } public class SqlServerSchemaReader : SchemaReader { public override List<string> GetStoredProcedures(DbConnection connection) { var result = new List<string>(); _connection = connection; var cmd = _connection.CreateCommand(); cmd.Connection = connection; cmd.CommandText = @"SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE routine_type = 'PROCEDURE' AND LEFT(Routine_Name, 3) NOT IN ('sp_', 'xp_', 'ms_') AND LEFT(Routine_Name, 6) NOT IN ('spEMT_', 'spFXT_') ORDER BY Routine_Name"; // pull the SP list in a reader using(cmd) { using (var rdr = cmd.ExecuteReader()) { while(rdr.Read()) { result.Add($"{rdr["Specific_Schema"]}.{rdr["Routine_Name"]}"); } } } return result; } public override Dictionary<string, List<string>> GetTVPs(DbConnection connection) { var result = new Dictionary<string, List<string>>(); _connection = connection; var cmd = _connection.CreateCommand(); cmd.Connection = connection; cmd.CommandText = @"select s.name as [Schema], t.name as [Type], c.name as [Column] from sys.table_types t inner join sys.schemas AS s ON t.[schema_id] = s.[schema_id] inner join sys.columns c on c.[object_id] = t.type_table_object_id where is_user_defined = 1"; // pull the SP list in a reader using(cmd) { using (var rdr = cmd.ExecuteReader()) { while(rdr.Read()) { var tvp = $"{rdr["Schema"]}.{rdr["Type"]}"; if (result.ContainsKey(tvp)) { result[tvp].Add(rdr["Column"].ToString()); } else { result.Add(tvp, new List<string>{ rdr["Column"].ToString() }); } } } } return result; } // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection) { var result=new Tables(); _connection=connection; var cmd=_connection.CreateCommand(); cmd.Connection=connection; cmd.CommandText = TABLE_SQL_INCLUDE_VIEWS; //TableCommandText; // Change - Allows the inclusion of views //cmd.CommandText = TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema=rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); tbl.Ignore = true; result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) { pkColumn.IsPK=true; } } return result; } DbConnection _connection; List<Column> LoadColumns(Table tbl) { using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); p = cmd.CreateParameter(); p.ParameterName = "@schemaName"; p.Value=tbl.Schema; cmd.Parameters.Add(p); //var isFirstColumn = true; var result = new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { // Skip Computed Columns from mapping if (((int)rdr["IsComputed"]) != 1) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString()); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=((int)rdr["IsIdentity"])==1; /*if (isFirstColumn && !col.IsAutoIncrement) { if (col.PropertyType == "Guid") { // || col.PropertyName.ToLower() == "id") { col.IsAutoIncrement = true; } } isFirstColumn = false;*/ result.Add(col); } } } return result; } } string GetPK(string table){ string sql=@"SELECT c.name AS ColumnName FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id INNER JOIN sys.objects AS o ON i.object_id = o.object_id LEFT OUTER JOIN sys.columns AS c ON ic.object_id = c.object_id AND c.column_id = ic.column_id WHERE (i.is_primary_key = 1) AND (o.name = @tableName)"; using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result=cmd.ExecuteScalar(); if(result!=null) return result.ToString(); } return ""; } string GetPropertyType(string sqlType) { string sysType="string"; switch (sqlType) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": case "time": sysType= "DateTime"; break; case "float": sysType="double"; break; case "real": sysType="float"; break; case "numeric": case "smallmoney": case "decimal": case "money": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; case "geography": sysType = "Microsoft.SqlServer.Types.SqlGeography"; break; case "geometry": sysType = "Microsoft.SqlServer.Types.SqlGeometry"; break; } return sysType; } const string TABLE_SQL_INCLUDE_VIEWS = @"SELECT * FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME"; const string TABLE_SQL= @"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' OR TABLE_TYPE='VIEW' ORDER BY TABLE_NAME"; const string COLUMN_SQL=@"SELECT TABLE_CATALOG AS [Database], TABLE_SCHEMA AS Owner, TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS OrdinalPosition, COLUMN_DEFAULT AS DefaultSetting, IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS MaxLength, DATETIME_PRECISION AS DatePrecision, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsIdentity') AS IsIdentity, COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsComputed') as IsComputed FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@tableName AND TABLE_SCHEMA=@schemaName ORDER BY OrdinalPosition ASC"; } public class SqlServerCeSchemaReader : SchemaReader { public override List<string> GetStoredProcedures(DbConnection connection) { return new List<string>(); } public override Dictionary<string, List<string>> GetTVPs(DbConnection connection) { return new Dictionary<string, List<string>>(); } // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection) { var result=new Tables(); _connection=connection; var cmd=_connection.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); tbl.Schema=null; tbl.IsView=false; result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } DbConnection _connection; List<Column> LoadColumns(Table tbl) { using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString()); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=rdr["AUTOINC_INCREMENT"]!=DBNull.Value; result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"SELECT KCU.COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON KCU.CONSTRAINT_NAME=TC.CONSTRAINT_NAME WHERE TC.CONSTRAINT_TYPE='PRIMARY KEY' AND KCU.TABLE_NAME=@tableName"; using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result=cmd.ExecuteScalar(); if(result!=null) return result.ToString(); } return ""; } string GetPropertyType(string sqlType) { string sysType="string"; switch (sqlType) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": case "time": sysType= "DateTime"; break; case "float": sysType="double"; break; case "real": sysType="float"; break; case "numeric": case "smallmoney": case "decimal": case "money": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; } return sysType; } const string TABLE_SQL=@"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='TABLE'"; const string COLUMN_SQL=@"SELECT TABLE_CATALOG AS [Database], TABLE_SCHEMA AS Owner, TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS OrdinalPosition, COLUMN_DEFAULT AS DefaultSetting, IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, AUTOINC_INCREMENT, CHARACTER_MAXIMUM_LENGTH AS MaxLength, DATETIME_PRECISION AS DatePrecision FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@tableName ORDER BY OrdinalPosition ASC"; } public class PostGreSqlSchemaReader : SchemaReader { public override List<string> GetStoredProcedures(DbConnection connection) { return new List<string>(); } public override Dictionary<string, List<string>> GetTVPs(DbConnection connection) { return new Dictionary<string, List<string>>(); } // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection) { var result=new Tables(); _connection=connection; var cmd=_connection.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["table_name"].ToString(); tbl.Schema=rdr["table_schema"].ToString(); tbl.IsView=string.Compare(rdr["table_type"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } DbConnection _connection; List<Column> LoadColumns(Table tbl) { using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["column_name"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["udt_name"].ToString()); col.IsNullable=rdr["is_nullable"].ToString()=="YES"; col.IsAutoIncrement = rdr["column_default"].ToString().StartsWith("nextval("); result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"SELECT kcu.column_name FROM information_schema.key_column_usage kcu JOIN information_schema.table_constraints tc ON kcu.constraint_name=tc.constraint_name WHERE lower(tc.constraint_type)='primary key' AND kcu.table_name=@tablename"; using (var cmd=_connection.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; var p = cmd.CreateParameter(); p.ParameterName = "@tableName"; p.Value=table; cmd.Parameters.Add(p); var result=cmd.ExecuteScalar(); if(result!=null) return result.ToString(); } return ""; } string GetPropertyType(string sqlType) { switch (sqlType) { case "int8": case "serial8": return "long"; case "bool": return "bool"; case "bytea ": return "byte[]"; case "float8": return "double"; case "int4": case "serial4": return "int"; case "money ": return "decimal"; case "numeric": return "decimal"; case "float4": return "float"; case "int2": return "short"; case "time": case "timetz": case "timestamp": case "timestamptz": case "date": return "DateTime"; default: return "string"; } } const string TABLE_SQL=@" SELECT table_name, table_schema, table_type FROM information_schema.tables WHERE (table_type='BASE TABLE' OR table_type='VIEW') AND table_schema NOT IN ('pg_catalog', 'information_schema'); "; const string COLUMN_SQL=@" SELECT column_name, is_nullable, udt_name, column_default FROM information_schema.columns WHERE table_name=@tableName; "; } public class MySqlSchemaReader : SchemaReader { public override List<string> GetStoredProcedures(DbConnection connection) { return new List<string>(); } public override Dictionary<string, List<string>> GetTVPs(DbConnection connection) { return new Dictionary<string, List<string>>(); } // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection) { var result=new Tables(); var cmd=connection.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema=rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } //this will return everything for the DB var schema = connection.GetSchema("COLUMNS"); //loop again - but this time pull by table name foreach (var item in result) { item.Columns=new List<Column>(); //pull the columns from the schema var columns = schema.Select("TABLE_NAME='" + item.Name + "'"); foreach (var row in columns) { Column col=new Column(); col.Name=row["COLUMN_NAME"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(row); col.IsNullable=row["IS_NULLABLE"].ToString()=="YES"; col.IsPK=row["COLUMN_KEY"].ToString()=="PRI"; col.IsAutoIncrement=row["extra"].ToString().ToLower().IndexOf("auto_increment")>=0; item.Columns.Add(col); } } return result; } static string GetPropertyType(DataRow row) { bool bUnsigned = row["COLUMN_TYPE"].ToString().IndexOf("unsigned")>=0; string propType="string"; switch (row["DATA_TYPE"].ToString()) { case "bigint": propType= bUnsigned ? "ulong" : "long"; break; case "int": propType= bUnsigned ? "uint" : "int"; break; case "smallint": propType= bUnsigned ? "ushort" : "short"; break; case "guid": propType= "Guid"; break; case "smalldatetime": case "date": case "datetime": case "timestamp": propType= "DateTime"; break; case "float": propType="float"; break; case "double": propType="double"; break; case "numeric": case "smallmoney": case "decimal": case "money": propType= "decimal"; break; case "bit": case "bool": case "boolean": propType= "bool"; break; case "tinyint": propType = bUnsigned ? "byte" : "sbyte"; break; case "image": case "binary": case "blob": case "mediumblob": case "longblob": case "varbinary": propType= "byte[]"; break; } return propType; } const string TABLE_SQL=@" SELECT * FROM information_schema.tables WHERE (table_type='BASE TABLE' OR table_type='VIEW') "; } public class OracleSchemaReader : SchemaReader { public override List<string> GetStoredProcedures(DbConnection connection) { return new List<string>(); } public override Dictionary<string, List<string>> GetTVPs(DbConnection connection) { return new Dictionary<string, List<string>>(); } // SchemaReader.ReadSchema public override Tables ReadSchema(DbConnection connection) { var result=new Tables(); _connection=connection; var cmd=_connection.CreateCommand(); cmd.Connection=connection; cmd.CommandText=TABLE_SQL; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); //pull the tables in a reader using(cmd) { using (var rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Table tbl=new Table(); tbl.Name=rdr["TABLE_NAME"].ToString(); tbl.Schema = rdr["TABLE_SCHEMA"].ToString(); tbl.IsView=string.Compare(rdr["TABLE_TYPE"].ToString(), "View", true)==0; tbl.CleanName=CleanUp(tbl.Name); tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); result.Add(tbl); } } } foreach (var tbl in result) { tbl.Columns=LoadColumns(tbl); // Mark the primary key string PrimaryKey=GetPK(tbl.Name); var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==PrimaryKey.ToLower().Trim()); if(pkColumn!=null) pkColumn.IsPK=true; } return result; } DbConnection _connection; DbProviderFactory _factory; List<Column> LoadColumns(Table tbl) { using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=COLUMN_SQL; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); var p = cmd.CreateParameter(); p.ParameterName = ":tableName"; p.Value=tbl.Name; cmd.Parameters.Add(p); var result=new List<Column>(); using (IDataReader rdr=cmd.ExecuteReader()) { while(rdr.Read()) { Column col=new Column(); col.Name=rdr["ColumnName"].ToString(); col.PropertyName=CleanUp(col.Name); col.PropertyType=GetPropertyType(rdr["DataType"].ToString(), (rdr["DataType"] == DBNull.Value ? null : rdr["DataType"].ToString())); col.IsNullable=rdr["IsNullable"].ToString()=="YES"; col.IsAutoIncrement=true; result.Add(col); } } return result; } } string GetPK(string table){ string sql=@"select column_name from USER_CONSTRAINTS uc inner join USER_CONS_COLUMNS ucc on uc.constraint_name = ucc.constraint_name where uc.constraint_type = 'P' and uc.table_name = upper(:tableName) and ucc.position = 1"; using (var cmd=_factory.CreateCommand()) { cmd.Connection=_connection; cmd.CommandText=sql; cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); var p = cmd.CreateParameter(); p.ParameterName = ":tableName"; p.Value=table; cmd.Parameters.Add(p); var result=cmd.ExecuteScalar(); if(result!=null) return result.ToString(); } return ""; } string GetPropertyType(string sqlType, string dataScale) { string sysType="string"; switch (sqlType.ToLower()) { case "bigint": sysType = "long"; break; case "smallint": sysType= "short"; break; case "int": sysType= "int"; break; case "uniqueidentifier": sysType= "Guid"; break; case "smalldatetime": case "datetime": case "date": sysType= "DateTime"; break; case "float": sysType="double"; break; case "real": case "numeric": case "smallmoney": case "decimal": case "money": case "number": sysType= "decimal"; break; case "tinyint": sysType = "byte"; break; case "bit": sysType= "bool"; break; case "image": case "binary": case "varbinary": case "timestamp": sysType= "byte[]"; break; } if (sqlType == "number" && dataScale == "0") return "long"; return sysType; } const string TABLE_SQL=@"select TABLE_NAME from USER_TABLES"; const string COLUMN_SQL=@"select table_name TableName, column_name ColumnName, data_type DataType, data_scale DataScale, nullable IsNullable from USER_TAB_COLS utc where table_name = upper(:tableName) order by column_id"; } /// <summary> /// Summary for the Inflector class /// </summary> public static class Inflector { private static readonly List<InflectorRule> _plurals = new List<InflectorRule>(); private static readonly List<InflectorRule> _singulars = new List<InflectorRule>(); private static readonly List<string> _uncountables = new List<string>(); /// <summary> /// Initializes the <see cref="Inflector"/> class. /// </summary> static Inflector() { AddPluralRule("$", "s"); AddPluralRule("s$", "s"); AddPluralRule("(ax|test)is$", "$1es"); AddPluralRule("(octop|vir)us$", "$1i"); AddPluralRule("(alias|status)$", "$1es"); AddPluralRule("(bu)s$", "$1ses"); AddPluralRule("(buffal|tomat)o$", "$1oes"); AddPluralRule("([ti])um$", "$1a"); AddPluralRule("sis$", "ses"); AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves"); AddPluralRule("(hive)$", "$1s"); AddPluralRule("([^aeiouy]|qu)y$", "$1ies"); AddPluralRule("(x|ch|ss|sh)$", "$1es"); AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices"); AddPluralRule("([m|l])ouse$", "$1ice"); AddPluralRule("^(ox)$", "$1en"); AddPluralRule("(quiz)$", "$1zes"); AddSingularRule("s$", String.Empty); AddSingularRule("ss$", "ss"); AddSingularRule("Cms$", "Cms"); AddSingularRule("(n)ews$", "$1ews"); //AddSingularRule("([ti])a$", "$1um"); AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis"); AddSingularRule("(^analy)ses$", "$1sis"); AddSingularRule("([^f])ves$", "$1fe"); AddSingularRule("(hive)s$", "$1"); AddSingularRule("(tive)s$", "$1"); AddSingularRule("([lr])ves$", "$1f"); AddSingularRule("([^aeiouy]|qu)ies$", "$1y"); AddSingularRule("(s)eries$", "$1eries"); AddSingularRule("(m)ovies$", "$1ovie"); AddSingularRule("(x|ch|ss|sh)es$", "$1"); AddSingularRule("([m|l])ice$", "$1ouse"); AddSingularRule("(bus)es$", "$1"); AddSingularRule("(o)es$", "$1"); AddSingularRule("(shoe)s$", "$1"); AddSingularRule("(cris|ax|test)es$", "$1is"); AddSingularRule("(octop|vir)i$", "$1us"); AddSingularRule("(alias|status)$", "$1"); AddSingularRule("(alias|status)es$", "$1"); AddSingularRule("^(ox)en", "$1"); AddSingularRule("(vert|ind)ices$", "$1ex"); AddSingularRule("(matr)ices$", "$1ix"); AddSingularRule("(quiz)zes$", "$1"); AddIrregularRule("person", "people"); AddIrregularRule("man", "men"); AddIrregularRule("child", "children"); AddIrregularRule("sex", "sexes"); AddIrregularRule("tax", "taxes"); AddIrregularRule("move", "moves"); AddUnknownCountRule("equipment"); AddUnknownCountRule("information"); AddUnknownCountRule("rice"); AddUnknownCountRule("money"); AddUnknownCountRule("species"); AddUnknownCountRule("series"); AddUnknownCountRule("fish"); AddUnknownCountRule("sheep"); } /// <summary> /// Adds the irregular rule. /// </summary> /// <param name="singular">The singular.</param> /// <param name="plural">The plural.</param> private static void AddIrregularRule(string singular, string plural) { AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1))); AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1))); } /// <summary> /// Adds the unknown count rule. /// </summary> /// <param name="word">The word.</param> private static void AddUnknownCountRule(string word) { _uncountables.Add(word.ToLower()); } /// <summary> /// Adds the plural rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddPluralRule(string rule, string replacement) { _plurals.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Adds the singular rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddSingularRule(string rule, string replacement) { _singulars.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Makes the plural. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakePlural(string word) { return ApplyRules(_plurals, word); } /// <summary> /// Makes the singular. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeSingular(string word) { return ApplyRules(_singulars, word); } /// <summary> /// Applies the rules. /// </summary> /// <param name="rules">The rules.</param> /// <param name="word">The word.</param> /// <returns></returns> private static string ApplyRules(IList<InflectorRule> rules, string word) { string result = word; if (!_uncountables.Contains(word.ToLower())) { for (int i = rules.Count - 1; i >= 0; i--) { string currentPass = rules[i].Apply(word); if (currentPass != null) { result = currentPass; break; } } } return result; } /// <summary> /// Converts the string to title case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string ToTitleCase(string word) { return Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])", delegate(Match match) { return match.Captures[0].Value.ToUpper(); }); } /// <summary> /// Converts the string to human case. /// </summary> /// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param> /// <returns></returns> public static string ToHumanCase(string lowercaseAndUnderscoredWord) { return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " ")); } /// <summary> /// Adds the underscores. /// </summary> /// <param name="pascalCasedWord">The pascal cased word.</param> /// <returns></returns> public static string AddUnderscores(string pascalCasedWord) { return Regex.Replace(Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower(); } /// <summary> /// Makes the initial caps. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialCaps(string word) { return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower()); } /// <summary> /// Makes the initial lower case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialLowerCase(string word) { return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); } /// <summary> /// Determine whether the passed string is numeric, by attempting to parse it to a double /// </summary> /// <param name="str">The string to evaluated for numeric conversion</param> /// <returns> /// <c>true</c> if the string can be converted to a number; otherwise, <c>false</c>. /// </returns> public static bool IsStringNumeric(string str) { double result; return (double.TryParse(str, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out result)); } /// <summary> /// Adds the ordinal suffix. /// </summary> /// <param name="number">The number.</param> /// <returns></returns> public static string AddOrdinalSuffix(string number) { if (IsStringNumeric(number)) { int n = int.Parse(number); int nMod100 = n % 100; if (nMod100 >= 11 && nMod100 <= 13) return String.Concat(number, "th"); switch (n % 10) { case 1: return String.Concat(number, "st"); case 2: return String.Concat(number, "nd"); case 3: return String.Concat(number, "rd"); default: return String.Concat(number, "th"); } } return number; } /// <summary> /// Converts the underscores to dashes. /// </summary> /// <param name="underscoredWord">The underscored word.</param> /// <returns></returns> public static string ConvertUnderscoresToDashes(string underscoredWord) { return underscoredWord.Replace('_', '-'); } #region Nested type: InflectorRule /// <summary> /// Summary for the InflectorRule class /// </summary> private class InflectorRule { /// <summary> /// /// </summary> public readonly Regex regex; /// <summary> /// /// </summary> public readonly string replacement; /// <summary> /// Initializes a new instance of the <see cref="InflectorRule"/> class. /// </summary> /// <param name="regexPattern">The regex pattern.</param> /// <param name="replacementText">The replacement text.</param> public InflectorRule(string regexPattern, string replacementText) { regex = new Regex(regexPattern, RegexOptions.IgnoreCase); replacement = replacementText; } /// <summary> /// Applies the specified word. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public string Apply(string word) { if (!regex.IsMatch(word)) return null; string replace = regex.Replace(word, replacement); if (word == word.ToUpper()) replace = replace.ToUpper(); return replace; } } #endregion }
the_stack