Dispose、Close、=null三者之间的区别

 
上午想做个简单的单件设计模式(Singleton)的小例子,结果出现了一些意想不到的问题。我的本意是建立两个窗体类Form1和Form2,在Form2上放置一个名为Button1的按钮,单击Button1会调出Form1的窗口事例,并且保证再单击Button1的时候,不会再弹出第二个Form1实例,除非关掉Form1实例并重新单击Button1,总之,保证只能弹出一个Form1实例(当然不是用模态方式啦)。代码如下所示:
 
Form1类
       public class Form1
       {    
              private static Form1 frm;
              private Form1()//这个构造函数只允许类内调用,所以是私有的
              {
                     InitializeComponent();
              }
 
              public static Form1 CreateForm1()//该函数可带参数,自己想想如何实现
              {
                     if(frm == null)
                     {
                            frm = new Form1();
                            return frm;
                     }
                     else
                     {
                            return frm;
                     }
              }
       }
 
Form2类
              public class Form2
       {    
              ..... 
              private void button1_Click(object sender, System.EventArgs e)
              {
                     Form1 frm1 = Form1.CreateForm1();
                     frm1.Show();
              }
              .....
       }
于是问题出现了:我单击Form2窗体上的一个名为button1按钮要弹出Form1的窗口(函数如上),第一次可以弹出来,并且可以保证再单击button1时,不再弹出Form1的窗口,但是关闭Form1窗口实例后,再次单击button1按钮则出错,解释为无法访问名为“Form1”的已处置对象。这是什么原因?
经过细致的观察和向高手询问,终于搞清楚了问题的真相。这就是Dispose和null之间的区别。Dispose和Close是相同的,据说是因为有些类有Open的方法,所以为了对应才搞出了一个Close方法。Dispose()方法实际上是销毁了对象的实例,但是该对象变量仍然指向这块被销毁的内存地址上!而只要有所指向,它就绝不等于null!而若原来夫frm = new Form1();然后又frm = null;这意味着frm不再指向new出来的对象,他们之间的关系被“切断”了,frm成了一个没有指向的变量,但同时new出来的那个对象也占据着一块内存,它并没有被干掉!后来我又发现,窗体在执行Close()方法后会激发Closing事件,而使用dispose()方法则不会激发该事件。在singleton模式中,单例窗体的Closing事件里面,加入了“frm=null;”这么一句话,所以不要用dispose()关闭单例窗体,而要用Close()方法关闭。引申出来,所有拥有Close()方法的类,最好都用Close()方法关闭,而不要用Dispose()方法。
所以,上面的例子中,把frm1关掉后,它new出来的那个对象所占用的地址被dispose掉了,但是变量frm1仍然指向这块被dispose掉的地址!所以它也就不等于null!所以当再次单击Button1的时候,直接进入了else部分,导致了错误。那怎么解决呢?这么办,在Form1的Closed事件中将frm1设置成null,就可以了。因为关闭窗体,执行dispose的时候,窗体内的其他代码并不停止,直到执行完毕,所以,可以将frm1设置成null,完全没有问题。
这里还有另外一个问题。假如一个对象(自定义的类的实例)没有dispose掉,就把它设置成null,那这块内存怎么办呢?垃圾回收机制会自动收拾它的。但是垃圾回收机制,不能保证何时去回收它,所以你也不知道它到底啥时候能回收掉,这样可能影响系统的效率。解决方法是,使该类继承IDisposable接口,然后实现他的Dispose()方法。函数内写GC.SuppressFinalize(this);这样,如果手动调用dispose()方法,GC就不会通过析构函数再次销毁对象了。尤其当这个对象作为局部变量的时候,这样做是很有必要的。可以将dispose()写入finally{}语句中,更好的方法是使用using关键字把代码装入{}中。例如:
Using(Class1 cls1 = new Class())
{。。。。}
Using里的参数必须是实现了dispose方法的对象。当程序运行出{}时,自动销毁cls1(但是cls1!=null,这个已经反复说过多次了)。真正是实现的时候,可能还要考虑到多线程等诸多问题。
using Autodesk.Revit.DB; using Autodesk.Revit.UI; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.Integration; using Application = Autodesk.Revit.ApplicationServices.Application; namespace 水闸闸孔总净宽计算 { public partial class 计算原理与简图 : System.Windows.Forms.Form { ExternalCommandData dataform; string msgform; ElementSet eleform; UIApplication uiapp = null; UIDocument uidoc = null; Document doc = null; Application app = null; public 计算原理与简图(ExternalCommandData data, ref string msg, ElementSet ele) { InitializeComponent(); dataform = data; msgform = msg; eleform = ele; uiapp = data.Application; uidoc = uiapp.ActiveUIDocument; doc = uidoc.Document; } private 水闸计算 水闸计算; public 计算原理与简图(水闸计算 mainFormRef) { InitializeComponent(); this.水闸计算 = mainFormRef; // 保存引用 } PreviewControl previewControl = null; string pathname = typeof(定制按钮).Assembly.Location; string filename = ""; private void 计算原理与简图_Load(object sender, EventArgs e) { int wz = pathname.LastIndexOf(@"\"); string pathsjtxt = pathname.Substring(0, wz + 1);//pathsjtxt是数据表路径的意思 filename = pathsjtxt + "水闸计算样板.rvt"; Document newDoc = app.OpenDocumentFile(filename); View3D view3D = null; //找到当前文件的3D视图 FilteredElementCollector ViewCollector = new FilteredElementCollector(newDoc).OfClass(typeof(View3D)); foreach (View3D view in ViewCollector) { if ("{3D}".Equals(view.Name) || "三维".Equals(view.Name)) { view3D = view; break; } } previewControl = elementHost1.Child as PreviewControl; if (previewControl != null) { previewControl.Dispose(); } elementHost1.Child = new PreviewControl(newDoc, view3D.Id); previewControl = elementHost1.Child as PreviewControl; } } }运行时,Document newDoc = app.OpenDocumentFile(filename);这行代码显示为将对象设置引用到对象的实例
07-28
public void yz_Click(object sender, EventArgs e) { Session theSession = Session.GetSession(); Part displayPart = theSession.Parts.Display; if (displayPart != null && displayPart.ComponentAssembly != null) { TraverseAssemblyTopLevelOnly(displayPart.ComponentAssembly.RootComponent, theSession); } } private static void TraverseAssemblyTopLevelOnly(Component rootComponent, Session theSession) { foreach (Component child in rootComponent.GetChildren()) { if (child.IsSuppressed) { theSession.ListingWindow.WriteLine($"发现抑制组件: {child.DisplayName}"); // 获取抑制组件的原型 Part prototypePart = GetSuppressedComponentPrototypeAlternative(child, theSession); if (prototypePart != null) { theSession.ListingWindow.WriteLine($"成功获取原型: {prototypePart.FullPath}"); // 在这里对原型部件进行操作 // 操作完成后关闭部件,以便下次可以重新打开 ClosePartIfNotDisplay(prototypePart, theSession); } // 注意:这里不递归遍历抑制组件的子组件 } else { // 只有非抑制组件才递归遍历其子组件 if (child.GetChildren().Length > 0) { TraverseAssemblyTopLevelOnly(child, theSession); } } } } private static Part GetSuppressedComponentPrototypeAlternative(Component suppressedComp, Session theSession) { PartLoadStatus loadStatus = null; try { Part displayPart = theSession.Parts.Display; string displayPartPath = Path.GetDirectoryName(displayPart.FullPath); string suppressedCompName = suppressedComp.DisplayName; string presumedPartPath = Path.Combine(displayPartPath, suppressedCompName + ".prt"); // 检查部件是否已经打开 Part existingPart = FindPartByFullPath(presumedPartPath, theSession); if (existingPart != null) { theSession.ListingWindow.WriteLine($"部件已打开: {existingPart.FullPath}"); return existingPart; } // 使用OpenBaseDisplay作为替代方案,并传入loadStatus作为out参数 Part prototypePart = (Part)theSession.Parts.OpenBaseDisplay(presumedPartPath, out loadStatus); if (prototypePart != null) { theSession.ListingWindow.WriteLine($"使用OpenBaseDisplay成功打开部件: {prototypePart.FullPath}"); } return prototypePart; } catch (Exception ex) { theSession.ListingWindow.WriteLine($"替代方案也失败: {ex.Message}"); return null; } finally { // 清理PartLoadStatus资源 if (loadStatus != null) { loadStatus.Dispose(); } } } private static Part FindPartByFullPath(string fullPath, Session theSession) { try { // 遍历所有打开的部件,查找匹配的路径 PartCollection parts = theSession.Parts; foreach (Part part in parts) { if (part.FullPath.Equals(fullPath, StringComparison.OrdinalIgnoreCase)) { return part; } } return null; } catch (Exception ex) { theSession.ListingWindow.WriteLine($"查找部件时出错: {ex.Message}"); return null; } } private static void ClosePartIfNotDisplay(Part part, Session theSession) { try { // 不要关闭显示部件 if (part != null && part != theSession.Parts.Display && part != theSession.Parts.Work) { // 检查部件是否还有引用 if (CanClosePart(part)) { part.Close(BasePart.CloseWholeTree.False, BasePart.CloseModified.CloseModified, null); theSession.ListingWindow.WriteLine($"已关闭部件: {part.FullPath}"); } else { theSession.ListingWindow.WriteLine($"部件 {part.FullPath} 有其他引用,无法关闭"); } } } catch (Exception ex) { theSession.ListingWindow.WriteLine($"关闭部件时出错: {ex.Message}"); } } private static bool CanClosePart(Part part) { try { // 简单检查:如果部件不是显示部件或工作部件,并且没有未保存的修改,则可以关闭 // 您可以根据需要调整此逻辑 return !part.IsModified; } catch { return false; } } 以上代码yz_Click函数执行一次后,可以显示被抑制的文件,但是待抑制的文件关闭后,再次执行yz_Click函数没起作用,然后再次执行yz_Click就可以了。也就是说除了第一次执行yz_Click函数正常外,以后再用必须执行2次才能起作用,请改正
最新发布
09-30
请帮我分析一下下面代码的作用using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Data; using System.Data.SqlClient; using System.Web.Configuration; public class cGlobal { private static string _sessionName = "loginUser"; private static string _cookieName = "user"; public cGlobal() { // Something to do. } public static void setLogout() { HttpContext context = HttpContext.Current; context.Session.Clear(); context.Session.Abandon(); HttpCookie cookie = new HttpCookie(_cookieName); context.Response.Cookies.Add(cookie); } public class loginUserInfo { public enum userType { sysUser = 0, deptHeader } public string id { get; set; } public userType type { get; set; } public bool isADVerify { get; set; } public bool isDeptHead { get { return type == userType.deptHeader; } } public bool isSysUser { get { return type == userType.sysUser; } } public bool isValid { get; set; } public void setEmpty() { id = string.Empty; type = userType.sysUser; isValid = false; isADVerify = false; } public loginUserInfo() { setEmpty(); } } public static loginUserInfo loginUser { get { HttpContext context = HttpContext.Current; loginUserInfo userInfo = new loginUserInfo(); if (context.Session[_sessionName] == null) { HttpCookie cookie = context.Request.Cookies[_cookieName]; DateTime expires = DateTime.Now.AddDays(-1); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; object tmpResult = null; try { if (cookie == null || cookie.Values["value"] == null || cookie.Values["expires"] == null) { throw new Exception("cookie not exist."); } if (!DateTime.TryParse(cookie.Values["expires"], out expires) || expires < DateTime.Now) { throw new Exception("expired."); } userInfo.id = cookie.Values["value"]; if (userInfo.id == string.Empty) { throw new Exception("no value."); } sqlConn.Open(); sqlCmd.CommandText = @" SELECT [IsADVerify],[PasswordIsInit] FROM [SystemUsers] WHERE [UserId]=@userId"; sqlCmd.Parameters.AddWithValue("@userId", userInfo.id); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (sqlDR.Read()) { userInfo.type = cGlobal.loginUserInfo.userType.sysUser; userInfo.isADVerify = (bool)sqlDR["IsADVerify"]; } else { sqlDR.Close(); sqlCmd.CommandText = @" SELECT [DeptId] FROM [DeptHeadMap] WHERE [HeadMemberId]=@headMemberId"; sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@headMemberId", userInfo.id); tmpResult = sqlCmd.ExecuteScalar(); if (tmpResult != null && !tmpResult.Equals(DBNull.Value)) { userInfo.type = cGlobal.loginUserInfo.userType.deptHeader; userInfo.isADVerify = true; } } } userInfo.isValid = true; cGlobal.loginUser = userInfo; } catch (Exception ex) { userInfo.setEmpty(); } } } } else { userInfo = context.Session[_sessionName] as cGlobal.loginUserInfo; } return userInfo; } set { HttpContext context = HttpContext.Current; context.Session.Clear(); context.Session.Add(_sessionName, value); HttpCookie cookie = new HttpCookie(_cookieName); cookie.Values.Add("value", value.id); cookie.Values.Add("type", value.type.ToString()); cookie.Values.Add("expires", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now.AddDays(1))); context.Response.Cookies.Add(cookie); } } protected static object _isErrLogWriting = new object(); public static void writeErrLog(string msg) { string filePath = string.Format(@"{0}{1}\{2:yyyyMMdd}.err", HttpContext.Current.Server.MapPath("/"), WebConfigurationManager.AppSettings["logPath"], DateTime.Now); lock (_isErrLogWriting) { using (StreamWriter writer = new StreamWriter(filePath, true)) { writer.WriteLine(string.Format(@" {0:yyyy-MM-dd HH:mm:ss}, {1}, {2}", HttpContext.Current.Request.Url.AbsolutePath, DateTime.Now, msg)); writer.Close(); } } } public static string mainDatabaseConnectionString { get { return WebConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString; } } public static string TestDatabaseConnectionString { get { return WebConfigurationManager.ConnectionStrings["TestdbConnStr"].ConnectionString; } } public static int cardUIdLength { get { int len = 8; if (int.TryParse(WebConfigurationManager.AppSettings["cardUIdLen"], out len)) { // Todo: output error log } return len; } } public static int acsPasswordLength { get { int len = 4; if (int.TryParse(WebConfigurationManager.AppSettings["acsPwdLen"], out len)) { // Todo: output error log } return len; } } /// <summary> /// 系統密碼長度最短限制 /// </summary> public static int sysPwdMinLength { get { int len = 8; if (int.TryParse(WebConfigurationManager.AppSettings["sysPwdMinLen"], out len)) { // Todo: output error log } return len; } } /// <summary> /// 服務程式呼叫逾時時間 /// </summary> public static int serviceTimeout { get { int timeout = 1000; if (int.TryParse(WebConfigurationManager.AppSettings["serviceTimeout"], out timeout)) { // Todo: output error log } return timeout; } } /// <summary> /// 修改密碼往前追溯修改紀錄次數 /// </summary> public static int editSysPwdTraceCount { get { int count = 13; using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [ParamValue] FROM [SystemParam] WHERE [ParamId]='Sys_PasswordTraceCount'"; using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (sqlDR.Read()) { int.TryParse(sqlDR["ParamValue"].ToString(), out count); } } } catch (Exception ex) { // Todo: write error log } } } return count; } } /// <summary> /// 取得系統密碼有效期限訊息 /// </summary> /// <param name="userId"></param> /// <returns></returns> public static sysPwdExpireInto getSysPwdExpiredInfo(string userId) { cGlobal.sysPwdExpireInto info = new sysPwdExpireInto() { expireValue = 3, expireUnit = cGlobal.sysPwdExpireUnit.month, noticeValue = 14, noticeUnit = cGlobal.sysPwdExpireUnit.day }; info.lastModifyDate = DateTime.Now; info.expireDate = info.lastModifyDate.AddMonths(3); info.startNoticeDate = info.expireDate.AddDays(-14); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT TOP(1) [LogTime] FROM [SystemUsersPwdHistory] WHERE [UserId]=@userId ORDER BY [LogTime] DESC"; sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@userId", userId); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (sqlDR.Read()) { info.lastModifyDate = (DateTime)sqlDR["LogTime"]; } } sqlCmd.CommandText = @" SELECT [ParamId],[ParamValue] FROM [SystemParam] WHERE [ParamId] IN ('Sys_PasswordExpire','Sys_PasswordExpireNotice')"; using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { int parseInt; cGlobal.sysPwdExpireUnit parseUnit; string[] tmp = null; while (sqlDR.Read()) { tmp = sqlDR["ParamValue"].ToString().Split(','); if (tmp.Length != 2 || !int.TryParse(tmp[0], out parseInt) || !Enum.TryParse(tmp[1], out parseUnit)) { continue; } switch (sqlDR["ParamId"].ToString()) { case "Sys_PasswordExpire": info.expireValue = parseInt; info.expireUnit = parseUnit; break; case "Sys_PasswordExpireNotice": info.noticeValue = parseInt; info.noticeUnit = parseUnit; break; } } } } catch (Exception ex) { // Todo: write error log } } } switch (info.expireUnit) { case cGlobal.sysPwdExpireUnit.year: info.expireDate = info.lastModifyDate.AddYears(info.expireValue); break; case cGlobal.sysPwdExpireUnit.month: info.expireDate = info.lastModifyDate.AddMonths(info.expireValue); break; case cGlobal.sysPwdExpireUnit.day: info.expireDate = info.lastModifyDate.AddDays(info.expireValue); break; case cGlobal.sysPwdExpireUnit.hour: info.expireDate = info.lastModifyDate.AddHours(info.expireValue); break; case cGlobal.sysPwdExpireUnit.minute: info.expireDate = info.lastModifyDate.AddMinutes(info.expireValue); break; case cGlobal.sysPwdExpireUnit.second: info.expireDate = info.lastModifyDate.AddSeconds(info.expireValue); break; } switch (info.noticeUnit) { case cGlobal.sysPwdExpireUnit.year: info.startNoticeDate = info.expireDate.AddYears(-info.noticeValue); break; case cGlobal.sysPwdExpireUnit.month: info.startNoticeDate = info.expireDate.AddMonths(-info.noticeValue); break; case cGlobal.sysPwdExpireUnit.day: info.startNoticeDate = info.expireDate.AddDays(-info.noticeValue); break; case cGlobal.sysPwdExpireUnit.hour: info.startNoticeDate = info.expireDate.AddHours(-info.noticeValue); break; case cGlobal.sysPwdExpireUnit.minute: info.startNoticeDate = info.expireDate.AddMinutes(-info.noticeValue); break; case cGlobal.sysPwdExpireUnit.second: info.startNoticeDate = info.expireDate.AddSeconds(-info.noticeValue); break; } return info; } public enum sysPwdExpireUnit { year = 0, month, day, hour, minute, second } public class sysPwdExpireInto { public DateTime lastModifyDate { get; set; } public int expireValue { get; set; } public sysPwdExpireUnit expireUnit { get; set; } public DateTime expireDate { get; set; } public bool isExpired { get { return DateTime.Now > expireDate; } } public int noticeValue { get; set; } public sysPwdExpireUnit noticeUnit { get; set; } public DateTime startNoticeDate { get; set; } public bool needNotice { get { return DateTime.Now > startNoticeDate; } } } public static string systemVersion { get { return WebConfigurationManager.AppSettings["version"].Trim(); } } public static string systemRelease { get { return WebConfigurationManager.AppSettings["release"].Trim(); } } public static string importFilePath { get { string path = WebConfigurationManager.AppSettings["importFilePath"]; try { path = HttpContext.Current.Server.MapPath(path); } catch (Exception ex) { // Todo: write error log path = string.Empty; } return path; } } /// <summary> /// 取得設備時間群組可設定的組數 /// </summary> /// <param name="modelName"></param> /// <returns></returns> public static int getDeviceTimeGroupMaxCount(string modelName) { int count = 0; switch (modelName.ToUpper()) { case "SC202A": case "SC202B": count = 10; break; case "SC300": count = 100; break; case "DEFAULT": case "DEFAULT_EV1": case "LIFT_3S": count = 90; break; case "DC1001T": count = 90; break; case "SOYAL716E": count = 10; break; } return count; } /// <summary> /// 取得設備時間群組每組可設定的段數 /// </summary> /// <param name="modelName"></param> /// <returns></returns> public static int getDeviceTimeGroupSectorMaxCount(string modelName) { int count = 0; switch (modelName.ToUpper()) { case "SC202A": case "SC202B": count = 1; break; case "SC300": count = 2; break; case "DEFAULT": case "DEFAULT_EV1": case "LIFT_3S": count = 4; break; case "DC1001T": count = 4; break; case "SOYAL716E": count = 1; break; } return count; } public static bool getDeviceTimeGroupSectorDatesWithHoliday(string modelName) { bool result = false; if (modelName.ToUpper() == "SC300") { result = true; } return result; } public class sysPageInfo { public string pageId { get; set; } public bool isBasic { get; set; } } /// <summary> /// 取得登入者可使用的頁面 /// </summary> /// <param name="userId"></param> /// <returns></returns> public static sysPageInfo[] getSystemPages(string userId) { List<sysPageInfo> pageList = new List<sysPageInfo>(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT DISTINCT [SFM].[PageId], [SFM].[IsBasic] FROM [SystemUserPerms] AS [SUP] INNER JOIN [SystemFunctionMap] AS [SFM] ON [SFM].[IsEnable]=1 AND [SFM].[FunctionId]=[SUP].[FunctionId] WHERE [SUP].[UserId]=@userId"; sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@userId", userId); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { while (sqlDR.Read()) { if (sqlDR["PageId"].Equals(DBNull.Value)) { continue; } pageList.Add(new sysPageInfo() { pageId = sqlDR["PageId"].ToString(), isBasic = (bool)sqlDR["IsBasic"] }); } } } catch (Exception ex) { // Todo: write error log pageList.Clear(); } } } return pageList.ToArray(); } /// <summary> /// 人員資料狀態 /// </summary> public enum MemberDataState { Active = 0, Disable, Delete, Lock, TempCard } /// <summary> /// 取得登入者在頁面上可使用者功能 /// </summary> /// <param name="userId"></param> /// <param name="pageId"></param> /// <returns></returns> public static List<string> getPageFunctions(string userId, string pageId) { List<string> funcList = new List<string>(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [SFM].[FunctionId] FROM [SystemUserPerms] AS [SUP] INNER JOIN [SystemFunctionMap] AS [SFM] ON [SFM].[IsEnable]=1 AND [SFM].[FunctionId]=[SUP].[FunctionId] WHERE [SUP].[UserId]=@userId AND [SFM].[PageId]=@pageId"; sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@userId", userId); sqlCmd.Parameters.AddWithValue("@pageId", pageId); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { while (sqlDR.Read()) { if (sqlDR["FunctionId"].Equals(DBNull.Value)) { continue; } funcList.Add(sqlDR["FunctionId"].ToString()); } } } catch (Exception ex) { // Todo: write error log funcList.Clear(); } } } return funcList; } /// <summary> /// 操作紀錄資訊 /// </summary> public class opRecordInfo { public string pageId { get; set; } public string funcId { get; set; } public string actionDescr { get; set; } public string detailDescr { get; set; } public opRecordInfo() { pageId = string.Empty; funcId = string.Empty; actionDescr = string.Empty; detailDescr = string.Empty; } } /// <summary> /// 加入一筆操作紀錄 /// </summary> /// <param name="info"></param> /// <param name="sqlCmd"></param> /// <returns></returns> public static bool writeOperateRecords(cGlobal.opRecordInfo info, SqlCommand sqlCmd = null) { bool result = true; string userId = cGlobal.loginUser.id; bool sqlCmdExist = true; string prevCmd = string.Empty; SqlParameter[] prevParam = null; if (sqlCmd == null) { sqlCmdExist = false; sqlCmd = new SqlCommand(); sqlCmd.Connection = new SqlConnection(); sqlCmd.Connection.ConnectionString = cGlobal.mainDatabaseConnectionString; } else { prevCmd = sqlCmd.CommandText; if (sqlCmd.Parameters.Count > 0) { prevParam = new SqlParameter[sqlCmd.Parameters.Count]; sqlCmd.Parameters.CopyTo(prevParam, 0); } } try { if (sqlCmd.Connection.State != ConnectionState.Open) { sqlCmd.Connection.Open(); } sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@operateTime", DateTime.Now); sqlCmd.Parameters.AddWithValue("@userId", userId); sqlCmd.Parameters.AddWithValue("@pageId", info.pageId); sqlCmd.Parameters.AddWithValue("@functionId", info.funcId); sqlCmd.Parameters.AddWithValue("@actionDescr", info.actionDescr); sqlCmd.Parameters.AddWithValue("@detailDescr", info.detailDescr); if (info.funcId == string.Empty && info.pageId != string.Empty) { sqlCmd.CommandText = @" SELECT TOP(1) [FunctionId] FROM [SystemFunctionMap] WHERE [PageId]=@pageId"; using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (!sqlDR.Read()) { throw new Exception("Invalid Action."); } sqlCmd.Parameters["@functionId"].Value = sqlDR["FunctionId"].ToString(); } } sqlCmd.CommandText = @" INSERT INTO [OperateRecords] ([OperateTime],[UserId],[FunctionId],[ActionDescr],[DetailDescr]) VALUES (@operateTime,@userId,@functionId,@actionDescr,@detailDescr)"; result = sqlCmd.ExecuteNonQuery() > 0; } catch (Exception ex) { // Todo: write error log result = false; } finally { if (!sqlCmdExist) { sqlCmd.Connection.Dispose(); sqlCmd.Dispose(); } else { sqlCmd.CommandText = prevCmd; if (prevParam != null) { sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddRange(prevParam); } } } return result; } /// <summary> /// 權限異動方式 /// </summary> public enum authEditAction { delete = 0, add } /// <summary> /// 權限異動紀錄資訊 /// </summary> public class authEditInfo { public string memberId { get; set; } public string cardUId { get; set; } public string deviceId { get; set; } public int subDeviceIx { get; set; } public authEditAction action { get; set; } public bool isGroup { get; set; } public string remark { get; set; } public authEditInfo() { memberId = string.Empty; cardUId = string.Empty; deviceId = string.Empty; subDeviceIx = 0; action = authEditAction.delete; isGroup = false; remark = string.Empty; } } /// <summary> /// 加入一筆權限異動紀錄 /// </summary> /// <param name="info"></param> /// <param name="sqlCmd"></param> /// <returns></returns> public static bool writeAuthEditRecords(cGlobal.authEditInfo info, SqlCommand sqlCmd = null) { bool result = true; string userId = cGlobal.loginUser.id; bool sqlCmdExist = true; string prevCmd = string.Empty; SqlParameter[] prevParam = null; if (sqlCmd == null) { sqlCmdExist = false; sqlCmd = new SqlCommand(); sqlCmd.Connection = new SqlConnection(); sqlCmd.Connection.ConnectionString = cGlobal.mainDatabaseConnectionString; } else { prevCmd = sqlCmd.CommandText; if (sqlCmd.Parameters.Count > 0) { prevParam = new SqlParameter[sqlCmd.Parameters.Count]; sqlCmd.Parameters.CopyTo(prevParam, 0); } } try { if (sqlCmd.Connection.State != ConnectionState.Open) { sqlCmd.Connection.Open(); } sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@actionTime", DateTime.Now); sqlCmd.Parameters.AddWithValue("@editor", userId); sqlCmd.Parameters.AddWithValue("@memberId", info.memberId); sqlCmd.Parameters.AddWithValue("@cardUId", info.cardUId); sqlCmd.Parameters.AddWithValue("@deviceId", info.deviceId); sqlCmd.Parameters.AddWithValue("@subDeviceIx", info.subDeviceIx); sqlCmd.Parameters.AddWithValue("@action", info.action.ToString()); sqlCmd.Parameters.AddWithValue("@isGroup", info.isGroup); sqlCmd.Parameters.AddWithValue("@remark", info.remark); sqlCmd.CommandText = @" INSERT INTO [AuthEditLog] ([ActionTime],[Editor], [MemberId],[CardUId], [DeviceId],[SubDeviceIx], [Action],[IsGroup],[IsAuto], [Remark]) VALUES (@actionTime,@editor, @memberId,@cardUId, @deviceId,@subDeviceIx, @action,@isGroup,0, @remark)"; sqlCmd.ExecuteNonQuery(); } catch (Exception ex) { // Todo: write error log result = false; } finally { if (!sqlCmdExist) { sqlCmd.Connection.Dispose(); sqlCmd.Dispose(); } else { sqlCmd.CommandText = prevCmd; if (prevParam != null) { sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddRange(prevParam); } } } return result; } public class mailInfo { public string receiver { get; set; } public string subject { get; set; } public string mailContent { get; set; } public mailInfo() { receiver = string.Empty; subject = string.Empty; mailContent = string.Empty; } } /// <summary> /// 加入一筆權限異動紀錄 /// </summary> /// <param name="info"></param> /// <param name="sqlCmd"></param> /// <returns></returns> public static bool writeMailJob(cGlobal.mailInfo info, SqlCommand sqlCmd = null) { bool result = true; bool sqlCmdExist = true; string prevCmd = string.Empty; if (sqlCmd == null) { sqlCmdExist = false; sqlCmd = new SqlCommand(); sqlCmd.Connection = new SqlConnection(); sqlCmd.Connection.ConnectionString = cGlobal.mainDatabaseConnectionString; } else { prevCmd = sqlCmd.CommandText; } try { if (sqlCmd.Connection.State != ConnectionState.Open) { sqlCmd.Connection.Open(); } sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@receiver", info.receiver); sqlCmd.Parameters.AddWithValue("@subject", info.subject); sqlCmd.Parameters.AddWithValue("@mailContent", info.mailContent); sqlCmd.CommandText = @" INSERT INTO [MailJob] ([Receiver],[Subject],[MailContent]) VALUES (@receiver,@subject,@mailContent)"; result = sqlCmd.ExecuteNonQuery() > 0; } catch (Exception ex) { // Todo: write error log result = false; } finally { if (!sqlCmdExist) { sqlCmd.Connection.Dispose(); sqlCmd.Dispose(); } else { sqlCmd.CommandText = prevCmd; } } return result; } /// <summary> /// 取得登入者可管理的設備 /// </summary> /// <param name="userId"></param> /// <returns></returns> public static DataTable getMgmtDevices(string userId) { DataTable deviceTbl = new DataTable(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlCmd.Parameters.AddWithValue("@userId", userId); sqlCmd.CommandText = @" SELECT [DeviceId],[SubDeviceIx] FROM [DeviceMgmtGrpContent] WHERE [GroupId] IN ( SELECT [GroupId] FROM [SystemUserDeviceMgmtGrp] WHERE [UserId]=@userId) UNION SELECT [DeviceId],[SubDeviceIx] FROM [DeviceMgmtWhiteList] WHERE [UserId]=@userId EXCEPT SELECT [DeviceId],[SubDeviceIx] FROM [DeviceMgmtBlackList] WHERE [UserId]=@userId"; using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd)) { sqlDA.Fill(deviceTbl); } } catch (Exception ex) { // Todo: write error log deviceTbl = new DataTable(); } } } return deviceTbl; } public class sysParamInfo { public string paramId { get; set; } public string paramValue { get; set; } public string paramDescr { get; set; } public sysParamInfo() { paramId = string.Empty; paramValue = string.Empty; paramDescr = string.Empty; } } public static sysParamInfo getSystemParameter(string paramId) { cGlobal.sysParamInfo result = new cGlobal.sysParamInfo() { paramId = string.Empty, paramValue = string.Empty, paramDescr = string.Empty }; using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [ParamId], [ParamValue], [ParamDescr] FROM [SystemParam] WHERE [ParamId]=@paramId"; sqlCmd.Parameters.Clear(); sqlCmd.Parameters.AddWithValue("@paramId", paramId); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (sqlDR.Read()) { result.paramId = sqlDR["ParamId"].ToString(); result.paramValue = sqlDR["ParamValue"].ToString(); result.paramDescr = sqlDR["ParamDescr"].ToString(); } } } catch (Exception ex) { // Todo: write error log } } } return result; } public static sysParamInfo getSystemPatameter(string paramId) { cGlobal.sysParamInfo result = new sysParamInfo(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [ParamId], [ParamValue], [ParamDescr] FROM [SystemParam] WHERE [ParamId]=@paramId"; sqlCmd.Parameters.AddWithValue("@paramId", paramId); using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { if (sqlDR.Read()) { result.paramId = sqlDR["ParamId"].ToString(); result.paramValue = sqlDR["ParamValue"].ToString(); result.paramDescr = sqlDR["ParamDescr"].ToString(); } } } catch (Exception ex) { // Todo: write error log } } } return result; } public static sysParamInfo[] getSystemPatameter() { List<cGlobal.sysParamInfo> result = new List<sysParamInfo>(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [ParamId], [ParamValue], [ParamDescr] FROM [SystemParam]"; using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { while (sqlDR.Read()) { result.Add(new cGlobal.sysParamInfo() { paramId = sqlDR["ParamId"].ToString(), paramValue = sqlDR["ParamValue"].ToString(), paramDescr = sqlDR["ParamDescr"].ToString() }); } } } catch (Exception ex) { // Todo: write error log } } } return result.ToArray(); } public class mbrImgFilePathInfo { public string path_emp { get; set; } public string path_ven { get; set; } public string domain { get; set; } public string account { get; set; } public string password { get; set; } public void Reset() { path_emp = string.Empty; path_ven = string.Empty; domain = string.Empty; account = string.Empty; password = string.Empty; } public mbrImgFilePathInfo() { Reset(); } } /// <summary> /// 同仁 / 廠商資料照片位置 (從資料庫讀取) /// </summary> public static mbrImgFilePathInfo mbrImgFilePath { get { mbrImgFilePathInfo info = new cGlobal.mbrImgFilePathInfo(); using (SqlConnection sqlConn = new SqlConnection()) { sqlConn.ConnectionString = cGlobal.mainDatabaseConnectionString; using (SqlCommand sqlCmd = new SqlCommand()) { sqlCmd.Connection = sqlConn; try { sqlConn.Open(); sqlCmd.CommandText = @" SELECT [ParamId],[ParamValue] FROM [SystemParam] WHERE [ParamId] LIKE 'Sys_ImgFilePath%'"; using (SqlDataReader sqlDR = sqlCmd.ExecuteReader()) { while (sqlDR.Read()) { switch (sqlDR["ParamId"].ToString()) { case "Sys_ImgFilePath_TypeEmp": info.path_emp = sqlDR["ParamValue"].ToString(); break; case "Sys_ImgFilePath_TypeVen": info.path_ven = sqlDR["ParamValue"].ToString(); break; case "Sys_ImgFilePath_Domain": info.domain = sqlDR["ParamValue"].ToString(); break; case "Sys_ImgFilePath_Account": info.account = sqlDR["ParamValue"].ToString(); break; case "Sys_ImgFilePath_Password": info.password = sqlDR["ParamValue"].ToString(); break; } } } } catch (Exception ex) { // Todo: write error log info.Reset(); } } } return info; } } /// <summary> /// 壓縮Base64文字資料顯示圖片至32kb以下(for IE8) /// </summary> /// <param name="srcBase64Img"></param> /// <returns></returns> public static String compressBase64Img(String srcBase64Img) { byte[] org_img_bytes = Convert.FromBase64String(srcBase64Img); MemoryStream ms = new MemoryStream(org_img_bytes); byte[] buffer = ms.ToArray(); ms.Flush(); System.Drawing.Image srcImg = null; System.Drawing.Bitmap tmpBmp = null; System.Drawing.Graphics tmpGraphics = null; double new_width = 0; double new_height = 0; // 持續壓縮Base64碼大小至32kb以下 (IE8限制) int length = Convert.ToBase64String(buffer).Length; int sizeLimit = 32 * 1024; double scale = 0.75; int retryLimit = 5; while (retryLimit > 0 && length >= sizeLimit) { srcImg = System.Drawing.Image.FromStream(ms); if (srcImg.Width >= srcImg.Height) { new_width = srcImg.Width * scale; new_height = new_width * srcImg.Height / (double)srcImg.Width; } else if (srcImg.Height >= srcImg.Width) { new_height = srcImg.Height * scale; new_width = new_height * srcImg.Width / (double)srcImg.Height; } tmpBmp = new System.Drawing.Bitmap((int)new_width, (int)new_height, srcImg.PixelFormat); tmpGraphics = System.Drawing.Graphics.FromImage(tmpBmp); tmpGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; tmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; tmpGraphics.DrawImage(srcImg, 0, 0, tmpBmp.Width, tmpBmp.Height); ms = new MemoryStream(); tmpBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); buffer = ms.ToArray(); length = Convert.ToBase64String(buffer).Length; retryLimit--; } ms.Close(); return Convert.ToBase64String(buffer); } }
09-29
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值