using Newtonsoft.Json.Linq; using System; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Resources; using System.Drawing; using Newtonsoft.Json; using Gs.DevApp.Entity; using System.Windows.Forms; using static System.Windows.Forms.Control; using DevExpress.XtraEditors; using DevExpress.XtraTab; using System.Text.RegularExpressions; using System.Collections.Generic; using Gs.DevApp.UserControl; using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid; using DevExpress.XtraGrid.Views.Grid; using System.Configuration; using DevExpress.XtraGrid.Views.Grid.ViewInfo; using DevExpress.XtraTreeList.Nodes; using DevExpress.XtraTreeList; using System.Net.Http; using System.Threading.Tasks; using DevExpress.Data.Helpers; using DevExpress.Utils.About; using DevExpress.Office.Model; namespace Gs.DevApp.ToolBox { /// /// 通用类 /// public class UtilityHelper { private static string WebApiUrl = ConfigurationManager.AppSettings["WebApiUrl"].ToString(); public static async Task UploadFileAsync(string filePath) { using (var httpClient = new HttpClient()) using (var form = new MultipartFormDataContent()) { httpClient.DefaultRequestHeaders.Add("token", ToolBox.UtilityHelper.GetBasicAuthTicket()); using (var fs = File.OpenRead(filePath)) using (var streamContent = new StreamContent(fs)) { form.Add(streamContent, "file", Path.GetFileName(filePath)); var response = await httpClient.PostAsync(WebApiUrl + "Upload/UploadFile", form); string responseString = await response.Content.ReadAsStringAsync(); return responseString; } } } /// /// httpPost访问服务 /// /// 服务地址 /// 方法名称 /// 参数 /// public static string HttpPost(string url, string meth, string param) { if (string.IsNullOrEmpty(url)) url = WebApiUrl; url += meth; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("token", GetBasicAuthTicket()); request.Accept = "*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; StreamWriter requestStream = null; WebResponse response = null; string responseStr = null; try { requestStream = new StreamWriter(request.GetRequestStream()); requestStream.Write(param); requestStream.Close(); response = request.GetResponse(); if (response != null) { StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); responseStr = reader.ReadToEnd(); //File.WriteAllText(Server.MapPath("~/") + @"\test.txt", responseStr); reader.Close(); } } catch (Exception ex) { LogHelper.Debug(url, param + ":" + ex.Message); throw ex; } finally { request = null; requestStream = null; response = null; } return responseStr; } /// /// 默认页大小 /// /// public static int GetPageSize() { return int.Parse(System.Configuration.ConfigurationSettings.AppSettings.Get("PageSize").ToString()); } /// /// 根据图片名读取资源文件,不带后缀名 /// /// /// 1为大图 /// public static Image GetImgFromResource(string imageName, int lay) { Assembly assembly = Assembly.GetExecutingAssembly(); ResourceManager resourceManager = new ResourceManager("Gs.DevApp.Properties.Resources", assembly); try { Image image = resourceManager.GetObject(imageName) as Image; if (image != null) { return image; } } catch (Exception ex) { } Image image2 = resourceManager.GetObject(lay == 1 ? "chartsshowlegend_32x32" : "linktoprevious_16x16") as Image; return image2; } /// /// 初始化一个表 /// /// /// public static void SetDefaultTable(GridControl gc, GridView gv) { DataTable dt = new DataTable(); foreach (GridColumn col in gv.Columns) { dt.Columns.Add(col.FieldName, typeof(string)); } gc.BindingContext = new BindingContext(); gc.DataSource = dt; gc.ForceInitialize(); } /// /// 生成访问服务的token /// /// public static string GetBasicAuthTicket() { string userGuid = string.IsNullOrEmpty(LoginInfoModel.CurrentUser.LoginUserGuid) ? Guid.NewGuid().ToString() : LoginInfoModel.CurrentUser.LoginUserGuid; string orgGuid = string.IsNullOrEmpty(LoginInfoModel.CurrentUser.LoginOrgGuid) ? Guid.NewGuid().ToString() : LoginInfoModel.CurrentUser.LoginOrgGuid; string token = (userGuid + "~" + orgGuid); return token; } /// /// 服务返回的json转为ReturnModel-->包含TablePage分页, /// /// /// public static ReturnModel ReturnToTablePage(string strReturn) { ReturnModel rto = new ReturnModel(); JObject json = JObject.Parse(strReturn); rto.rtnCode = int.Parse(json["rtnCode"].ToString()); rto.rtnMsg = json["rtnMsg"].ToString(); rto.rtnData = new PageListModel(); rto.rtnData.pages = int.Parse(json["rtnData"]["pages"].ToString()); rto.rtnData.total = int.Parse(json["rtnData"]["total"].ToString()); rto.rtnData.everyPageSize = int.Parse(json["rtnData"]["everyPageSize"].ToString()); JArray array = new JArray(); var d = json["rtnData"]["list"]; foreach (var a in d) { array.Add(a); } DataTable dt = JsonConvert.DeserializeObject(array.ToString()); rto.rtnData.list = dt; return rto; } /// /// 服务返回的json返回ReturnModel, /// /// /// public static ReturnModel ReturnToDynamic(string strReturn) { ReturnModel rto = new ReturnModel(); JObject json = JObject.Parse(strReturn); rto.rtnCode = int.Parse(json["rtnCode"].ToString()); rto.rtnMsg = json["rtnMsg"].ToString(); rto.rtnData = json["rtnData"]; return rto; } /// /// 服务返回的json串返回ReturnModel-->仅仅有list,不分页, /// /// /// public static ReturnModel ReturnToList(string strReturn) { ReturnModel rto = new ReturnModel(); JObject json = JObject.Parse(strReturn); rto.rtnCode = int.Parse(json["rtnCode"].ToString()); rto.rtnMsg = json["rtnMsg"].ToString(); rto.rtnData = new DataTable(); JArray array = new JArray(); var d = json["rtnData"]; foreach (var a in d) { array.Add(a); } DataTable dt = JsonConvert.DeserializeObject(array.ToString()); rto.rtnData = dt; return rto; } /// /// 根据对象批量设置文本框的值 /// /// controls:为groupBox1.Controls/panel1.Controls /// 对像 /// 是否可编辑 /// 关联的grid public static void SetValueByObj(ControlCollection controls, dynamic dynamicObject, Boolean isEdt, List gridViews = null) { isEdt = !isEdt; if (gridViews != null) { foreach (DevExpress.XtraGrid.Views.Grid.GridView gv in gridViews) { gv.OptionsBehavior.Editable = !isEdt; } } foreach (JProperty property in dynamicObject.Properties()) { string strName = property.Name; string strVal = property.Value.ToString(); try { string _dddddd = "txt_" + strName; Control[] cols = controls.Find(_dddddd, true); if (cols.Length > 0) { Control colType = cols[0]; if (colType is LookUpEdit) { LookUpEdit txt = colType as LookUpEdit; if (txt != null) { txt.EditValue = strVal; } txt.ReadOnly = isEdt; continue; } if (colType is ImageComboBoxEdit) { ImageComboBoxEdit txt = colType as ImageComboBoxEdit; for (int i = 0; i < txt.Properties.Items.Count; i++) { if (txt.Properties.Items[i].Description == strVal) { txt.ReadOnly = isEdt; txt.SelectedIndex = i; continue; }; } continue; } if (colType is ComboBoxEdit) { ComboBoxEdit txt = colType as ComboBoxEdit; if (txt.Properties.TextEditStyle == DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor) txt.SelectedIndex = int.Parse(strVal); else txt.Text = strVal; txt.ReadOnly = isEdt; continue; } //下拉 if (colType is ComboBoxEdit) { ComboBoxEdit txt = colType as ComboBoxEdit; if (txt.Properties.TextEditStyle == DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor) txt.SelectedIndex = int.Parse(strVal); else txt.Text = strVal; txt.ReadOnly = isEdt; continue; } //自定义下拉 if (colType is UcComBox) { UcComBox txt = colType as UcComBox; txt.Val = strVal; txt.Enabled = !isEdt; continue; } //文本 if (colType is TextEdit) { TextEdit txt = colType as TextEdit; if (txt != null) txt.Text = strVal; txt.ReadOnly = isEdt; continue; } //数字卡 if (colType is NumericUpDown) { NumericUpDown txt = colType as NumericUpDown; if (txt != null) txt.Text = strVal; txt.ReadOnly = isEdt; continue; } //单选 if (colType is CheckEdit) { CheckEdit txt = colType as CheckEdit; if (txt != null) { switch (strVal) { case "True": txt.Checked = true; break; case "1": txt.Checked = true; break; case "False": txt.Checked = false; break; default: txt.Checked = false; break; } } txt.ReadOnly = isEdt; continue; } //单选 if (colType is CheckBox) { CheckBox txt = colType as CheckBox; if (txt != null) txt.Checked = bool.Parse(strVal); txt.Enabled = !isEdt; continue; } //时间 if (colType is DateTimePicker) { DateTimePicker txt = colType as DateTimePicker; txt.Text = strVal.ToString(); txt.Enabled = !isEdt; continue; } //Label if (colType is Label) { Label txt = colType as Label; if (_dddddd == "txt_checkStatus") { if (strVal.ToString() == "True") txt.Text = "已审核"; if (strVal.ToString() == "False") txt.Text = "未审核"; } else txt.Text = strVal.ToString(); continue; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// /// 清空容器里面的控件 /// /// controls:为groupBox1.Controls/panel1.Controls /// 是否可编辑 /// 关联的grid public static void CleanValueByControl(ControlCollection controls, Boolean isEdt, List gridViews = null) { isEdt = !isEdt; if (gridViews != null) { foreach (DevExpress.XtraGrid.Views.Grid.GridView gv in gridViews) { gv.OptionsBehavior.Editable = !isEdt; } } foreach (Control ctrl in controls) { //多行文本 if (ctrl is MemoEdit) { MemoEdit txt = ctrl as MemoEdit; txt.Text = ""; txt.ReadOnly = isEdt; continue; } //下拉 if (ctrl is ComboBoxEdit) { ComboBoxEdit txt = ctrl as ComboBoxEdit; if (txt.Properties.TextEditStyle == DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor) txt.SelectedIndex = 0; else txt.Text = ""; txt.ReadOnly = isEdt; continue; } //自定义的下拉 if (ctrl is UcComBox) { UcComBox txt = ctrl as UcComBox; txt.Val = "0"; txt.Enabled = !isEdt; continue; } //文本 if (ctrl is TextEdit) { TextEdit txt = ctrl as TextEdit; txt.Text = ""; txt.ReadOnly = isEdt; continue; } //时间 if (ctrl is DateTimePicker) { DateTimePicker txt = ctrl as DateTimePicker; txt.Enabled = !isEdt; continue; } //单选 if (ctrl is CheckBox) { CheckBox txt = ctrl as CheckBox; txt.Checked = false; txt.Enabled = !isEdt; continue; } } } /// /// 禁用或启用容器里面的控件 /// /// controls:为groupBox1.Controls/panel1.Controls /// /// public static void ChangeEnableByControl(ControlCollection controls, Boolean isEdt, List gridViews = null) { isEdt = !isEdt; if (gridViews != null) { foreach (DevExpress.XtraGrid.Views.Grid.GridView gv in gridViews) { gv.OptionsBehavior.Editable = !isEdt; } } foreach (Control ctrl in controls) { //文本 if (ctrl is TextEdit) { TextEdit txt = ctrl as TextEdit; txt.ReadOnly = isEdt; continue; } //数字卡 if (ctrl is NumericUpDown) { NumericUpDown txt = ctrl as NumericUpDown; txt.ReadOnly = isEdt; continue; } //下拉 if (ctrl is UcComBox) { UcComBox txt = ctrl as UcComBox; txt.Val = "0"; txt.Enabled = !isEdt; continue; } //日期 if (ctrl is DateTimePicker) { ctrl.Enabled = !isEdt; continue; } //单选 if (ctrl is CheckBox) { ctrl.Enabled = !isEdt; continue; } } } /// ///切换选项卡 /// /// 选项卡容器 /// 从0开始,如果是999,则全部可用 public static void JumpToTab(XtraTabControl tabControl, int idx) { if (idx == 999) { for (int i = 0; i < tabControl.TabPages.Count; i++) { tabControl.TabPages[i].PageEnabled = true; } tabControl.SelectedTabPageIndex = tabControl.TabPages.Count - 1; return; } for (int i = 0; i < tabControl.TabPages.Count; i++) { tabControl.TabPages[i].PageEnabled = false; } tabControl.TabPages[idx].PageEnabled = true; tabControl.SelectedTabPageIndex = idx; } /// /// TreeView联动选择 /// /// public static void TreeViewCheck(TreeViewEventArgs e) { try { if (e.Node.Nodes.Count > 0) { foreach (TreeNode tn in e.Node.Nodes) { tn.Checked = e.Node.Checked; foreach (TreeNode x in tn.Nodes) { x.Checked = e.Node.Checked; foreach (TreeNode y in x.Nodes) { y.Checked = e.Node.Checked; } } } } if (e.Node.Checked == true && e.Node.Parent != null && e.Node.Parent.Nodes.Count > 0) { TreeNode currentNode = e.Node; while (currentNode != null) { currentNode.Checked = e.Node.Checked; currentNode = currentNode.Parent; } } } catch (Exception ex) { ToolBox.MsgHelper.ShowError(ex.Message); } } /// /// 转驼峰命名 /// /// /// public static string ToCamelCase(string strItem) { //如果包含小写,但不包含下划线 bool hasLowercase = Regex.IsMatch(strItem, @"[a-z]"); if (hasLowercase && !strItem.Contains("_")) { char[] chars = strItem.ToCharArray(); chars[0] = char.ToLower(chars[0]); return new string(chars); } string[] strItems = strItem.ToLower().Split('_'); string strItemTarget = strItems[0]; for (int j = 1; j < strItems.Length; j++) { string temp = strItems[j].ToString(); string temp1 = temp[0].ToString().ToUpper(); string temp2 = ""; temp2 = temp1 + temp.Remove(0, 1); strItemTarget += temp2; } return strItemTarget; } /// /// 读取grid的当前行 /// /// /// 编辑框中的主键名 /// 编辑框中的文本框名 /// /// /// public static (string, string) GetCurrentRow(XtraTabControl xtraTabControl1 , System.Windows.Forms.Label lbGuid , DevExpress.XtraEditors.TextEdit txtName , DevExpress.XtraGrid.Views.Grid.GridView gridView1 , int SelectedTabPageIndex = 1) { string _strGuid = ""; string _strName = ""; if (xtraTabControl1.SelectedTabPageIndex == SelectedTabPageIndex && lbGuid.Text.Length > 10) { _strGuid = lbGuid.Text.Trim(); _strName = txtName.Text.Trim(); } else { DataRow dr = gridView1.GetFocusedDataRow(); if (dr == null || string.IsNullOrEmpty(dr["guid"].ToString())) { } else { _strGuid = dr["guid"].ToString(); _strName = dr[2].ToString(); } } return (_strGuid, _strName); } /// /// 读取TreeView的当前行 /// /// /// /// /// /// /// public static (string, string) GetCurrentRow(XtraTabControl xtraTabControl1 , System.Windows.Forms.Label lbGuid , DevExpress.XtraEditors.TextEdit txtName , System.Windows.Forms.TreeView tlMenu , int SelectedTabPageIndex = 1) { string _strGuid = ""; string _strName = ""; if (xtraTabControl1.SelectedTabPageIndex == SelectedTabPageIndex && lbGuid.Text.Length > 10) { _strGuid = lbGuid.Text.Trim(); _strName = txtName.Text.Trim(); } else { TreeNode clickedNode = tlMenu.SelectedNode; if (clickedNode != null) { _strGuid = clickedNode.Name.ToString(); _strName = clickedNode.Text.Trim(); } } return (_strGuid, _strName); } /// /// 读取TreeList的当前行 /// /// /// /// /// /// /// public static (string, string) GetCurrentRow(XtraTabControl xtraTabControl1 , System.Windows.Forms.Label lbGuid , DevExpress.XtraEditors.TextEdit txtName , DevExpress.XtraTreeList.TreeList tlMenu , int SelectedTabPageIndex = 1) { string _strGuid = ""; string _strName = ""; if (xtraTabControl1.SelectedTabPageIndex == SelectedTabPageIndex && lbGuid.Text.Length > 10) { _strGuid = lbGuid.Text.Trim(); _strName = txtName.Text.Trim(); } else { _strGuid = tlMenu.FocusedNode.GetValue("guid").ToString(); _strName = tlMenu.FocusedNode.GetValue(0).ToString(); } return (_strGuid, _strName); } /// /// 读取GridView双击的主键 /// /// /// /// /// public static string GetCurrentDoubleRow(DevExpress.XtraGrid.Views.Grid.GridView gridView1 , MouseEventArgs e , string colName) { GridHitInfo info = gridView1.CalcHitInfo(e.Location); if (info.InRow) { GridView view = info.View as GridView; if (view != null) { DataRow row = view.GetDataRow(info.RowHandle); if (row != null) { string rowGuid = (row[colName].ToString()); return rowGuid; } } } return ""; } /// /// 读取GridView双击的主键 /// /// /// /// /// public static string GetCurrentDoubleRow(DevExpress.XtraTreeList.TreeList tlMenu , MouseEventArgs e , string colName) { TreeListHitInfo info = tlMenu.CalcHitInfo(e.Location); if (info.Node != null) { TreeListNode clickedNode = tlMenu.FocusedNode; if (clickedNode.FirstNode == null) { string rowGuid = clickedNode.GetValue(colName).ToString(); return rowGuid; } } return ""; } } /// /// 下拉框条目类 /// public class CboItemEntity { public CboItemEntity() { } public CboItemEntity(string val, string text) { this.Text = text; this.Value = val; } private object _text = 0; private object _Value = ""; /// /// 显示值 /// public object Text { get { return this._text; } set { this._text = value; } } /// /// 对象值 /// public object Value { get { return this._Value; } set { this._Value = value; } } public override string ToString() { return this.Text.ToString(); } } /// /// 查询框 /// public class FilterEntity { /// /// /// /// 字段名 /// 字段名备注 /// 操作符 /// 操作符备注 /// public FilterEntity(string id, string idDec, string oper, string operDec, string val) { this.fileId = id; this.fileIdDec = idDec; this.fileOper = oper; this.fileOperDec = operDec; this.fileValue = val; } public string fileId { get; set; } public string fileIdDec { get; set; } public string fileOper { get; set; } public string fileOperDec { get; set; } public string fileValue { get; set; } } }