/// <summary> /// 전화번호가 형식에 맞게 제대로 입력되었는 지 확인하기 위함. /// </summary> /// <param name="Value"></param> /// <param name="ErrMsgIs"></param> /// <returns></returns> public static bool IsPhone(string Value, out string ErrMsgIs) { ErrMsgIs = ""; const string drTextAllowed = "0123456789-)"; const int drMinLength = 7; const int drMaxLength = 12; for (int i = 0; i <= Value.Length - 1; i++) { char c = Value[i]; if (drTextAllowed.IndexOf(c) == -1) { ErrMsgIs = "전화번호는 다음 문자열만 허용됩니다\n" + drTextAllowed; return(false); } } Value = CFindRep.RemoveExcept(Value, "0123456789"); if (Value.Length < drMinLength) { ErrMsgIs = "전화번호는 최소한 " + drMinLength + "자리 이상의 숫자로 구성되어야 합니다"; return(false); } else if (Value.Length > drMaxLength) { ErrMsgIs = "전화번호는 최대한 " + drMaxLength + "자리 이하의 숫자로 구성되어야 합니다"; return(false); } return(true); }
/// <summary> /// Key와 Value로 구분된 문자열에서 nTH번째에 해당하는 Key를 리턴함. /// </summary> /// <param name="nTH"></param> /// <param name="Default"></param> /// <returns></returns> public string GetKeyByIndex(int nTH, string Default) { int PosStart = 0, PosEnd = 0, PosOfnTH; if (nTH == 0) { PosStart = 0; PosEnd = mKeyValueList.IndexOf("!") - 1; if (PosEnd == -2) { return Default; } } else { PosOfnTH = CFindRep.IndexOfnTH(mKeyValueList, mColDelim, nTH - 1); if (PosOfnTH == -1) { return Default; } PosStart = PosOfnTH + 1; PosEnd = mKeyValueList.IndexOf("!", PosStart) - 1; if (PosEnd == -2) { return Default; } } return mKeyValueList.Substring(PosStart, (PosEnd - PosStart) + 1); }
public static string GetScriptWindowOpen(string Url, string Target, FeaturesForWindowOpen Features, bool PrefixJavascriptVoid) { string sFeatures = ""; if (Features.width != null) { sFeatures += ",width=" + Features.width.ToString(); } if (Features.height != null) { sFeatures += ",height=" + Features.height.ToString(); } if (Features.left != null) { sFeatures += ",left=" + Features.left.ToString(); } if (Features.top != null) { sFeatures += ",top=" + Features.top.ToString(); } if (Features.location != null) { sFeatures += ",location=" + CFindRep.IfTrueThen1FalseThen0(Features.location.Value); } //if (Features.directories != null) // sFeatures += ",directories=" + CFindRep.IfTrueThen1FalseThen0(Features.directories.Value); if (Features.menubar != null) { sFeatures += ",menubar=" + CFindRep.IfTrueThen1FalseThen0(Features.menubar.Value); } if (Features.resizable != null) { sFeatures += ",resizable=" + CFindRep.IfTrueThen1FalseThen0(Features.resizable.Value); } if (Features.scrollbars != null) { sFeatures += ",scrollbars=" + CFindRep.IfTrueThen1FalseThen0(Features.scrollbars.Value); } if (Features.status != null) { sFeatures += ",status=" + CFindRep.IfTrueThen1FalseThen0(Features.status.Value); } if (Features.toolbar != null) { sFeatures += ",toolbar=" + CFindRep.IfTrueThen1FalseThen0(Features.toolbar.Value); } if (!string.IsNullOrEmpty(sFeatures)) { sFeatures = sFeatures.Substring(1); } string s = (PrefixJavascriptVoid ? "javascript:void(" : "") + "window.open(\"" + Url + "\", \"" + Target + "\", \"" + sFeatures + "\")" + (PrefixJavascriptVoid ? ");" : ";"); return(s); }
/// <summary> /// 현재 페이지를 호출한 페이지가 같은 서버 안에 있는 지 여부를 리턴함. /// </summary> /// <param name="ErrMsgIs"></param> /// <returns></returns> /// <example> /// <![CDATA[ /// 다음은 현재 페이지를 호출한 페이지가 다른 사이트의 페이지이면 에러 메세지를 출력하고 더 이상 진행하지 않음. /// if (!IsRefererInSameServer(out ErrMsgIs) /// { /// Response.Write(ErrMsgIs); /// Response.End(); /// } /// ]]> /// </example> public static bool IsRefererInSameServer(out string ErrMsgIs) { ErrMsgIs = ""; string Referer = CFindRep.IfNullThenEmpty(HttpContext.Current.Request.ServerVariables.Get("HTTP_REFERER")); if (Referer == "") { Referer = CWeb.GetRemoteIpAddress(HttpContext.Current); } Referer = CPath.GetServerUrl(Referer).ToLower(); string Server = HttpContext.Current.Request.ServerVariables.Get("LOCAL_ADDR"); Server = CPath.GetServerUrl(Server).ToLower(); if (Referer == Server) { return(true); } Server = HttpContext.Current.Request.ServerVariables.Get("HTTP_HOST"); Server = CPath.GetServerUrl(Server).ToLower(); if (Referer == Server) { return(true); } ErrMsgIs = "서버명이 다음과 같이 일치하지 않습니다.\r\n클라이언트: " + Referer + ", 서버: " + Server; return(false); }
public static string GetSeqListSelected(GridView grvList, string CheckBoxId, int ColSelect, int ColSeq) { string SeqList = ""; for (int i = 0, i2 = grvList.Rows.Count; i < i2; i++) { CheckBox chkSelect = grvList.Rows[i].Cells[ColSelect].FindControl(CheckBoxId) as CheckBox; if (chkSelect == null) { continue; } if (!chkSelect.Checked) { continue; } int Seq = CFindRep.IfNotNumberThen0(grvList.Rows[i].Cells[ColSeq].Text); if (Seq == 0) { continue; } SeqList += "," + Seq.ToString(); } if (SeqList != "") { SeqList = SeqList.Substring(1); } return(SeqList); }
public static int GetAttributeInt32(XmlAttribute Attr) { if (Attr != null) { return(CFindRep.IfNotNumberThen0(Attr.Value)); } else { return(0); } }
public static double GetAttributeDouble(XmlAttribute Attr) { if (Attr != null) { return(CFindRep.IfNotNumberThen0Double(Attr.Value)); } else { return(0); } }
public static Decimal GetAttributeDecimal(XmlAttribute Attr) { if (Attr != null) { return(CFindRep.IfNotNumberThen0Decimal(Attr.Value)); } else { return(0); } }
public static float GetAttributeFloat(XmlAttribute Attr) { if (Attr != null) { return(CFindRep.IfNotNumberThen0Float(Attr.Value)); } else { return(0); } }
public static int GetLinkButtonValue(TableCell cell) { LinkButton lbt = cell.Controls[0] as LinkButton; if (lbt == null) { return(0); } return(CFindRep.IfNotNumberThen0(lbt.Text)); }
private static string GetSqlTemplateReplaced(string Sql, DbServerType DSType, List <CSqlNameValueKeepValue> aNameValueKeepValue) { foreach (CSqlNameValueKeepValue nvk in aNameValueKeepValue) { string FieldName = nvk.Name; bool KeepValue = nvk.KeepValue; string Value = ""; if (nvk.Value == null) { Value = "null"; } else if (KeepValue) { //함수나 연산자가 사용된 경우엔 변형하지 않음. Value = nvk.Value.ToString(); } else { SqlColumnTypeSimple ColumnType = GetColumnTypeSimple(nvk.Value); switch (ColumnType) { case SqlColumnTypeSimple.DateTime: case SqlColumnTypeSimple.String: Value = nvk.Value.ToString(); Value = "'" + Value.Replace("'", "''"); if (DSType == DbServerType.MySQL) { Value = Value.Replace(@"\", @"\\"); } Value += "'"; break; case SqlColumnTypeSimple.Boolean: Value = CFindRep.IfTrueThen1FalseThen0((bool)nvk.Value); break; case SqlColumnTypeSimple.Numeric: Value = nvk.Value.ToString(); break; } } Sql = Sql.Replace("{{" + FieldName + "}}", Value); } return(Sql); }
private XmlElement GetElementBreak(XmlDocument XDoc, string Seconds) { double dSeconds = CFindRep.IfNotNumberThen0Double(Seconds); XmlElement el = XDoc.CreateElement("break"); if (!string.IsNullOrEmpty(Seconds)) { el.Attributes.Append(GetAttrTime(XDoc, dSeconds)); } return(el); }
private static Dictionary <int, string> SplitSqlBySemicolon(string Sql) { List <int> aIndex = new List <int>(); Dictionary <int, string> dicIdxSql = new Dictionary <int, string>(); bool IsStartQuot = false; for (int i = 0; i < Sql.Length; i++) { char c = Sql[i]; if (c == '\'') { IsStartQuot = !IsStartQuot; } else if (c == ';') { if (!IsStartQuot) { aIndex.Add(i); } } } int IndexStart = 0; int IndexEnd = -2; for (int i = 0; i < aIndex.Count; i++) { IndexStart = IndexEnd + 2; IndexEnd = aIndex[i] - 1; string SqlCur = Sql.Substring(IndexStart, (IndexEnd - IndexStart + 1)); if (!string.IsNullOrEmpty(CFindRep.TrimWhiteSpace(SqlCur))) { dicIdxSql.Add(IndexStart, SqlCur); } } { IndexStart = IndexEnd + 2; IndexEnd = Sql.Length - 1; string SqlCur = Sql.Substring(IndexStart, (IndexEnd - IndexStart + 1)); if (!string.IsNullOrEmpty(CFindRep.TrimWhiteSpace(SqlCur))) { dicIdxSql.Add(IndexStart, SqlCur); } } return(dicIdxSql); }
public static string GetServerVariablesInHtml() { HttpRequest Req = HttpContext.Current.Request; StringBuilder sb = new StringBuilder(); sb.Append("<table border=1 cellpadding=0 cellspacing=0>"); foreach (string Key in Req.ServerVariables) { sb.Append("<tr><td>" + (string)Key + "</td><td>" + CFindRep.IfNullOrEmptyThen(Req.ServerVariables.Get(Key), " ") + "</td></tr>"); } sb.Append("</table>"); return(sb.ToString()); }
/// <example> /// Console.WriteLine(RowSource.PadLeftH("a한b", 2, 'x')); //xa /// Console.WriteLine(RowSource.PadLeftH("한글", 2, 'x')); //한 /// </example> public static string PadLeftH(string Value, int TotalWidth, char PaddingChar) { int LenH = CTwoByte.LenH(Value); if (LenH > TotalWidth) { int ModIs; Value = CTwoByte.LeftH(Value, TotalWidth, out ModIs); LenH = CTwoByte.LenH(Value); } int nPad = TotalWidth - LenH; return(CFindRep.Repeat(PaddingChar, nPad) + Value); }
/// <summary> /// 현재 문장을 감싼 p 태그가 하나 뿐이라면 삭제함. /// </summary> /// <param name="Value"></param> /// <returns></returns> public static string TrimPTagIfOne(string Value) { string ValueNew = Value.Trim(); if (ValueNew.StartsWith("<p>", StringComparison.CurrentCultureIgnoreCase) && ValueNew.EndsWith("</p>", StringComparison.CurrentCultureIgnoreCase) && (ValueNew.IndexOf("<p>", 3, StringComparison.CurrentCultureIgnoreCase) == -1) ) { ValueNew = CFindRep.SubstringFromTo(ValueNew, "<p>".Length, ValueNew.Length - ("</p>".Length + 1)); return(ValueNew); } return(Value); }
public static string EncryptNumber(long Decrypted) { int[] aKey = GetKeyForEncryptNumber(); int Antilog = GetAntilogForEncryptNumber(); string sDecrypted = Decrypted.ToString(CFindRep.Repeat('0', aKey.Length)); string[] aDecrypted = CArray.SplitByLength(sDecrypted, 1); for (int i = 0; i < aDecrypted.Length; i++) { aDecrypted[i] = CMath.GetNFrom10((Convert.ToInt32(aDecrypted[i]) ^ aKey[i % 10]), Antilog); } return(string.Join("", aDecrypted)); }
public static void SplitToVariable(string ValueList, char Delim, out string Value1Is, out int Value2Is, out int Value3Is) { Value1Is = ""; Value2Is = 0; Value3Is = 0; string sValue2Is; string sValue3Is; string sValue4Is; SplitToVariable(ValueList, Delim, out Value1Is, out sValue2Is, out sValue3Is, out sValue4Is); Value2Is = CFindRep.IfNotNumberThen0(sValue2Is); Value3Is = CFindRep.IfNotNumberThen0(sValue3Is); }
public static void RestoreListControlSelectedIndex(string AppProductName, ContainerControl FrmOrUc, ListControl lst, CXmlConfig xc) { string FrmOrUcName = FrmOrUc.Name; string Section = AppProductName + "\\" + FrmOrUcName; string ControlName = lst.Name; int SelectedIndex = (xc != null) ? CFindRep.IfNotNumberThen0(xc.GetSetting(FrmOrUcName + "." + ControlName, lst.SelectedIndex)) : CFindRep.IfNotNumberThen0(CRegistry.GetSetting(Section, ControlName, lst.SelectedIndex)); if (lst.SelectedIndex != SelectedIndex) { //Items.Count 읽을 수 없어 try 사용. try { lst.SelectedIndex = SelectedIndex; } catch (Exception) { } } }
public SvcBackup() { InitializeComponent(); this.tmr = new Timer(); CXmlConfig xc = GetXmlConfig(); //60 = 1분 int Interval = CFindRep.IfNotNumberThen(xc.GetSetting("IntervalMinutes", 60), 60); this.tmr.Interval = Interval * 1000; //this.tmr.Interval = 15000; this.tmr.Enabled = true; this.tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed); //처음엔 무조건 실행 //tmr_Elapsed(this.tmr, null); }
public static string GetOracleApplicationErrorMessage(int OraErrorNumber, string ExceptionMessage) { /* * ORA-20000: 1지문2문항의 1번째 문제유형:L, 문항영역:2, 문항번호:17에 대한 권한이 없거나 허용 개수를 초과했습니다. * ORA-06512: ""DB_CONTEST.PKG_EXAM_INFO"", 줄 330에서 * ORA-06512: 줄 1에서 */ string Pattern = "ORA" + OraErrorNumber.ToString() + ":\\s(?<Message>.+?)ORA-"; Regex r = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); Match m = r.Match(ExceptionMessage); //If not found, return original message. if (!m.Success) { return(ExceptionMessage); } return(CFindRep.TrimWhiteSpace(m.Groups["Message"].Value)); }
/// <summary> /// 줄바꿈에는 \r\n과 \n이 둘다 허용되므로 모든 경우를 줄바꿈으로 인정해서 Split하기 위함. /// </summary> /// <param name="Value"></param> /// <example> /// string s = "a\n\nb\nc"; /// string[] a = CArray.SplitLineBreak(s, StringSplitOptions.None); //'a', '', 'b', 'c' /// string[] a = CArray.SplitLineBreak(s, StringSplitOptions.RemoveEmptyEntries); //'a', 'b', 'c' /// /// string s2 = ""; /// string[] a2 = CArray.SplitLineBreak(s, StringSplitOptions.None); //a2.Length = 0 /// string[] a2 = CArray.SplitLineBreak(s, StringSplitOptions.RemoveEmptyEntries); //a2.Length = 1, a2[0] = "" /// </example> /// <returns></returns> public static string[] SplitLineBreak(string Value, StringSplitOptions Options) { Value = CFindRep.ReplaceLineBreakToNewLine(Value); return(Value.Split(new char[] { '\n' }, Options)); //\r로 구분된 Silverlight TextBox 경우 Split 안되어 주석. //List<string> aValue = new List<string>(); //string Pattern = "^.*$"; //Regex r = new Regex(Pattern, RegexOptions.Multiline); //for (Match m = r.Match(Value); m.Success; m = m.NextMatch()) //{ // if ((m.Value == "") && (Options == StringSplitOptions.RemoveEmptyEntries)) // continue; // // 줄바꿈이 \r\n인 경우, \r은 남게 되므로 삭제함. // aValue.Add(m.Value.Trim('\r')); //} //return aValue.ToArray(); }
/// <summary> /// 가운데 정렬 후 양쪽에 <paramref name="PaddingChar"/>를 채워서 <paramref name="TotalWidth"/> 길이를 맞춤. /// </summary> /// <param name="Value"></param> /// <param name="TotalWidth"></param> /// <param name="PaddingChar"></param> /// <returns></returns> /// <example> /// string s = CTwoByte.PadCenterH("안a녕", 8, 'x'); //"x안a녕xx" /// string s2 = CTwoByte.PadCenterH("12", 1, 'x'); //"12" /// string s3 = CTwoByte.PadCenterH("12", 3, 'x'); //"12x" /// </example> public static string PadCenterH(string Value, int TotalWidth, char PaddingChar) { int LenH = CTwoByte.LenH(Value); if (TotalWidth <= LenH) { return(Value); } int Half = (int)((TotalWidth - LenH) / 2); int Mod = (TotalWidth - LenH) % 2; if (Half == 0) { return(Value + CFindRep.Repeat(PaddingChar, Mod)); } string Pad = CFindRep.Repeat(PaddingChar, Half); return(Pad + Value + Pad + CFindRep.Repeat(PaddingChar, Mod)); }
private static Version GetVersion(XmlDocument XDoc) { XmlAttribute Attr = XDoc.DocumentElement.Attributes["FileVersion"]; if (Attr == null) { return(new Version()); } int Version = CFindRep.IfNotNumberThen0(Attr.Value); if (Version > 0) { //4255 -> 4.2.5.5 string[] aVersion = CArray.SplitByLength(Attr.Value, 1); return(new Version(Convert.ToInt32(aVersion[0]), Convert.ToInt32(aVersion[1]), Convert.ToInt32(aVersion[2]), Convert.ToInt32(aVersion[3]))); } else { return(new Version(Attr.Value)); } }
public static string FindVariable(string ValueHasVar, string DelimStart, string DelimEnd, int StartIndex, out int StartIndexNextIs) { StartIndexNextIs = -1; int PosStart = ValueHasVar.IndexOf(DelimStart, StartIndex); if (PosStart == -1) { return(""); } PosStart += DelimStart.Length; int PosEnd = ValueHasVar.IndexOf(DelimEnd, (PosStart + 1)); if (PosEnd == -1) { return(""); } PosEnd--; StartIndexNextIs = (PosEnd + 1 + DelimEnd.Length); return(CFindRep.SubstringFromTo(ValueHasVar, PosStart, PosEnd)); }
public static void PasteItem(ListView lvw) { IDataObject data = Clipboard.GetDataObject(); if (data.GetData("System.String", true) == null) { return; } string Text = data.GetData("System.String", true).ToString(); Text = CFindRep.ReplaceLineBreakToNewLine(Text); if (!CFindRep.IsPastable(Text)) { return; } string[] Rows = Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); for (int rw = 0, rw2 = Rows.Length; rw < rw2; rw++) { string[] Cols = Rows[rw].Split('\t'); lvw.Items.Add(new ListViewItem(Cols)); } }
/// <summary> /// Form의 위치와 크기 정보를 다음에 불러올 수 있도록 레지스트리에 저장함. /// </summary> /// <param name="AppProductName">Application.ProductName</param> /// <param name="FrmOrUc">Form 개체</param> /// <param name="Kind">저장될 값의 종류</param> /// <example> /// 다음은 폼이 닫힐 때 폼의 위치, 크기 정보를 저장하고, /// 폼이 열릴 때 저장되었던 폼의 위치, 크기 정보를 불러와서 열린 폼에 적용합니다. /// <code> /// private void Form1_Load(object sender, System.EventArgs e) /// { /// CWinForm.RestoreFormStatus(Application.ProductName, this, FormSaveRestoreKind.SizePosition); /// } /// private void Form1_FormClosing(object sender, FormClosingEventArgs e) /// { /// CWinForm.SaveFormStatus(Application.ProductName, this, FormSaveRestoreKind.SizePosition); /// } /// </code> /// </example> public static void SaveFormStatus(string AppProductName, ContainerControl FrmOrUc, FormSaveRestoreKind Kind, CXmlConfig xc) { string FrmOrUcName = FrmOrUc.Name; string Section = AppProductName + "\\" + FrmOrUcName; if ((Kind & FormSaveRestoreKind.SizePosition) == FormSaveRestoreKind.SizePosition) { Form frm = (Form)FrmOrUc; if (xc != null) { xc.SaveSetting(FrmOrUcName + ".WindowState", Convert.ToInt32(frm.WindowState)); } else { CRegistry.SaveSetting(Section, "WindowState", Convert.ToInt32(frm.WindowState)); } if (frm.WindowState == FormWindowState.Normal) { if (xc != null) { xc.SaveSetting(FrmOrUcName + ".Left", frm.Left); xc.SaveSetting(FrmOrUcName + ".Top", frm.Top); } else { CRegistry.SaveSetting(Section, "Left", frm.Left); CRegistry.SaveSetting(Section, "Top", frm.Top); } switch (frm.FormBorderStyle) { case FormBorderStyle.Fixed3D: case FormBorderStyle.FixedDialog: case FormBorderStyle.FixedSingle: case FormBorderStyle.FixedToolWindow: break; default: if (xc != null) { xc.SaveSetting(FrmOrUcName + ".Width", frm.Width); xc.SaveSetting(FrmOrUcName + ".Height", frm.Height); } else { CRegistry.SaveSetting(Section, "Width", frm.Width); CRegistry.SaveSetting(Section, "Height", frm.Height); } break; } } } if (((Kind & FormSaveRestoreKind.TextBox) == FormSaveRestoreKind.TextBox) || ((Kind & FormSaveRestoreKind.NumericUpDown) == FormSaveRestoreKind.NumericUpDown) || ((Kind & FormSaveRestoreKind.ListControl) == FormSaveRestoreKind.ListControl) || ((Kind & FormSaveRestoreKind.CheckBox) == FormSaveRestoreKind.CheckBox)) { List <Control> aCtl = new List <Control>(); aCtl = GetControls(FrmOrUc, ref aCtl); foreach (Control ctl in aCtl) { Type TypeCur = ctl.GetType(); string ControlName = ctl.Name; if (((Kind & FormSaveRestoreKind.TextBox) == FormSaveRestoreKind.TextBox) && (TypeCur.BaseType == typeof(TextBoxBase))) { TextBoxBase txt = (TextBoxBase)ctl; if (xc != null) { xc.SaveSetting(FrmOrUcName + "." + ControlName, txt.Text); } else { CRegistry.SaveSetting(Section, ControlName, txt.Text); } } else if (((Kind & FormSaveRestoreKind.NumericUpDown) == FormSaveRestoreKind.NumericUpDown) && (TypeCur == typeof(NumericUpDown))) { NumericUpDown nud = (NumericUpDown)ctl; if (xc != null) { xc.SaveSetting(FrmOrUcName + "." + ControlName, nud.Value); } else { CRegistry.SaveSetting(Section, ControlName, nud.Value); } } else if (((Kind & FormSaveRestoreKind.ListControl) == FormSaveRestoreKind.ListControl) && (TypeCur.BaseType == typeof(ListControl))) { ListControl lst = (ListControl)ctl; SaveListControlSelectedIndex(AppProductName, FrmOrUc, lst, xc); } else if (((Kind & FormSaveRestoreKind.CheckBox) == FormSaveRestoreKind.CheckBox) && (TypeCur == typeof(CheckBox))) { CheckBox chk = (CheckBox)ctl; if (xc != null) { xc.SaveSetting(FrmOrUcName + "." + ControlName, CFindRep.IfTrueThen1FalseThen0(chk.Checked)); } else { CRegistry.SaveSetting(Section, ControlName, CFindRep.IfTrueThen1FalseThen0(chk.Checked)); } } } } }
/// <summary> /// 미리 저장된 Form의 위치와 크기 정보를 불러와서 현재 폼의 위치와 크기를 변경함. /// </summary> /// <param name="AppProductName">Application.ProductName</param> /// <param name="FrmOrUc">Form 개체</param> /// <param name="Kind">저장될 값의 종류</param> /// <example> /// 다음은 폼이 닫힐 때 폼의 위치, 크기 정보를 저장하고, /// 폼이 열릴 때 저장되었던 폼의 위치, 크기 정보를 불러와서 열린 폼에 적용합니다. /// <code> /// private void Form1_Load(object sender, System.EventArgs e) /// { /// CWinForm.RestoreFormStatus(Application.ProductName, this, FormSaveRestoreKind.SizePosition); /// } /// private void Form1_FormClosing(object sender, FormClosingEventArgs e) /// { /// CWinForm.SaveFormStatus(Application.ProductName, this, FormSaveRestoreKind.SizePosition); /// } /// </code> /// </example> public static void RestoreFormStatus(string AppProductName, ContainerControl FrmOrUc, FormSaveRestoreKind Kind, CXmlConfig xc) { string FrmOrUcName = FrmOrUc.Name; string Section = AppProductName + "\\" + FrmOrUcName; if ((Kind & FormSaveRestoreKind.SizePosition) == FormSaveRestoreKind.SizePosition) { Form frm = (Form)FrmOrUc; int LeftWill, TopWill; int WindowStateDefault = (int)FormWindowState.Normal; object WindowState = (xc != null) ? xc.GetSetting(FrmOrUcName + ".WindowState", WindowStateDefault) : CRegistry.GetSetting(Section, "WindowState", WindowStateDefault); FormWindowState ws = FormWindowState.Normal; try { ws = (FormWindowState)Convert.ToInt32(WindowState); } catch (Exception) { } if (frm.WindowState != ws) { frm.WindowState = ws; } if (ws == FormWindowState.Normal) { int LeftDefault = frm.Left; object Left = (xc != null) ? xc.GetSetting(FrmOrUcName + ".Left", LeftDefault) : CRegistry.GetSetting(Section, "Left", LeftDefault); LeftWill = Convert.ToInt32(Left); if (LeftWill < 0) { LeftWill = 0; } int TopDefault = frm.Top; object Top = (xc != null) ? xc.GetSetting(FrmOrUcName + ".Top", TopDefault) : CRegistry.GetSetting(Section, "Top", TopDefault); TopWill = Convert.ToInt32(Top); if (TopWill < 0) { TopWill = 0; } if (frm.Left != LeftWill) { frm.Left = LeftWill; } if (frm.Top != TopWill) { frm.Top = TopWill; } switch (frm.FormBorderStyle) { case FormBorderStyle.Fixed3D: case FormBorderStyle.FixedDialog: case FormBorderStyle.FixedSingle: case FormBorderStyle.FixedToolWindow: break; default: int WidthDefault = frm.Width; object Width = (xc != null) ? xc.GetSetting(FrmOrUcName + ".Width", WidthDefault) : CRegistry.GetSetting(Section, "Width", WidthDefault); int WidthWill = Convert.ToInt32(Width); if (frm.Width != WidthWill) { frm.Width = WidthWill; } int HeightDefault = frm.Height; object Height = (xc != null) ? xc.GetSetting(FrmOrUcName + ".Height", HeightDefault) : CRegistry.GetSetting(Section, "Height", HeightDefault); int HeightWill = Convert.ToInt32(Height); if (frm.Height != HeightWill) { frm.Height = HeightWill; } break; } } } if (((Kind & FormSaveRestoreKind.TextBox) == FormSaveRestoreKind.TextBox) || ((Kind & FormSaveRestoreKind.NumericUpDown) == FormSaveRestoreKind.NumericUpDown) || ((Kind & FormSaveRestoreKind.ListControl) == FormSaveRestoreKind.ListControl) || ((Kind & FormSaveRestoreKind.CheckBox) == FormSaveRestoreKind.CheckBox)) { List <Control> aCtl = new List <Control>(); aCtl = GetControls(FrmOrUc, ref aCtl); foreach (Control ctl in aCtl) { Type TypeCur = ctl.GetType(); string ControlName = ctl.Name; if (((Kind & FormSaveRestoreKind.TextBox) == FormSaveRestoreKind.TextBox) && (TypeCur.BaseType == typeof(TextBoxBase))) { TextBoxBase txt = (TextBoxBase)ctl; string Value = (xc != null) ? xc.GetSetting(FrmOrUcName + "." + ControlName, txt.Text) : CRegistry.GetSetting(Section, ControlName, txt.Text).ToString(); if (txt.Text != Value) { txt.Text = Value; } } else if (((Kind & FormSaveRestoreKind.NumericUpDown) == FormSaveRestoreKind.NumericUpDown) && (TypeCur == typeof(NumericUpDown))) { NumericUpDown nud = (NumericUpDown)ctl; string Value = (xc != null) ? xc.GetSetting(FrmOrUcName + "." + ControlName, nud.Value) : CRegistry.GetSetting(Section, ControlName, nud.Value).ToString(); if (nud.Value.ToString() != Value) { nud.Value = (decimal)CFindRep.IfNotNumberThen0Decimal(Value); } } else if (((Kind & FormSaveRestoreKind.ListControl) == FormSaveRestoreKind.ListControl) && (TypeCur.BaseType == typeof(ListControl))) { ListControl lst = (ListControl)ctl; RestoreListControlSelectedIndex(Application.ProductName, FrmOrUc, lst, xc); } else if (((Kind & FormSaveRestoreKind.CheckBox) == FormSaveRestoreKind.CheckBox) && (TypeCur == typeof(CheckBox))) { CheckBox chk = (CheckBox)ctl; bool Checked = (xc != null) ? (xc.GetSetting(FrmOrUcName + "." + ControlName, CFindRep.IfTrueThen1FalseThen0(chk.Checked)) == "1") : (CRegistry.GetSetting(Section, ControlName, CFindRep.IfTrueThen1FalseThen0(chk.Checked)).ToString() == "1"); if (chk.Checked != Checked) { chk.Checked = Checked; } } else if (((Kind & FormSaveRestoreKind.RadioButton) == FormSaveRestoreKind.RadioButton) && (TypeCur == typeof(RadioButton))) { RadioButton rad = (RadioButton)ctl; bool Checked = (xc != null) ? (xc.GetSetting(FrmOrUcName + "." + ControlName, CFindRep.IfTrueThen1FalseThen0(rad.Checked)) == "1") : (CRegistry.GetSetting(Section, ControlName, CFindRep.IfTrueThen1FalseThen0(rad.Checked)).ToString() == "1"); if (rad.Checked != Checked) { rad.Checked = Checked; } } } } }
public static CSyncReturn Syncronize(Type T) { CScriptConstSyncAttribute[] attributes = (CScriptConstSyncAttribute[])T.GetCustomAttributes(typeof(CScriptConstSyncAttribute), false); string FullPath = attributes[0].FullPathOfJavaScript; if (FullPath.StartsWith("/")) { FullPath = HttpContext.Current.Server.MapPath(FullPath); } if (!File.Exists(FullPath)) { throw new Exception(string.Format("{0} is not exists.", FullPath)); } string JsGenerated = ConvertToJavaScript(T, 0); string FileContent = CFile.GetTextInFile(FullPath); string LogDateTime = DateTime.Now.ToString(CConst.Format_yyyyMMddHHmmss); string FullPathBackup = GetFullPathBackup(FullPath, LogDateTime); string Declare = "var " + T.Name + " "; SyncResults SyncResult = SyncResults.NoChange; string JsAlready = GetJavaScriptByDeclare(FileContent, Declare); if (!string.IsNullOrEmpty(JsAlready)) { if (CFindRep.TrimWhiteSpace(JsGenerated) != CFindRep.TrimWhiteSpace(JsAlready)) { SyncResult = SyncResults.Update; } } else { SyncResult = SyncResults.Append; } if (SyncResult != SyncResults.NoChange) { string Line = string.Format("//{0} {1} by CScriptConstSyncAttribute", LogDateTime, SyncResult); string FileContentNew = ""; if (SyncResult == SyncResults.Update) { FileContentNew = FileContent.Replace(JsAlready, Line + "\r\n" + JsGenerated); } else if (SyncResult == SyncResults.Append) { FileContentNew = FileContent + "\r\n" + Line + "\r\n" + JsGenerated; } CFile.WriteTextToFile(FullPath, FileContentNew); CFile.WriteTextToFile(FullPathBackup, FileContent); } return(new CSyncReturn() { SyncResult = SyncResult, FullPathOfJavaScript = FullPath, FullPathOfJavaScriptBackup = FullPathBackup }); }
private static string ConvertToJavaScript(Type T, int Depth) { string TmpAll = ""; if (Depth == 0) { TmpAll = @"var {{Name}} = { {{NameValue}} };"; } else { TmpAll = @", {{Tab}}{{Name}}: {{Tab}}{ {{NameValue}} {{Tab}}}"; } string TmpNameValue = ",\r\n{{Tab}}\t{{Name}}: {{Value}}"; string NameValue = ""; MemberInfo[] aMi = T.GetMembers(BindingFlags.Public | BindingFlags.Static); foreach (MemberInfo mi in aMi) { if (mi.MemberType == MemberTypes.Field) { FieldInfo fi = T.GetField(mi.Name); Type FieldType = fi.FieldType; string Name = fi.Name; string Value = ""; if (fi.IsLiteral) { object ConstValue = fi.GetRawConstantValue(); if (FieldType.IsEnum) { DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); string Desc = (attributes.Length > 0) ? attributes[0].Description : null; if (!string.IsNullOrEmpty(Desc)) { Value = string.Format("new CVnd(\"{0}\", \"{1}\", \"{2}\")", ConstValue, Name, Desc); } else { Value = ConstValue.ToString(); } } else { if (FieldType == typeof(char)) { Value = string.Format("'{0}'", ConstValue); } else if (FieldType == typeof(string)) { Value = string.Format("\"{0}\"", ConstValue); } else { Value = ConstValue.ToString(); } } } else if (fi.IsInitOnly) { if (FieldType == typeof(string[])) { string[] aValue = (string[])fi.GetValue(null); Value = "[ \"" + string.Join("\", \"", aValue) + "\" ]"; } } NameValue += TmpNameValue .Replace("{{Tab}}", CFindRep.Repeat('\t', Depth)) .Replace("{{Name}}", Name) .Replace("{{Value}}", Value.ToString()); } else if (mi.MemberType == MemberTypes.NestedType) { Type Typ = T.GetNestedType(mi.Name); NameValue += ConvertToJavaScript(Typ, Depth + 1); } } if (!string.IsNullOrEmpty(NameValue)) { NameValue = NameValue.Substring(",\r\n".Length); } string s = TmpAll .Replace("{{Tab}}", CFindRep.Repeat('\t', Depth)) .Replace("{{Name}}", T.Name) .Replace("{{NameValue}}", NameValue); return(s); }