public static object ProcessMillisecond(string source, string propertyName) { try { if (source != null && source.Length > 0) { Newtonsoft.Json.Linq.JArray itmarr = Newtonsoft.Json.Linq.JArray.Parse(source); foreach (var itm in itmarr) { var val = itm[propertyName]; if (val != null && val.ToString().Length > 0) { string[] tSplit = val.ToString().Split('.'); if (tSplit.Length == 2) { tSplit[1] = tSplit[1].Substring(6, tSplit[1].Length - 6); itm[propertyName] = string.Join(".", tSplit); } } } return(itmarr.ToString()); } } catch (Exception ex) { AggieGlobalLogManager.Fatal("Millisecond conversion failed. exception{0}", ex.Message); } return(source); }
private void ExtraGuiAction(Newtonsoft.Json.Linq.JArray resp) { string s = resp.ToString(); rtbResults.AppendText(s); rtbResults.AppendText("++++++++++++++++++++++++"); }
public IActionResult InstanceManage() { string groupId = Request.Querys("groupid"); Business.FlowTask flowTask = new Business.FlowTask(); var groupTasks = flowTask.GetListByGroupId(groupId.ToGuid()); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var groupTask in groupTasks) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject(); string opation = "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"cngStatus('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-exclamation\"></i>状态</a>"; if (groupTask.ExecuteType.In(0, 1) && 5 != groupTask.TaskType) { opation += "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"designate('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-hand-o-right\"></i>指派</a>" + "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"goTo('" + groupTask.Id.ToString() + "');\"><i class=\"fa fa-level-up\"></i>跳转</a>"; } jObject.Add("id", groupTask.Id); jObject.Add("StepID", groupTask.StepName); jObject.Add("SenderName", groupTask.SenderName); jObject.Add("ReceiveTime", groupTask.ReceiveTime.ToDateTimeString()); jObject.Add("ReceiveName", groupTask.ReceiveName); jObject.Add("CompletedTime1", groupTask.CompletedTime1.HasValue ? groupTask.CompletedTime1.Value.ToDateTimeString() : ""); jObject.Add("Status", flowTask.GetExecuteTypeTitle(groupTask.ExecuteType)); jObject.Add("Comment", groupTask.Comments); jObject.Add("Note", groupTask.Note); jObject.Add("Opation", opation); jArray.Add(jObject); } ViewData["json"] = jArray.ToString(); ViewData["appid"] = Request.Querys("appid"); ViewData["iframeid"] = Request.Querys("iframeid"); return(View()); }
public IActionResult Index() { bool isoneself = "1".Equals(Request.Querys("isoneself")); Guid userId = Current.UserId; var all = new Business.FlowComment().GetAll(); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); Business.User user = new Business.User(); foreach (var comment in all) { if (isoneself && comment.UserId != userId) { continue; } Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", comment.Id }, { "Comments", comment.Comments }, { "UserId", !comment.UserId.IsEmptyGuid() ? user.GetName(comment.UserId) : "全部人员" }, { "AddType", comment.AddType == 0 ? "用户添加" : "管理员添加" }, { "Sort", comment.Sort }, { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + comment.Id + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" } }; jArray.Add(jObject); } ViewData["json"] = jArray.ToString(); ViewData["appId"] = Request.Querys("appid"); ViewData["tabId"] = Request.Querys("tabid"); ViewData["isoneself"] = Request.Querys("isoneself"); return(View()); }
public async Task AGitHubConnector_WillReturnAGitHubUsersRepositories_WhenSearchingSuccessfullyForUser_AndThereIsReposAvailable() { HttpResponseMessage expectedResponseFromGitHub = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(@"{login:'******'}") }; Newtonsoft.Json.Linq.JArray expectedRepositories = Generators.JsonGitHubRepositories.Sample(50, 1).First(); HttpResponseMessage expectedRepositoriesResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(expectedRepositories.ToString()) }; Mock <IAppHttpClient> appHttpClient = new Mock <IAppHttpClient>(); appHttpClient.SetupSequence(c => c.Get(It.IsAny <string>())) .ReturnsAsync(expectedResponseFromGitHub) .ReturnsAsync(expectedRepositoriesResponse); GitHubConnector connector = new GitHubConnector(appHttpClient.Object); GitHubUser result = await connector.FindUser("test"); Assert.AreEqual(result.Repositories.ToList().Count, expectedRepositories.Count); }
//"json lista i da se pazi na identifikacioni kod, mozda ima isti u bazu a primarni je kljuc" //[{"RedniBroj":0,"IdentifikacioniKod":"2d9dfib0-cce9-4da5-af04-f58e4dfb9e5a","DateAndTimeAdded":"2019-08-04T21:03:18.903","P":2,"DbelementC":[{"Id":0,"Grupa":"t","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"s","Vrednost":8,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"n","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"}]}, //{"RedniBroj":1,"IdentifikacioniKod":"76affdcd-9d55-4j36-a082-9c48c5cd37dd","DateAndTimeAdded":"2019-08-04T21:03:19.383","P":2,"DbelementC":[{"Id":0,"Grupa":"t","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"s","Vrednost":8,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"n","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"}]}, //{"RedniBroj":2,"IdentifikacioniKod":"b0f66gda-1b44-4z51-838c-a3587d08f4ff","DateAndTimeAdded":"2019-08-04T21:03:19.387","P":2,"DbelementC":[{"Id":0,"Grupa":"t","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"s","Vrednost":8,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"},{"Id":0,"Grupa":"n","Vrednost":6,"IdElementP":"d94076f1-c953-4899-9161-5a35cc505e77"}]}] public IActionResult Post([FromBody] Newtonsoft.Json.Linq.JArray ListaPretraga) { List <DbelementP> list = JsonConvert.DeserializeObject <List <DbelementP> >(ListaPretraga.ToString()); ZadatakContext db = new ZadatakContext(); foreach (DbelementP item in list) { db.DbelementP.Add(item); } db.SaveChanges(); return(this.Content(ListaPretraga.ToString())); }
public async Task <List <AzureDevOpsBuild> > GetAzureDevOpsBuilds(string patToken, TableStorageAuth tableStorageAuth, string organization, string project, string buildName, bool useCache) { List <AzureDevOpsBuild> builds = new List <AzureDevOpsBuild>(); Newtonsoft.Json.Linq.JArray list = null; if (useCache == true) { //Get the builds from Azure storage AzureTableStorageDA daTableStorage = new AzureTableStorageDA(); list = daTableStorage.GetTableStorageItems(tableStorageAuth, tableStorageAuth.TableAzureDevOpsBuilds, daTableStorage.CreateBuildWorkflowPartitionKey(organization, project, buildName)); } else { //Get the builds from the Azure DevOps API AzureDevOpsAPIAccess api = new AzureDevOpsAPIAccess(); list = await api.GetAzureDevOpsBuildsJArray(patToken, organization, project); } if (list != null) { builds = JsonConvert.DeserializeObject <List <AzureDevOpsBuild> >(list.ToString()); //We need to do some post processing and loop over the list to construct a usable url foreach (AzureDevOpsBuild item in builds) { item.url = $"https://dev.azure.com/{organization}/{project}/_build/results?buildId={item.id}&view=results"; } //sort the final list builds = builds.OrderBy(o => o.queueTime).ToList(); } return(builds); }
/// <summary> /// 得到一个流程所有的表和字段 /// </summary> /// <returns></returns> public string GetTableJSON() { string dbs = Request.Forms("dbs"); if (dbs.IsNullOrWhiteSpace()) { return("[]"); } Newtonsoft.Json.Linq.JArray jArray = null; try { jArray = Newtonsoft.Json.Linq.JArray.Parse(dbs); } catch { return("[]"); } if (null == jArray) { return("[]"); } Business.DbConnection dbConnection = new Business.DbConnection(); Newtonsoft.Json.Linq.JArray jArray1 = new Newtonsoft.Json.Linq.JArray(); foreach (Newtonsoft.Json.Linq.JObject jObject in jArray) { string table = jObject.Value <string>("table"); string connId = jObject.Value <string>("link"); int type = 0; if (!connId.IsGuid(out Guid cid)) { continue; } var dbConnModel = dbConnection.Get(cid); if (null == dbConnModel) { continue; } Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject { { "table", table }, { "connId", connId }, { "type", type }, { "connName", dbConnModel.Name + "(" + dbConnModel.ConnType + ")" } }; var fields = dbConnection.GetTableFields(cid, table); Newtonsoft.Json.Linq.JArray fieldArray = new Newtonsoft.Json.Linq.JArray(); foreach (var field in fields) { Newtonsoft.Json.Linq.JObject jObject2 = new Newtonsoft.Json.Linq.JObject { { "name", field.FieldName }, { "comment", field.Comment } }; fieldArray.Add(jObject2); } jObject1.Add("fields", fieldArray); jArray1.Add(jObject1); } return(jArray1.ToString()); }
public async Task <List <GitHubActionsRun> > GetGitHubActionRuns(string clientId, string clientSecret, TableStorageAuth tableStorageAuth, string owner, string repo, string workflowName, string workflowId, bool useCache) { List <GitHubActionsRun> runs = new List <GitHubActionsRun>(); Newtonsoft.Json.Linq.JArray list = null; if (useCache == true) { //Get the builds from Azure storage AzureTableStorageDA daTableStorage = new AzureTableStorageDA(); list = daTableStorage.GetTableStorageItems(tableStorageAuth, tableStorageAuth.TableGitHubRuns, daTableStorage.CreateBuildWorkflowPartitionKey(owner, repo, workflowName)); } else { //Get the builds from the GitHub API GitHubAPIAccess api = new GitHubAPIAccess(); list = await api.GetGitHubActionRunsJArray(clientId, clientSecret, owner, repo, workflowId); } if (list != null) { runs = JsonConvert.DeserializeObject <List <GitHubActionsRun> >(list.ToString()); //sort the final list runs = runs.OrderBy(o => o.created_at).ToList(); } return(runs); }
public string TreeRefresh() { string refreshId = Request.Querys("refreshid"); if (!refreshId.IsGuid(out Guid rid)) { return("[]"); } Business.Dictionary dictionary = new Business.Dictionary(); var childs = dictionary.GetChilds(rid); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var child in childs) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", child.Id }, { "parentID", child.ParentId }, { "title", child.Status == 1 ? "<span style='color:#999'>" + child.Title + "[作废]</span>" : child.Title }, { "type", "2" }, { "ico", "" }, { "hasChilds", dictionary.HasChilds(child.Id) ? 1 :0 } }; jArray.Add(jObject); } return(jArray.ToString()); }
public string TreeRefresh() { int showType = Request.Querys("showtype").ToString().ToInt(0); bool showUser = !"0".Equals(Request.Querys("shouser")); string refreshId = Request.Querys("refreshid"); Business.Organize organize = new Business.Organize(); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); #region 显示工作组 if (1 == showType) { return(""); } #endregion if (refreshId.IsGuid(out Guid guid)) { var childs = organize.GetChilds(guid); foreach (var child in childs) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject() { { "id", child.Id }, { "parentID", child.ParentId }, { "title", child.Name }, { "ico", "" }, { "link", "" }, { "type", child.Type }, { "hasChilds", organize.HasChilds(child.Id) ? 1 : showUser?organize.HasUsers(child.Id) ? 1 : 0 : 0 } }; jArray.Add(jObject); } if (showUser) { var users = organize.GetUsers(guid); var organizeUsers = new Business.OrganizeUser().GetListByOrganizeId(guid); foreach (var userModel in users) { var organizeUserModel1 = organizeUsers.Find(p => p.UserId == userModel.Id); bool isPartTime = organizeUserModel1.IsMain != 1;//是否是兼职 Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject() { { "id", isPartTime ? organizeUserModel1.Id : userModel.Id }, { "parentID", guid }, { "title", userModel.Name + (isPartTime ? "<span style='color:#666;'>[兼任]</span>" : "") }, { "ico", "fa-user" }, { "link", "" }, { "userID", userModel.Id }, { "type", isPartTime ? 6 : 4 }, { "hasChilds", 0 } }; jArray.Add(jObject); } } } return(jArray.ToString()); }
public void DecodeBatchMode_ArrayContainingNonObject() { var formatter = new JsonEventFormatter(); var array = new JArray { CreateMinimalValidJObject(), "text" }; var data = Encoding.UTF8.GetBytes(array.ToString()); Assert.Throws <ArgumentException>(() => formatter.DecodeBatchModeMessage(data, s_jsonCloudEventBatchContentType, extensionAttributes: null)); }
public static async Task Notifications(SocketMessage Message, string[] SegmentedMessage) { if (SegmentedMessage.Length != 2) { MessageHandler.NotLongEnough(Message); return; } Shared.ConfigHandler.LoadConfig(); Newtonsoft.Json.Linq.JArray JA = Newtonsoft.Json.Linq.JArray.Parse(Shared.ConfigHandler.Config["Notifications"]["DiscordUsers"].ToString()); if (SegmentedMessage[1].ToLower() == "on") { if (JA.ToString().Contains(Message.Author.Id.ToString())) { await MessageHandler.SendMessage(Message, Shared.ConfigHandler.Config["CommandResponses"]["Notifications"]["Already"].ToString(), null, -1, -1, "On"); } else { await MessageHandler.SendMessage(Message, Shared.ConfigHandler.Config["CommandResponses"]["Notifications"]["Set"].ToString(), null, -1, -1, "On"); JA.Add(Message.Author.Id.ToString()); } } else if (SegmentedMessage[1].ToLower() == "off") { if (!JA.ToString().Contains(Message.Author.Id.ToString())) { await MessageHandler.SendMessage(Message, Shared.ConfigHandler.Config["CommandResponses"]["Notifications"]["Already"].ToString(), null, -1, -1, "Off"); } else { await MessageHandler.SendMessage(Message, Shared.ConfigHandler.Config["CommandResponses"]["Notifications"]["Set"].ToString(), null, -1, -1, "Off"); for (int i = 0; i < JA.Count; i++) { if (JA[i].ToString() == Message.Author.Id.ToString()) { JA.RemoveAt(i); break; } } } } Shared.ConfigHandler.Config["Notifications"]["DiscordUsers"] = JA; Shared.ConfigHandler.SaveConfig(); }
private string GetResult(NeoArrayContainer container) { var array = new Newtonsoft.Json.Linq.JArray(); foreach (var x in container.GetVariables()) { array.Add(GetResult(x)); } return(array.ToString(Newtonsoft.Json.Formatting.Indented)); }
public static string GetAllRequestJSON(string search_text, string RequestID) { //Security Check if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "read")) { throw new Exception("No Access."); } //Get current user info SYS_UserView current_user = Controller_User.GetUser(RequestID, RequestID); LINQ_MeetingDataContext dc = new LINQ_MeetingDataContext(); //Security Check For AllDepartment string departmentID = ""; if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "allDepartment")) { departmentID = current_user.DepartmentID; } List <MET_RequestView> the_requestlist = (from c in dc.MET_RequestViews where c.Active == true && (departmentID == "" || (departmentID != "" && c.DepartmentID == departmentID)) && ((search_text == "") || (search_text != "" && ( c.RequestNo.Contains(search_text) || c.RequestStatus.Contains(search_text) || c.RequestTitle.Contains(search_text) || c.RequestType.Contains(search_text) || c.Description.Contains(search_text) || c.Remark.Contains(search_text) || c.DepartmentName.Contains(search_text)))) orderby c.CreatedOn descending select c ).ToList(); var lists = new Newtonsoft.Json.Linq.JArray() as dynamic; foreach (var row in the_requestlist) { dynamic request = new Newtonsoft.Json.Linq.JObject(); request.RequestID = row.RequestID; request.DepartmentID = row.DepartmentID; request.RequestType = row.RequestType; request.RequestNo = row.RequestNo; request.RequestUserName = row.RequestUserName; request.RequestTitle = row.RequestTitle; request.RequestStatus = row.RequestStatus; request.RequestOn = row.RequestOn; request.DepartmentName = row.DepartmentName; request.ApprovalStatus = row.ApprovalStatus; lists.Add(request); } return(lists.ToString()); }
/// <summary> /// 得到导出的JSON字符串 /// </summary> /// <param name="id"></param> /// <returns></returns> public string GetExportString(string id) { if (!id.IsGuid(out Guid dictId)) { return(string.Empty); } var dicts = GetAllChilds(dictId, true); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var dict in dicts) { jArray.Add(Newtonsoft.Json.Linq.JObject.FromObject(dict)); } return(jArray.ToString()); }
public void DecodeBatchMode_Minimal_WithStream() { var array = new JArray { CreateMinimalValidJObject() }; byte[] bytes = Encoding.UTF8.GetBytes(array.ToString()); var formatter = new JsonEventFormatter(); var cloudEvents = formatter.DecodeBatchModeMessage(new MemoryStream(bytes), s_jsonCloudEventBatchContentType, null); var cloudEvent = Assert.Single(cloudEvents); Assert.Equal("event-type", cloudEvent.Type); Assert.Equal("event-id", cloudEvent.Id); Assert.Equal(new Uri("//event-source", UriKind.RelativeOrAbsolute), cloudEvent.Source); }
public static string GetAllAgendaJSON(string search_text, string RequestID) { //Security Check if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "read")) { throw new Exception("No Access."); } //Get current user info SYS_UserView current_user = Controller_User.GetUser(RequestID, RequestID); LINQ_MeetingDataContext dc = new LINQ_MeetingDataContext(); //Security Check For AllDepartment string departmentID = ""; if (!Controller_User_Access.CheckProgramAccess(AccessProgramCode, RequestID, "allDepartment")) { departmentID = current_user.DepartmentID; } List <MET_AgendaView> the_agendalist = (from c in dc.MET_AgendaViews where c.Active == true && (departmentID == "" || (departmentID != "" && c.DepartmentID == departmentID)) && ((search_text == "") || (search_text != "" && ( c.AgendaNo.Contains(search_text) || c.AgendaRemark.Contains(search_text) || c.AgendaStatus.Contains(search_text) || c.CUserCode.Contains(search_text) || c.MUserCode.Contains(search_text) ))) orderby c.CreatedOn descending select c ).ToList(); var lists = new Newtonsoft.Json.Linq.JArray() as dynamic; foreach (var row in the_agendalist) { dynamic agenda = new Newtonsoft.Json.Linq.JObject(); agenda.AgendaID = row.AgendaID; agenda.AgendaNo = row.AgendaNo; agenda.AgendaDate = row.AgendaDate.ToString(); agenda.AgendaRemark = row.AgendaRemark; agenda.AgendaStatus = row.AgendaStatus; lists.Add(agenda); } return(lists.ToString()); }
public static string RandomSampleJson( string json, int?seed = null, int maxNumberOfItems = 10) { Newtonsoft.Json.Linq.JToken root = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(json); Random random = seed.HasValue ? new Random(seed.Value) : new Random(); string sampledJson; if (root.Type == Newtonsoft.Json.Linq.JTokenType.Array) { Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)root; IEnumerable <Newtonsoft.Json.Linq.JToken> tokens = array .OrderBy(x => random.Next()) .Take(random.Next(maxNumberOfItems)); Newtonsoft.Json.Linq.JArray newArray = new Newtonsoft.Json.Linq.JArray(); foreach (Newtonsoft.Json.Linq.JToken token in tokens) { newArray.Add(token); } sampledJson = newArray.ToString(); } else if (root.Type == Newtonsoft.Json.Linq.JTokenType.Object) { Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)root; IEnumerable <Newtonsoft.Json.Linq.JProperty> properties = jobject .Properties() .OrderBy(x => random.Next()) .Take(maxNumberOfItems); Newtonsoft.Json.Linq.JObject newObject = new Newtonsoft.Json.Linq.JObject(); foreach (Newtonsoft.Json.Linq.JProperty property in properties) { newObject.Add(property); } sampledJson = newObject.ToString(); } else { sampledJson = json; } return(sampledJson); }
/// <summary> /// 得到GRID列JSON /// </summary> /// <param name="programFields"></param> /// <returns></returns> private string GetColModels(List <Model.ProgramField> programFields) { if (null == programFields) { return(string.Empty); } Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var field in programFields) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject(); string name = field.Field; if (name.IsNullOrWhiteSpace()) { if (100 == field.ShowType) { name = "opation"; } else if (1 == field.ShowType) { name = "rowserialnumber"; } } jObject.Add("name", name); if (!field.IsSort.IsNullOrWhiteSpace()) { jObject.Add("index", field.IsSort.Trim()); } else { jObject.Add("sortable", false); } if (field.ShowType == 100) { jObject.Add("title", false); } if (!field.Width.IsNullOrWhiteSpace()) { jObject.Add("width", field.Width.GetNumber()); } jObject.Add("align", field.Align); jArray.Add(jObject); } return(jArray.ToString(Newtonsoft.Json.Formatting.None)); }
/// <summary> /// 得到导出的JSON字符串 /// </summary> /// <param name="ids">逗号分开的多个ID</param> /// <returns></returns> public string GetExportString(string ids) { if (ids.IsNullOrWhiteSpace()) { return("[]"); } Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (string id in ids.Split(',')) { if (!id.IsGuid(out Guid guid)) { continue; } var appLibraryModel = Get(guid); if (null == appLibraryModel) { continue; } jArray.Add(Newtonsoft.Json.Linq.JObject.FromObject(appLibraryModel)); } return(jArray.ToString()); }
public IActionResult Index() { var all = new Business.DbConnection().GetAll(); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var model in all) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", model.Id }, { "Name", model.Name }, { "ConnType", model.ConnType }, { "ConnString", model.ConnString }, { "Note", model.Note }, { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"add('" + model.Id + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" + "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"test('" + model.Id + "');return false;\"><i class=\"fa fa-magic\"></i>测试</a>" } }; jArray.Add(jObject); } ViewData["json"] = jArray.ToString(); ViewData["tabId"] = Request.Querys("tabid"); ViewData["query"] = "appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid"); return(View()); }
public IActionResult Index() { var buttons = new Business.FlowButton().GetAll(); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (var button in buttons) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", button.Id }, { "Title", button.Title }, { "Ico", button.Ico.IsNullOrWhiteSpace() ? "" : button.Ico.IsFontIco() ? "<i class=\"fa " + button.Ico + "\" style=\"font-size:14px;\"></i>" : "<img src=\"" + Url.Content("~" + button.Ico) + "\" alt=\"\" />" }, { "Note", button.Note }, { "Sort", button.Sort }, { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + button.Id + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" } }; jArray.Add(jObject); } ViewData["appId"] = Request.Querys("appid"); ViewData["tabId"] = Request.Querys("tabid"); ViewData["json"] = jArray.ToString(); return(View()); }
/// <summary> /// 处理数据 /// </summary> /// <param name="obj"></param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { OperateResult result = new OperateResult(); // 获取ip地址 string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString(); // 接收操作信息 if (!ReceiveInformationHead( socket, out int customer, out string fileName, out string Factory, out string Group, out string Identify, result, "filename received failed.ip:" + IpAddress )) { return; } string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName); // 操作分流 if (customer == HslCommunicationCode.Hsl_Protocol_File_Download) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 发送文件数据 if (!SendFileAndCheckReceive(socket, fullFileName, fileName, "", "", result, null)) { LogNet?.WriteError($"{StringResources.FileDownloadFailed}:{relativeName} ip:{IpAddress}"); return; } else { LogNet?.WriteInfo(StringResources.FileDownloadSuccess + ":" + relativeName); } socket?.Close(); } else if (customer == HslCommunicationCode.Hsl_Protocol_File_Upload) { string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName(); string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 上传文件 CheckFolderAndCreate(); try { FileInfo info = new FileInfo(fullFileName); if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } } catch (Exception ex) { LogNet?.WriteException("创建文件夹失败:" + fullFileName, ex); socket?.Close(); return; } if (ReceiveFileFromSocketAndMoveFile( socket, // 网络套接字 tempFileName, // 临时保存文件路径 fullFileName, // 最终保存文件路径 out string FileName, // 文件名称,从客户端上传到服务器时,为上传人 out long FileSize, out string FileTag, out string FileUpload, result )) { socket?.Close(); LogNet?.WriteInfo(StringResources.FileUploadSuccess + ":" + relativeName); } else { LogNet?.WriteInfo(StringResources.FileUploadFailed + ":" + relativeName); } } else if (customer == HslCommunicationCode.Hsl_Protocol_File_Delete) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); bool deleteResult = DeleteFileByName(fullFileName); // 回发消息 if (SendStringAndCheckReceive( socket, // 网络套接字 deleteResult ? 1 : 0, // 是否移动成功 deleteResult ? "成功" : "失败", // 字符串数据 result, // 结果数据对象 null, // 不进行报告 "回发删除结果错误") // 发送错误时的数据 ) { socket?.Close(); } if (deleteResult) { LogNet?.WriteInfo(StringResources.FileDeleteSuccess + ":" + fullFileName); } } else if (customer == HslCommunicationCode.Hsl_Protocol_File_Directory_Files) { List <GroupFileItem> fileNames = new List <GroupFileItem>(); foreach (var m in GetDirectoryFiles(Factory, Group, Identify)) { FileInfo fileInfo = new FileInfo(m); fileNames.Add(new GroupFileItem() { FileName = fileInfo.Name, FileSize = fileInfo.Length, }); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray()); if (SendStringAndCheckReceive( socket, HslCommunicationCode.Hsl_Protocol_File_Directory_Files, jArray.ToString(), result, null, "发送文件列表回客户端失败")) { socket?.Close(); } } else if (customer == HslCommunicationCode.Hsl_Protocol_File_Directories) { List <string> folders = new List <string>(); foreach (var m in GetDirectories(Factory, Group, Identify)) { DirectoryInfo directory = new DirectoryInfo(m); folders.Add(directory.Name); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray()); if (SendStringAndCheckReceive( socket, HslCommunicationCode.Hsl_Protocol_File_Directory_Files, jArray.ToString(), result, null, "发送文件夹列表回客户端失败")) { socket?.Close(); } } else { socket?.Close(); } }
/// <summary> /// 当接收到了新的请求的时候执行的操作 /// </summary> /// <param name="socket">异步对象</param> /// <param name="endPoint">终结点</param> protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint) { OperateResult result = new OperateResult( ); // 获取ip地址 string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( ); // 接收操作信息 if (!ReceiveInformationHead( socket, out int customer, out string fileName, out string Factory, out string Group, out string Identify).IsSuccess) { return; } string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName); if (customer == HslProtocol.ProtocolFileDownload) { // 先获取文件的真实名称 string guidName = TransformFactFileName(Factory, Group, Identify, fileName); // 获取文件操作锁 FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(guidName); fileMarkId.EnterReadOperator( ); // 发送文件数据 OperateResult send = SendFileAndCheckReceive(socket, ReturnAbsoluteFileName(Factory, Group, Identify, guidName), fileName, "", "", null); if (!send.IsSuccess) { fileMarkId.LeaveReadOperator( ); LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed} : {send.Message} :{relativeName} ip:{IpAddress}"); return; } else { LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName); } fileMarkId.LeaveReadOperator( ); // 关闭连接 socket?.Close( ); } else if (customer == HslProtocol.ProtocolFileUpload) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 上传文件 CheckFolderAndCreate( ); FileInfo info = new FileInfo(fullFileName); try { if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex); socket?.Close( ); return; } // 接收文件并回发消息 if (ReceiveFileFromSocketAndUpdateGroup( socket, // 网络套接字 fullFileName).IsSuccess) { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName); } else { LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileDelete) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); FileInfo info = new FileInfo(fullFileName); GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName); // 新增删除的任务 DeleteExsistingFile(info.DirectoryName, fileManagment.DeleteFile(info.Name)); // 回发消息 if (SendStringAndCheckReceive( socket, // 网络套接字 1, // 没啥含义 "success" // 没啥含意 ).IsSuccess) { socket?.Close( ); } LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName); } else if (customer == HslProtocol.ProtocolFileDirectoryFiles) { GroupFileContainer fileManagment = GetGroupFromFilePath(ReturnAbsoluteFilePath(Factory, Group, Identify)); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, fileManagment.JsonArrayContent).IsSuccess) { socket?.Close( ); } } else if (customer == HslProtocol.ProtocolFileDirectories) { List <string> folders = new List <string>( ); foreach (var m in GetDirectories(Factory, Group, Identify)) { DirectoryInfo directory = new DirectoryInfo(m); folders.Add(directory.Name); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else { // close not supported client socket?.Close( ); } }
public ActionResult Create() { int contactId = -1; ViewModels.Tasks.CreateTaskViewModel viewModel; Common.Models.Matters.Matter matter; List<ViewModels.Account.UsersViewModel> userList; List<ViewModels.Contacts.ContactViewModel> employeeContactList; Newtonsoft.Json.Linq.JArray taskTemplates; userList = new List<ViewModels.Account.UsersViewModel>(); employeeContactList = new List<ViewModels.Contacts.ContactViewModel>(); dynamic profile = ProfileBase.Create(Membership.GetUser().UserName); if (profile.ContactId != null && !string.IsNullOrEmpty(profile.ContactId)) contactId = int.Parse(profile.ContactId); using (IDbConnection conn = Data.Database.Instance.GetConnection()) { Data.Account.Users.List(conn, false).ForEach(x => { userList.Add(Mapper.Map<ViewModels.Account.UsersViewModel>(x)); }); Data.Contacts.Contact.ListEmployeesOnly(conn, false).ForEach(x => { employeeContactList.Add(Mapper.Map<ViewModels.Contacts.ContactViewModel>(x)); }); viewModel = new ViewModels.Tasks.CreateTaskViewModel(); viewModel.TaskTemplates = new List<ViewModels.Tasks.TaskTemplateViewModel>(); taskTemplates = new Newtonsoft.Json.Linq.JArray(); Data.Tasks.TaskTemplate.List(conn, false).ForEach(x => { viewModel.TaskTemplates.Add(Mapper.Map<ViewModels.Tasks.TaskTemplateViewModel>(x)); Newtonsoft.Json.Linq.JObject template = new Newtonsoft.Json.Linq.JObject(); template.Add(new Newtonsoft.Json.Linq.JProperty("Id", x.Id.Value)); template.Add(new Newtonsoft.Json.Linq.JProperty("TaskTemplateTitle", x.TaskTemplateTitle)); template.Add(new Newtonsoft.Json.Linq.JProperty("Title", x.Title)); template.Add(new Newtonsoft.Json.Linq.JProperty("Description", x.Description)); template.Add(new Newtonsoft.Json.Linq.JProperty("ProjectedStart", DTProp(x.ProjectedStart))); template.Add(new Newtonsoft.Json.Linq.JProperty("DueDate", DTProp(x.DueDate))); template.Add(new Newtonsoft.Json.Linq.JProperty("ProjectedEnd", DTProp(x.ProjectedEnd))); template.Add(new Newtonsoft.Json.Linq.JProperty("ActualEnd", DTProp(x.ActualEnd))); template.Add(new Newtonsoft.Json.Linq.JProperty("Active", x.Active)); taskTemplates.Add(template); }); if (contactId > 0) { viewModel.TaskContact = new ViewModels.Tasks.TaskAssignedContactViewModel() { Contact = new ViewModels.Contacts.ContactViewModel() { Id = contactId } }; } matter = Data.Matters.Matter.Get(Guid.Parse(Request["MatterId"]), conn, false); } ViewBag.Matter = matter; ViewBag.UserList = userList; ViewBag.EmployeeContactList = employeeContactList; ViewBag.TemplateJson = taskTemplates.ToString(); return View(new ViewModels.Tasks.CreateTaskViewModel() { TaskTemplates = viewModel.TaskTemplates, TaskContact = new ViewModels.Tasks.TaskAssignedContactViewModel() { AssignmentType = ViewModels.AssignmentTypeViewModel.Direct, Contact = viewModel.TaskContact.Contact } }); }
/// <summary> /// 当接收到了新的请求的时候执行的操作 /// </summary> /// <param name="socket">异步对象</param> /// <param name="endPoint">终结点</param> protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint) { OperateResult result = new OperateResult( ); // 获取ip地址 string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( ); // 接收操作信息 OperateResult infoResult = ReceiveInformationHead( socket, out int customer, out string fileName, out string Factory, out string Group, out string Identify); if (!infoResult.IsSuccess) { Console.WriteLine(infoResult.ToMessageShowString( )); return; } string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName); // 操作分流 if (customer == HslProtocol.ProtocolFileDownload) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 发送文件数据 OperateResult sendFile = SendFileAndCheckReceive(socket, fullFileName, fileName, "", ""); if (!sendFile.IsSuccess) { LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed}:{relativeName} ip:{IpAddress} reason:{sendFile.Message}"); return; } else { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileUpload) { string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName( ); string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 上传文件 CheckFolderAndCreate( ); // 创建新的文件夹 try { FileInfo info = new FileInfo(fullFileName); if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex); socket?.Close( ); return; } OperateResult receiveFile = ReceiveFileFromSocketAndMoveFile( socket, // 网络套接字 tempFileName, // 临时保存文件路径 fullFileName, // 最终保存文件路径 out string FileName, // 文件名称,从客户端上传到服务器时,为上传人 out long FileSize, out string FileTag, out string FileUpload ); if (receiveFile.IsSuccess) { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName); } else { LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName + " " + StringResources.Language.TextDescription + receiveFile.Message); } } else if (customer == HslProtocol.ProtocolFileDelete) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); bool deleteResult = DeleteFileByName(fullFileName); // 回发消息 if (SendStringAndCheckReceive( socket, // 网络套接字 deleteResult ? 1 : 0, // 是否移动成功 deleteResult ? StringResources.Language.FileDeleteSuccess : StringResources.Language.FileDeleteFailed ).IsSuccess) { socket?.Close( ); } if (deleteResult) { LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileDirectoryFiles) { List <GroupFileItem> fileNames = new List <GroupFileItem>( ); foreach (var m in GetDirectoryFiles(Factory, Group, Identify)) { FileInfo fileInfo = new FileInfo(m); fileNames.Add(new GroupFileItem( ) { FileName = fileInfo.Name, FileSize = fileInfo.Length, }); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else if (customer == HslProtocol.ProtocolFileDirectories) { List <string> folders = new List <string>( ); foreach (var m in GetDirectories(Factory, Group, Identify)) { DirectoryInfo directory = new DirectoryInfo(m); folders.Add(directory.Name); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else { socket?.Close( ); } }
/// <summary> /// 加载树JSON /// </summary> /// <returns></returns> public string Tree1() { string rootId = Request.Querys("root"); string tempitem = Request.Querys("tempitem"); //需要临时添加的项(如表单管理流程管理需要额外添加已删除的项目) string tempitemid = Request.Querys("tempitemid"); //需要临时添加项的ID Business.Dictionary dictionary = new Business.Dictionary(); if (rootId.IsNullOrEmpty()) { rootId = dictionary.GetRootId().ToString(); } Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); string[] rootIds = rootId.Split(','); foreach (string rid in rootIds) { if (!rid.IsGuid(out Guid rootGuid)) { continue; } var rootDict = dictionary.Get(rootGuid); if (null == rootDict) { continue; } var childs = dictionary.GetChilds(rootGuid); Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", rootDict.Id }, { "parentID", rootDict.ParentId }, { "title", rootDict.Status == 1 ? "<span style='color:#999'>" + rootDict.Title + "[作废]</span>" : rootDict.Title }, { "type", childs.Count > 0 ? "0" : "2" }, { "ico", "fa-briefcase" }, { "hasChilds", childs.Count } }; Newtonsoft.Json.Linq.JArray jArray1 = new Newtonsoft.Json.Linq.JArray(); foreach (var child in childs) { Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject { { "id", child.Id }, { "parentID", rootDict.Id }, { "title", child.Status == 1 ? "<span style='color:#999'>" + child.Title + "[作废]</span>" : child.Title }, { "type", "2" }, { "ico", "" }, { "hasChilds", dictionary.HasChilds(child.Id) ? 1 : 0 }, { "childs", new Newtonsoft.Json.Linq.JArray() } }; jArray1.Add(jObject1); } if (!tempitem.IsNullOrWhiteSpace() && !tempitemid.IsNullOrWhiteSpace() && rid.Equals(rootIds[rootIds.Length - 1])) { Newtonsoft.Json.Linq.JObject tempObject = new Newtonsoft.Json.Linq.JObject { { "id", tempitemid }, { "parentID", rootDict.Id }, { "title", tempitem }, { "type", "2" }, { "ico", "" }, { "hasChilds", 0 }, { "childs", new Newtonsoft.Json.Linq.JArray() } }; jArray1.Add(tempObject); } jObject.Add("childs", jArray1); jArray.Add(jObject); } return(jArray.ToString()); }
public ChangeFailureRateModel GetChangeFailureRate(bool getSampleData, TableStorageAuth tableStorageAuth, DevOpsPlatform targetDevOpsPlatform, string organization_owner, string project_repo, string branch, string buildName_workflowName, int numberOfDays, int maxNumberOfItems) { ListUtility <ChangeFailureRateBuild> utility = new ListUtility <ChangeFailureRateBuild>(); ChangeFailureRate changeFailureRate = new ChangeFailureRate(); if (getSampleData == false) { //Gets a list of change failure rate builds from Azure storage AzureTableStorageDA daTableStorage = new AzureTableStorageDA(); Newtonsoft.Json.Linq.JArray list = daTableStorage.GetTableStorageItems(tableStorageAuth, tableStorageAuth.TableChangeFailureRate, daTableStorage.CreateBuildWorkflowPartitionKey(organization_owner, project_repo, buildName_workflowName)); List <ChangeFailureRateBuild> initialBuilds = JsonConvert.DeserializeObject <List <ChangeFailureRateBuild> >(list.ToString()); //Build the date list and then generate the change failure rate metric List <ChangeFailureRateBuild> builds = new List <ChangeFailureRateBuild>(); List <KeyValuePair <DateTime, bool> > dateList = new List <KeyValuePair <DateTime, bool> >(); float maxBuildDuration = 0f; foreach (ChangeFailureRateBuild item in initialBuilds) { if (item.Branch == branch && item.StartTime > DateTime.Now.AddDays(-numberOfDays)) { //Special branch for Azure DevOps to construct the Url to each build if (targetDevOpsPlatform == DevOpsPlatform.AzureDevOps) { item.Url = $"https://dev.azure.com/{organization_owner}/{project_repo}/_build/results?buildId={item.Id}&view=results"; } builds.Add(item); } } //then build the calcuation foreach (ChangeFailureRateBuild item in builds) { KeyValuePair <DateTime, bool> newItem = new KeyValuePair <DateTime, bool>(item.StartTime, item.DeploymentWasSuccessful); dateList.Add(newItem); } //calculate the metric on all of the results float changeFailureRateMetric = changeFailureRate.ProcessChangeFailureRate(dateList, numberOfDays); //Filter the results to return the last n (maxNumberOfItems) List <ChangeFailureRateBuild> uiBuilds = utility.GetLastNItems(builds, maxNumberOfItems); foreach (ChangeFailureRateBuild item in uiBuilds) { if (item.BuildDuration > maxBuildDuration) { maxBuildDuration = item.BuildDuration; } } //We need to do some post processing and loop over the list a couple times to find the max build duration, construct a usable url, and calculate a build duration percentage foreach (ChangeFailureRateBuild item in uiBuilds) { float interiumResult = ((item.BuildDuration / maxBuildDuration) * 100f); item.BuildDurationPercent = Scaling.ScaleNumberToRange(interiumResult, 0, 100, 20, 100); } ChangeFailureRateModel model = new ChangeFailureRateModel { TargetDevOpsPlatform = targetDevOpsPlatform, DeploymentName = buildName_workflowName, ChangeFailureRateBuildList = uiBuilds, ChangeFailureRateMetric = changeFailureRateMetric, ChangeFailureRateMetricDescription = changeFailureRate.GetChangeFailureRateRating(changeFailureRateMetric), NumberOfDays = numberOfDays, MaxNumberOfItems = uiBuilds.Count, TotalItems = builds.Count }; return(model); } else { //Get sample data List <ChangeFailureRateBuild> sampleBuilds = utility.GetLastNItems(GetSampleBuilds(), maxNumberOfItems); ChangeFailureRateModel model = new ChangeFailureRateModel { TargetDevOpsPlatform = targetDevOpsPlatform, DeploymentName = buildName_workflowName, ChangeFailureRateBuildList = sampleBuilds, ChangeFailureRateMetric = 2f / 10f, ChangeFailureRateMetricDescription = changeFailureRate.GetChangeFailureRateRating(2f / 10f), NumberOfDays = numberOfDays, MaxNumberOfItems = sampleBuilds.Count, TotalItems = sampleBuilds.Count }; return(model); } }
public async Task <bool> UpdateChangeFailureRate(TableStorageAuth tableStorageAuth, string organization_owner, string project_repo, string buildName_workflowName, int percentComplete, int numberOfDays) { //Gets a list of change failure rate builds AzureTableStorageDA daTableStorage = new AzureTableStorageDA(); string partitionKey = daTableStorage.CreateBuildWorkflowPartitionKey(organization_owner, project_repo, buildName_workflowName); Newtonsoft.Json.Linq.JArray list = daTableStorage.GetTableStorageItems(tableStorageAuth, tableStorageAuth.TableChangeFailureRate, partitionKey); List <ChangeFailureRateBuild> initialBuilds = JsonConvert.DeserializeObject <List <ChangeFailureRateBuild> >(list.ToString()); //Get the list of items we are going to process, within the date/day range List <ChangeFailureRateBuild> builds = new List <ChangeFailureRateBuild>(); foreach (ChangeFailureRateBuild item in initialBuilds) { if (item.StartTime > DateTime.Now.AddDays(-numberOfDays)) { builds.Add(item); } } //Using the percent, convert it to a fraction FractionConverter converter = new FractionConverter(); FractionModel fracationModel = converter.ConvertToFraction(percentComplete); int numerator = fracationModel.Numerator; int denominator = fracationModel.Denominator; //Get builds for positive (builds we will set DeploymentWasSuccessful=true) and negative (builds we will set to DeploymentWasSuccessful=false) Console.WriteLine($"numerator {numerator} / denominator {denominator}"); //TODO: remember how this (x, numerator) syntax works so it can be documented. oooof. List <ChangeFailureRateBuild> postiveBuilds = builds.Where((x, numerator) => numerator % denominator != 0).ToList(); List <ChangeFailureRateBuild> negativeBuilds = builds.Where((x, numerator) => numerator % denominator == 0).ToList(); //Make the updates TableStorageCommonDA tableChangeFailureRateDA = new TableStorageCommonDA(tableStorageAuth, tableStorageAuth.TableChangeFailureRate); foreach (ChangeFailureRateBuild item in postiveBuilds) { item.DeploymentWasSuccessful = true; await daTableStorage.UpdateChangeFailureRate(tableChangeFailureRateDA, item, partitionKey, true); } foreach (ChangeFailureRateBuild item in negativeBuilds) { item.DeploymentWasSuccessful = false; await daTableStorage.UpdateChangeFailureRate(tableChangeFailureRateDA, item, partitionKey, true); } return(true); }
public string Query() { string Title = Request.Forms("Title"); string Address = Request.Forms("Address"); string typeid = Request.Forms("typeid"); string sidx = Request.Forms("sidx"); string sord = Request.Forms("sord"); int size = Tools.GetPageSize(); int number = Tools.GetPageNumber(); string order = (sidx.IsNullOrEmpty() ? "Type,Title" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord); Business.Dictionary dictionary = new Business.Dictionary(); if (typeid.IsGuid(out Guid typeId)) { var childsId = dictionary.GetAllChildsId(typeId); typeid = childsId.JoinSqlIn(); } var appLibraries = new Business.AppLibrary().GetPagerList(out int count, size, number, Title, Address, typeid, order); Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray(); foreach (System.Data.DataRow dr in appLibraries.Rows) { Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject { { "id", dr["Id"].ToString() }, { "Title", dr["Title"].ToString() }, { "Address", dr["Address"].ToString() }, { "TypeTitle", dictionary.GetTitle(dr["Type"].ToString().ToGuid()) }, { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + dr["Id"].ToString() + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" + "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"editButton('" + dr["Id"].ToString() + "');return false;\"><i class=\"fa fa-square-o\"></i>按钮</a>" } }; jArray.Add(jObject); } return("{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}"); }