|
|
|
C# WinApp เอาโค้ดบ้าน ๆ มาให้ใช้เล่นๆครับเผื่อใครอยากเอาไปพัฒนาแล้วส่งต่อมั่ง |
|
|
|
|
|
|
|
clsDataservices.cs
Code (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TORServices
{ public enum EnumConnstring
{
SQL_Server_ODBC,SQL_Server_OLEDB,
Excel_ODBC, Excel_OLEDB,
Text_ODBC, Text_OLEDB,
DBF_FoxPro_ODBC,DBF_FoxPro_OLEDB,
Access_ODBC,Access_OLEDB,
Oracle_ODBC,Oracle_OLEDB,
MySQL_ODBC,MySQL_OLEDB
};
public enum EnumConnectionType
{ ODBC, OLEDB, SqlClient }
public static class SQLString
{
public static string Company_Department = "SELECT * FROM dbo.Company_Department";
public static string Company_Section = "SELECT * FROM dbo.Company_Section";
public static string Company_Position = "SELECT * dbo.Company_Position";
public static string Company_COMPANY = "SELECT * FROM dbo.COMPANY";
public static string Company_Division = "SELECT * dbo.Company_Division";
}
internal class ClsPrintDataGridView
{
#region Variables
int iCellHeight = 0; //Used to get/set the datagridview cell height
int iTotalWidth = 0; //
int iRow = 0;//Used as counter
bool bFirstPage = false; //Used to check whether we are printing first page
bool bNewPage = false;// Used to check whether we are printing a new page
int iHeaderHeight = 0; //Used for the header height
StringFormat strFormat; //Used to format the grid rows.
List<double> arrColumnLefts = new List<double>();//Used to save left coordinates of columns
List<double> arrColumnWidths = new List<double>();//Used to save column widths
private PrintDocument _printDocument = new PrintDocument();
private DataGridView gw = new DataGridView();
private string _ReportHeader;
int iCount = 0;
#endregion
public ClsPrintDataGridView(DataGridView gridview, string ReportHeader)
{
_printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
_printDocument.BeginPrint += new PrintEventHandler(printDocument_BeginPrint);
gw = gridview;
_ReportHeader = ReportHeader;
}
public void PrintForm()
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = _printDocument;
printDialog.UseEXDialog = true;
//Get the document
if (DialogResult.OK == printDialog.ShowDialog())
{
_printDocument.DocumentName = _ReportHeader + string.Format("{0:yyyyMMdd hhmmss}", DateTime.Now);
_printDocument.Print();
}
}
#region Begin Print Event Handler
/// <span class="code-SummaryComment"><summary></span>
/// Handles the begin print event of print document
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void printDocument_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
if (arrColumnLefts != null) arrColumnLefts.Clear();
if (arrColumnWidths != null) arrColumnWidths.Clear();
arrColumnLefts = new List<double>();
arrColumnWidths = new List<double>();
iCellHeight = 0;
iCount = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in gw.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
#endregion
#region Print Page Event
/// <span class="code-SummaryComment"><summary></span>
/// Handles the print page event of print document
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void printDocument_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in gw.Columns)
{
iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
(double)iTotalWidth * (double)iTotalWidth *
((double)e.MarginBounds.Width / (double)iTotalWidth))));
iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;
// Save width and height of headers
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= gw.Rows.Count - 1)
{
DataGridViewRow GridRow = gw.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 5;
int iCount = 0;
//Check whether the current page settings allows more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString(_ReportHeader,
new Font(gw.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left,
e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToLongDateString() + " " +
DateTime.Now.ToShortTimeString();
//Draw Date
e.Graphics.DrawString(strDate,
new Font(gw.Font, FontStyle.Bold), Brushes.Black,
e.MarginBounds.Left +
(e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Width),
e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
new Font(new Font(gw.Font, FontStyle.Bold),
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top;
foreach (DataGridViewColumn GridCol in gw.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(GridCol.HeaderText,
GridCol.InheritedStyle.Font,
new SolidBrush(GridCol.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
//Draw Columns Contents
foreach (DataGridViewCell Cel in GridRow.Cells)
{
if (Cel.Value != null)
{
e.Graphics.DrawString(Cel.Value.ToString(),
Cel.InheritedStyle.Font,
new SolidBrush(Cel.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount],
(float)iTopMargin,
(int)arrColumnWidths[iCount], (float)iCellHeight),
strFormat);
}
//Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
#endregion
}
public class _DabaseSelected
{
public int _Key;
public string _Value;
}
public class _DatabaseSetting
{
public string FileDatabase;
public EnumConnectionType enumConnectionType;
public EnumConnstring enumConnstring;
public string PASS = "";
}
public static class clsDatabaseServices
{
public static void TextIndexAndValue(TextBox txtIndex, TextBox txtValue, string _SQL, string _ConnectionString)
{
List<TORServices._DabaseSelected> lst = new List<TORServices._DabaseSelected>();
lst = clsDatabaseServices.ReturnListIndex(_SQL, _ConnectionString, TORServices.EnumConnectionType.SqlClient);
if (lst.Count > 0)
{
txtIndex.Text = lst[0]._Key.ToString();
txtValue.Text = lst[0]._Value;
}
}
public static System.Windows.Forms.ComboBox DatabaseInCombobox(string _SQL, string strConn, EnumConnectionType ConnectionType)
{
ComboBox cmb = new ComboBox();
cmb.DataSource = GetTableForm(_SQL, strConn, ConnectionType);
return cmb;
}
public static void GetValueBindingSource(BindingSource bs, string column, string index)
{
if (index.Length > 0)
{
bs.Position = bs.Find(column, index);
}
}
public static string Connstring(string _file,EnumConnstring contype ,string pass = "4410210091")
{
// Server "Data Source=TORANN-PC;Initial Catalog=LogSystem;User ID=sa;Password=4410210091"
// Access 4.0 Provider=Microsoft.Jet.OLEDB.4.0;Data Source=X:\DATA\BASE.mdb;Jet OLEDB:Database Password=4410210091
// Access 12.0 Provider=Microsoft.ACE.OLEDB.12.0;Data Source=X:\DATA\BASE.mdb;Jet OLEDB:Database Password=4410210091
// Access ODBC Dsn=MS Access Database;dbq=X:\DATA\BASE.mdb;defaultdir=X:\DATA;driverid=25;fil=MS Access;maxbuffersize=2048;pagetimeout=5;pwd=4410210091;uid=admin
return "Dsn=MS Access Database;dbq=" + _file + ";defaultdir=" + System.IO.Path.GetDirectoryName(_file) + ";driverid=25;fil=MS Access;maxbuffersize=2048;pagetimeout=5;pwd=" + pass + ";uid=admin";
}
public static System.Data.DataTable GetTableForm(string _SQL, string strConn, EnumConnectionType ConnectionType )
{
System.Data.DataSet ds = new System.Data.DataSet();
switch (ConnectionType)
{
case EnumConnectionType.ODBC:
System.Data.Odbc.OdbcConnection conn1 = new System.Data.Odbc.OdbcConnection(strConn);
conn1.Open();
System.Data.Odbc.OdbcDataAdapter adapter1 = new System.Data.Odbc.OdbcDataAdapter(_SQL, conn1);
adapter1.Fill(ds);
break;
case EnumConnectionType.OLEDB:
System.Data.OleDb.OleDbConnection conn2 = new System.Data.OleDb.OleDbConnection(strConn);
conn2.Open();
System.Data.OleDb.OleDbDataAdapter adapter2 = new System.Data.OleDb.OleDbDataAdapter(_SQL, conn2);
adapter2.Fill(ds);
break;
case EnumConnectionType.SqlClient:
System.Data.SqlClient.SqlConnection conn3 = new System.Data.SqlClient.SqlConnection(strConn);
conn3.Open();
System.Data.SqlClient.SqlDataAdapter adapter3 = new System.Data.SqlClient.SqlDataAdapter(_SQL, conn3);
adapter3.Fill(ds);
break;
}
return ds.Tables[0];
}
public static string[] GetData(string field, string table, string strConn, EnumConnectionType ConnectionType )
{
DataTable dt = GetTableForm("Select " + field + " FROM " + table, strConn, ConnectionType);
string[] str= new string[dt.Rows.Count];
for (int i = 0;i<dt.Rows.Count;i++)
{
str[i] = dt.Rows[i][field].ToString();
}
return str;
}
public static DataRow GetDataRow(string sql ,string strConn, EnumConnectionType ConnectionType)
{
DataTable dt = GetTableForm(sql, strConn, ConnectionType);
return dt.Rows[0];
}
public static System.Data.DataTable GetTableFormExcel(string _SQL, string FileExcel)
{
string _ConnectionString = @"Data Source=" + FileExcel + "; Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;";
try
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(_ConnectionString);
conn.Open();
string strQuery = _SQL;
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataSet ds = new System.Data.DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
catch { return null; }
}
public static void PrintDataGridView(DataGridView gridview, string ReportHeader)
{
ClsPrintDataGridView pnt = new ClsPrintDataGridView(gridview, ReportHeader);
pnt.PrintForm();
}
public static List<_DabaseSelected> ReturnListIndex(string _strSQL,string _strConn, EnumConnectionType ConnectionTypeint , int clmIndex = 1,int clmValue = 2)
{
frmSelectgedDatabase f = new frmSelectgedDatabase();
f.table = GetTableForm(_strSQL,_strConn, ConnectionTypeint) ;
f.ShowDialog();
List< _DabaseSelected> LstInt = new List<_DabaseSelected>();
if (f.dataGridView1.Rows.Count > 0)
{
foreach (DataGridViewRow fees_row in f.dataGridView1.Rows)
{
if (fees_row.Cells[0].Value != null)
{
if ((bool)fees_row.Cells[0].Value == true)
{
_DabaseSelected ds = new _DabaseSelected();
ds._Key = (int)fees_row.Cells[clmIndex].Value;
ds._Value = (string)fees_row.Cells[clmValue].Value;
LstInt.Add(ds );
}
}
}
}
return LstInt;
}
public static void DataGridViewOpenEditFile(System.Windows.Forms.DataGridView DGV, System.Windows.Forms.DataGridViewCellEventArgs e, int clnOpen, int clnEdit, string PathOpen, bool EditFile = false)
{
if (e.ColumnIndex == clnEdit)
{
string s = TORServices.clsFile_Path.SelectAndSaveFile(PathOpen);
if (System.IO.File.Exists(PathOpen + "\\" + s))
{
DGV[clnOpen, e.RowIndex].Value = s;
}
}
else if (e.ColumnIndex == clnOpen)
{
if (System.IO.File.Exists(PathOpen + "\\" + DGV[clnOpen, e.RowIndex].Value.ToString()))
{
TORServices.clsFile_Path.OpenFile(PathOpen + "\\" + DGV[clnOpen, e.RowIndex].Value.ToString(), EditFile);
}
else { System.Windows.Forms.MessageBox.Show("เกิดข้อผิดพลาด ไฟล์เสียหาย" + Environment.NewLine + "กรุณาตรวจสอบ"); }
}
}
}
}
clsMath.cs
Code (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TORServices
{
public static class clsMathFunction
{
public static Int32 _XORvalue = 13;
public static double STDEV(double[] Input)
{
double _avg = Avg(Input);
double _STDEV = 0;
double Sum = 0;
if (Input.Length > 0)
{
for (int i = 0; i < Input.Length - 1; i++)
{
Sum = Sum + ((Input[i] - _avg) * (Input[i] - _avg));
}
_STDEV = Math.Sqrt(Sum / (Input.Length-1));
}
return _STDEV;
}
public static double Avg(double[] Input)
{
double _avg =0;
double Sum = 0;
if (Input.Length > 0)
{
for(int i = 0;i<Input.Length;i++)
{
Sum = Sum + Input[i];
}
_avg = Sum / Input.Length;
}
return _avg;
}
public static string NumFormat(int digit)
{
string format = "0";
if (digit > 0)
{
format = "0.";
for (int i = 1; i <= digit; i++)
{
format = format + "0";
}
}
return "{0:" + format + "}";
}
public static double GetRandomNumber(double minimum, double maximum,int digit = 1)
{
Random random = new Random();
return Convert.ToDouble(string.Format( NumFormat(digit) , (random.NextDouble() * (maximum - minimum) + minimum)));
}
public static string XOR_Enc(string str)
{
char[] f = str.ToCharArray();
for (int i = 0; i < f.Length; i++)
{
f[i] = (char)((uint)f[i] ^ _XORvalue);
}
return new string(f);
}
public static string XOR_Dec(string str)
{
char[] f = str.ToCharArray();
for (int i = 0; i < f.Length; i++)
{
f[i] = (char)((uint)f[i] ^ _XORvalue);
}
return new string(f);
}
public static string Decimal2Binary(int Dec)
{
string Bit = null;
Bit = "";
while ((Dec > 0))
{
Bit = (Dec % 2) + Bit;
Dec = Dec / 2;
}
return Bit;
}
public static double Sensitivity(object conct,object Abs)
{
return Convert.ToDouble(0.0044 * Convert.ToDouble(conct) / Convert.ToDouble(Abs));
}
public static string ThaiBaht(string txt)
{
string bahtTxt, n, bahtTH = "";
double amount;
try { amount = Convert.ToDouble(txt); }
catch { amount = 0; }
bahtTxt = amount.ToString("####.00");
string[] num = {"ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "สิบ"};
string[] rank = { "", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน", "ล้าน" };
string[] temp = bahtTxt.Split('.');
string intVal = temp[0];
string decVal = temp[1];
if (Convert.ToDouble(bahtTxt) == 0)
bahtTH = "ศูนย์บาทถ้วน";
else
{
for (int i = 0; i < intVal.Length; i++)
{
n = intVal.Substring(i, 1);
if (n != "0")
{
if ((i == (intVal.Length - 1)) && (n == "1"))
bahtTH += "เอ็ด";
else if ((i == (intVal.Length - 2)) && (n == "2"))
bahtTH += "ยี่";
else if ((i == (intVal.Length - 2)) && (n == "1"))
bahtTH += "";
else
bahtTH += num[Convert.ToInt32(n)];
bahtTH += rank[(intVal.Length - i) - 1];
}
}
bahtTH += "บาท";
if (decVal == "00")
bahtTH += "ถ้วน";
else
{
for (int i = 0; i < decVal.Length; i++)
{
n = decVal.Substring(i, 1);
if (n != "0")
{
if ((i == decVal.Length - 1) && (n == "1"))
bahtTH += "เอ็ด";
else if ((i == (decVal.Length - 2)) && (n == "2"))
bahtTH += "ยี่";
else if ((i == (decVal.Length - 2)) && (n == "1"))
bahtTH += "";
else
bahtTH += num[Convert.ToInt32(n)];
bahtTH += rank[(decVal.Length - i) - 1];
}
}
bahtTH += "สตางค์";
}
}
return bahtTH;
}
public static string ToThai(this double number)
{
return ThaiNumber(number.ToString());
}
public static string ToThai(this double number, string format)
{
return ThaiNumber(number.ToString(format));
}
public static string ToThai(this double number, IFormatProvider format)
{
return ThaiNumber(number.ToString(format));
}
public static string ToText(this double number)
{
string[] text = number.ToString().Split('.');
string inttext = IntToText(text[0]);
string dectext = (text.Length > 1) ? DecToText(text[1]) : string.Empty;
return (text.Length == 1) ? ((inttext != string.Empty) ? inttext : "ศูนย์") : string.Format("{0}จุด{1}", (inttext != string.Empty) ? inttext : "ศูนย์", dectext);
}
public static string ToBaht(this double number)
{
string[] text = number.ToString().Split('.');
string inttext = IntToText(text[0]);
string dectext = (text.Length > 1) ? (text[1].Length <= 2) ? ((inttext != string.Empty) ? "บาท" : string.Empty) + IntToText((text[1].Length == 1) ? text[1] + "0" : text[1]) + "สตางค์" : ((inttext != string.Empty) ? string.Empty : "ศูนย์") + "จุด" + DecToText(text[1]) + "บาท" : string.Empty;
return (text.Length == 1) ? (inttext == string.Empty) ? "ศูนย์บาท" : inttext + "บาทถ้วน" : inttext + dectext;
}
private static string ThaiNumber(string text)
{
string result = string.Empty;
char[] thai = new char[] { '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙' };
foreach (char c in text.ToCharArray())
{
result += (!char.IsDigit(c)) ? c : thai[Convert.ToInt16(c.ToString())];
}
return result;
}
private static string IntToText(string str)
{
List<string> text = new List<string>();
List<string> num = SplitString(str, 6);
for (int i = 0; i < num.Count; i++)
{
string numThai = NumToThai(num[i]) + string.Join(string.Empty, Enumerable.Repeat<string>("ล้าน", i).ToArray());
text.Add(numThai);
}
string[] result = text.ToArray();
Array.Reverse(result);
return string.Join(string.Empty, result);
}
private static string DecToText(string str)
{
string[] thai = new string[] { "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า" };
string result = string.Empty;
foreach (char c in str.ToCharArray())
{
result += thai[Convert.ToInt16(c.ToString())];
}
return result;
}
private static string NumToThai(string str)
{
string[] position = new string[] { string.Empty, "สิบ", "ร้อย", "พัน", "หมื่น", "แสน" };
string[] thai = new string[] { "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า" };
char[] charArray = str.ToCharArray();
List<string> text = new List<string>();
for (int i = 0; i < str.Length; i++)
{
if (charArray[i] != '0')
{
if (charArray[i] == '1' && i == 0)
{
text.Add((str.Length > 1) ? (Convert.ToInt64(str) != 10) ? "เอ็ด" : "หนึ่ง" : "หนึ่ง");
}
else if (charArray[i] == '1' && i == 1)
{
text.Add(position[i]);
}
else if (charArray[i] == '2' && i == 1)
{
text.Add("ยี่" + position[i]);
}
else
{
text.Add(thai[Convert.ToInt16(charArray[i].ToString())] + position[i]);
}
}
}
string[] result = text.ToArray();
Array.Reverse(result);
return string.Join(string.Empty, result);
}
private static List<string> SplitString(string str, int length)
{
List<string> result = new List<string>();
string text = string.Empty;
char[] charArray = str.ToCharArray();
for (int i = str.Length - 1; i >= 0 ; i--)
{
if (text.Length < length)
{
text += charArray[i];
}
if (i == 0 || text.Length == length)
{
result.Add(text);
text = string.Empty;
}
}
return result;
}
}
}
clsPathFile.cs
Code (C#)
//using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Windows;
using System.Runtime.InteropServices;
using System.IO.Compression;
using System.IO;
///using Microsoft.Deployment.Compression.Cab;
namespace TORServices
{
//เบอร์สั่งแก๊ส 024104872
//4386795051677962
//1016
public static class clsPathData
{
public static string FILEREF = _Path("FILEREF");
public static string Path_File_Int = _Path("FILEREF\\File_Int");
public static string Path_File_Ebook = _Path("FILEREF\\Path_File_Ebook");
public static string Path_File_PT = _Path("FILEREF\\File_PT");
public static string Path_File_Reagent = _Path("FILEREF\\File_Reagent");
public static string Path_Document = _Path("FILEREF\\Document");
public static string Path_File_STD = _Path("FILEREF\\File_STD");
public static string Path_tempFile = _Path("FILEREF\\tempFile");
public static string Path_File_Int_Program = _Path("FILEREF\\File_Int\\Program");
public static string Path_Method = _Path("FILEREF\\Method");
public static string CertificateLab = _Path("CertificateLab");
public static string Company = _Path("Company");
public static string Path_Backup = _Path("DATA_BACKUP");
public static string Path_Data_run= _Path( "DATA");
public static string File_ALSF717 = _Path("DATA\\File_ALSF717");
public static string Path_ALSF711 = _Path("DATA\\File_ALSF711");
public static string Path_AllReport = _Path("REPORT");
public static string Path_BlankForm = _Path("BLANK_FORM");
public static string Path_Product = _Path("Path_Product");
public static string Path_Map = _Path("Map");
public static string Path_Standard_Data = _Path("Standard_DATA");
public static string PathRARProgram { get { return Registry.GetValue(TORServices.clsFile_Path.KeyReg, "PathRARProgram", true).ToString(); } set { Registry.SetValue(TORServices.clsFile_Path.KeyReg, "PathRARProgram", value); } }
public static string _Path(string _p)
{
if (TORServices.clsFile_Path._PathDATA.Substring(TORServices.clsFile_Path._PathDATA.Length - 1) == "\\")
{
if (!System.IO.Directory.Exists(TORServices.clsFile_Path._PathDATA + _p))
{
TORServices.clsFile_Path.CreatePath(TORServices.clsFile_Path._PathDATA + _p);
}
return TORServices.clsFile_Path._PathDATA + _p;
}
else
{
if (!System.IO.Directory.Exists(TORServices.clsFile_Path._PathDATA + "\\" + _p))
{
TORServices.clsFile_Path.CreatePath(TORServices.clsFile_Path._PathDATA + "\\" + _p);
}
return TORServices.clsFile_Path._PathDATA + "\\" + _p;
}
}
public static void RenameTo(System.IO.DirectoryInfo di, string name)
{
if (di == null)
{
throw new ArgumentNullException("di", "Directory info to rename cannot be null");
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("New name cannot be null or blank", "name");
}
di.MoveTo(System.IO.Path.Combine(di.Parent.FullName, name));
return; //done
}
}
public static class clsFile_Path
{
public static string KeyReg = "HKEY_LOCAL_MACHINE\\SOFTWARE\\ProjectTOR_ARSA\\DATA_LAB";
public static string KeyPathRun = "RunData";
public static string _PathDATA = TORServices.Properties.Settings.Default.PathData;
public static string FilterFile = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png" +
"|txt files (*.txt)|*.txt" +
"|Document files (*.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx, *.pdf )|*.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx, *.pdf " +
"|Audio/Vdio files (*.AVI, *.XVID, *.DivX *.3GP *.MKV *.MP4 *.FLV *.MP3 *.DAT)|*.AVI, *.XVID, *.DivX *.3GP *.MKV *.MP4 *.FLV *.MP3 *.DAT" +
"|All files (*.*)|*.*";
#region _File
public enum CopyFileOption{ Copy_File,Move_File}
public enum CopyAction { OverWrite,SkipFile,Rname}
public static void ReplaceStringInFile(string _File, string _Str, string _Replace) { System.IO.File.Move(_File, _File.Replace(_Str, _Replace));}
public static string RenameFile(string _File)
{
string stg = _File;
if (System.IO.File.Exists(_File))
{
int i = 1;
do
{
stg = System.IO.Path.GetDirectoryName(_File) + "\\" + System.IO.Path.GetFileNameWithoutExtension(_File) + "_" + i + "." + System.IO.Path.GetExtension(_File);
i++;
} while (System.IO.File.Exists(stg));
}
return stg;
}
public static void RenameFileByFolder(string pathSources, string pathTarget, string FileType = "*.*")
{
new System.Threading.Thread(RenameFileByFolder).Start(new object[] { pathSources, pathTarget, FileType });
}
public static void RenameFileByFolder(object obj)
{
string pathSources = (string)((object[])obj)[0];
string pathTarget = (string)((object[])obj)[1];
string FileType = (string)((object[])obj)[2];
System.Collections.Generic.Stack<string> stack = new System.Collections.Generic.Stack<string>();
stack.Push(pathSources);
while ((stack.Count > 0))
{
string dir = stack.Pop();
foreach (string file in System.IO.Directory.GetFiles(dir, FileType))
{
System.IO.File.Move(file, RenameFile(pathTarget + "\\" + System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(file)) + System.IO.Path.GetFileName(file)));
}
string directoryName = null;
foreach (string directoryName_loopVariable in System.IO.Directory.GetDirectories(dir))
{
directoryName = directoryName_loopVariable;
stack.Push(directoryName);
}
}
MessageBox.Show("Progress Complete...");
}
public static void DeleteFileAndFolder(string pathSources )
{
new System.Threading.Thread(RenameFileByFolder).Start(new object[] { pathSources });
}
public static void DeleteFileAndFolder(object obj)
{
string path = (string)((object[])obj)[0];
IWshRuntimeLibrary.FileSystemObject filesystem = new IWshRuntimeLibrary.FileSystemObject();
System.Collections.Generic.Stack<string> stack = new System.Collections.Generic.Stack<string>();
// System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
stack.Push(path);
while ((stack.Count > 0))
{
string dir = stack.Pop();
System.IO.DirectoryInfo dirs = new System.IO.DirectoryInfo(dir);
if (filesystem.GetFolder(dirs.FullName).Size <= 0)
{
try
{
dirs.Delete(true);
}
catch { dirs.MoveTo(System.IO.Path.GetTempPath() + "\\" + String.Format("{0:ddMMyyyyHHmmss}", DateTime.Now) + dirs.Name); }
System.Threading.Thread.Sleep(10);
}
else
{
foreach (string file in System.IO.Directory.GetFiles(dir, "*.*"))
{
if (filesystem.GetFile(file).Size <= 0)
{
System.IO.FileInfo _file = new System.IO.FileInfo(file);
try
{
_file.Delete();
}
catch { _file.MoveTo(System.IO.Path.GetTempPath() + "\\" + String.Format("{0:ddMMyyyyHHmmss}", DateTime.Now) + _file.Name); }
}
System.Threading.Thread.Sleep(10);
}
string directoryName = null;
foreach (string directoryName_loopVariable in System.IO.Directory.GetDirectories(dir))
{
directoryName = directoryName_loopVariable;
stack.Push(directoryName);
}
}
}
}
public static void OpenFile(string _Path, Boolean _Edit = false)
{
string FileOnTemp;
if (_Edit)
{
FileOnTemp = _Path;
}
else
{
FileOnTemp = System.IO.Path.GetTempPath() + "FileOnTemp" + string.Format("{0:ddMMyyyhhmmss}", DateTime.Now) + System.IO.Path.GetExtension(_Path);
System.IO.File.Copy(_Path, FileOnTemp);
}
System.Diagnostics.Process.Start(FileOnTemp);
}
public static void Copy_Move_File(string Filesource,string Filetarget, CopyFileOption cpo = CopyFileOption.Copy_File,CopyAction cpa = CopyAction.SkipFile)
{
string stg = Filetarget;
try
{
if (System.IO.File.Exists(Filetarget))
{
switch (cpa)
{
case CopyAction.SkipFile:
stg = Filetarget;
break;
case CopyAction.OverWrite:
stg = Filetarget;
File.Delete(Filetarget);
break;
case CopyAction.Rname:
stg = RenameFile(Filetarget);
break;
}
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
//@\ / : ; * ? " '< > |[]{}
public static string CreateFileName(string strFile)
{
string _strFile = strFile;
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(34)).ToString(), "");// "
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(39)).ToString(), "");// '
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(42)).ToString(), "");// *
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(47)).ToString(), "");// /
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(58)).ToString(), "");// :
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(59)).ToString(), "");// ;
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(60)).ToString(), "");// <
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(62)).ToString(), "");// >
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(63)).ToString(), "");// ?
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(64)).ToString(), "");// @
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(91)).ToString(), "");// [
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(92)).ToString(), "");// \
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(93)).ToString(), "");// ]
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(123)).ToString(), "");//{
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(124)).ToString(), "");//|
_strFile = _strFile.Replace(Convert.ToChar(Convert.ToByte(125)).ToString(), "");//}
return _strFile;
}
public static void DelEmptyFile(string _path)
{
System.Collections.Generic.List<string> lst = GetFilesRecursive(_path, "*.*");
IWshRuntimeLibrary.FileSystemObject filesystem = new IWshRuntimeLibrary.FileSystemObject();
foreach (string name in lst)
{
if (filesystem.GetFile(name).Size <= 0)
{
try
{
System.IO.File.Delete(name);
}
catch { }
}
}
MessageBox.Show("Del File Complete ....");
}
public static string SelectAndSaveFile(string _path, string ExtFile = "All files (*.*)|*.*")
{
frmFileCopy f = new frmFileCopy(); f.PathTarget = _path; f.ShowDialog(); return f._FileTarget;
}
public static string SelectFile(string _path, string ExtFile = "All files (*.*)|*.*")
{
string _F = "";
try
{
OpenFileDialog fb = new OpenFileDialog();
fb.ShowDialog();
_F = fb.FileName;
}
catch { }
return _F;
}
public static bool IsFileExcelOpen(string FileName)
{
try
{
Stream s = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
s.Close();
return true;
}
catch (Exception)
{
return false;
}
}
public static System.Collections.Generic.List<string> GetFilesRecursive(string initial, string _Extension)
{
System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>();
System.Collections.Generic.Stack<string> stack = new System.Collections.Generic.Stack<string>();
stack.Push(initial);
while ((stack.Count > 0))
{
string dir = stack.Pop();
string _ext = (_Extension.Substring(0, 1) != "*") ? "*" + _Extension : _Extension;
result.AddRange(System.IO.Directory.GetFiles(dir, _ext));
string directoryName = null;
foreach (string directoryName_loopVariable in System.IO.Directory.GetDirectories(dir))
{
directoryName = directoryName_loopVariable;
stack.Push(directoryName);
}
}
return result;
}
public static System.Collections.Generic.List<string> GetFilesRecursive(string initial, string[] _Extension )
{
System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>();
System.Collections.Generic.Stack<string> stack = new System.Collections.Generic.Stack<string>();
stack.Push(initial);
while ((stack.Count > 0))
{
string dir = stack.Pop();
foreach (string ext in _Extension)
{
string _ext = (ext.Substring(0, 1) != "*") ? "*" + ext : ext;
result.AddRange(System.IO.Directory.GetFiles(dir, _ext));
}
string directoryName = null;
foreach (string directoryName_loopVariable in System.IO.Directory.GetDirectories(dir))
{
directoryName = directoryName_loopVariable;
stack.Push(directoryName);
}
}
return result;
}
#endregion
#region _PathFolder
public static void DelEmptyFolder(string _path)
{
string[] array1 = System.IO.Directory.GetDirectories(_path);// so for each logical drive make this call
// Display all folders.
IWshRuntimeLibrary.FileSystemObject filesystem = new IWshRuntimeLibrary.FileSystemObject();
foreach (string name in array1)
{
if (filesystem.GetFolder(name).Size <= 0)
{
var testDirectories = System.IO.Directory.GetDirectories(name);
foreach (var directory in testDirectories)
{
System.IO.Directory.Delete(directory, true);
}
try
{
System.IO.Directory.Delete(name);
}
catch { }
}
}
MessageBox.Show("Del Folder Complete ....");
}
public static void DelFolderAndsubFolder(string _path,bool ShowMsg = true)
{
System.Collections.Generic.List<string> lst = GetFilesRecursive(_path, "*.*");
IWshRuntimeLibrary.FileSystemObject filesystem = new IWshRuntimeLibrary.FileSystemObject();
foreach (string name in lst)
{
{ try { System.IO.File.Delete(name); } catch { } }
}
DelEmptyFolder(_path);
System.IO.Directory.Delete(_path, true);
if (ShowMsg == true) { MessageBox.Show("Del Folder Complete ...."); }
}
public static string SelectFolder()
{
string _p = "";
try
{
System.Windows.Forms.FolderBrowserDialog fb = new FolderBrowserDialog();
fb.ShowDialog();
_p = fb.SelectedPath;
if (_p.Substring(_p.Length - 1) != "\\")
{
_p = _p + "\\";
}
}
catch { _p = ""; }
return _p;
}
public static void CreatePath(string _path)
{
if (!(System.IO.Directory.Exists(_path)))
{
System.Diagnostics.Process.Start("cmd.exe", "/c md " + Convert.ToChar(34) + _path + Convert.ToChar(34));
}
}
#endregion
public static System.Diagnostics.Process IsProcessOpen(string name)
{
foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
return clsProcess;
}
}
return null;
}
}
}
clsText.cs
Code (C#)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace TORServices
{
public static class clsINI
{
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int GetPrivateProfileString(string lpApplicationName, string lpKeyName, string lpDefault, global::System.Text.StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);
public static string ReadValue(string Path, string section, string key)
{
global::System.Text.StringBuilder sb = new global::System.Text.StringBuilder(255);
dynamic i = GetPrivateProfileString(section, key, "", sb, 255, Path);
return sb.ToString();
}
public static void WriteValue(string Path, string section, string key, string value) { WritePrivateProfileString(section, key, value, Path); }
public static string textFileReader(string pathFileName)
{
string line;
StreamReader fs;
try
{
fs = new StreamReader(pathFileName);
line = fs.ReadToEnd();
/* อ่าน Encode จาก String ที่อ่านมาได้จาก text file */
Encoding encodeSource = Encoding.GetEncoding(fs.CurrentEncoding.CodePage);
fs.Close();
//* ............ */
Encoding systemEncode = Encoding.Default;
Encoding targetEncode = encodeSource;
/* สั่ง getbyte array จาก string ที่เราอ่านมา */
byte[] srcData = systemEncode.GetBytes( line );
byte[] dstData;
/* ถ้าเป้น Encode ต่างกัน windows และ text file ให้ Convert byte array ไปเป็น text file encode */
if( targetEncode != systemEncode )
dstData = Encoding.Convert( systemEncode, targetEncode, srcData );
else
dstData = srcData;
/* convert bytearray ไปเป็น string ด้วย text file encode */
return targetEncode.GetString(dstData);
}
catch(Exception ex)
{
throw new IOException("cannot find " + pathFileName,ex);
}
}
public static System.Collections.Generic.List<string> textFileReaderFormline(string pathFileName)
{
System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
System.IO.StreamReader fs;
fs = new System.IO.StreamReader(pathFileName, System.Text.Encoding.GetEncoding(874));
string line;
while ((line = fs.ReadLine()) != null)
{
list.Add(line);
}
return list;
}
}
}
cntlSidTabControl.cs
Code (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace TORServices
{
#region _SidTabControl
public class cntlSidTabControl : System.Windows.Forms.TabControl
{
public void AddNewForm(Form form)
{
for (int i = 0; i < this.TabCount;i++ )
{
if (this.TabPages[i].Text == form.Text)
{
this.TabIndex = i;
return;
}
}
TabPage tab = new TabPage();
this.Controls.Add(tab);
form.TopLevel = false;
form.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left);
form.Dock = DockStyle.Fill;
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form.Parent = tab;
tab.Text = form.Text;
try { form.Show(); }
catch { }
this.SelectedTab = tab;
}
public cntlSidTabControl()
{
SetStyle(ControlStyles.DoubleBuffer, true);
TabStop = false;
DrawMode = TabDrawMode.OwnerDrawFixed;
_closeButtonBrush = new SolidBrush(_closeButtonColor);
ItemSize = new Size(ItemSize.Width, 24);
// used to expand the tab header, find a better way
Padding = new Point(16, 0);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stringFormat.Dispose();
_closeButtonBrush.Dispose();
}
base.Dispose(disposing);
}
public delegate void TabClosedDelegate(object sender, ClosedEventArgs e);
public delegate void TabClosingDelegate(object sender, ClosingEventArgs e);
public event TabClosedDelegate TabClosed;
public event TabClosingDelegate TabClosing;
private int _buttonWidth = 16;
[DefaultValue(16), Category("Action Buttons")]
public int ButtonWidth
{
get { return _buttonWidth; }
set { _buttonWidth = value; }
}
private int _crossOffset = 3;
[DefaultValue(3), Category("Action Buttons")]
public int CrossOffset
{
get { return _crossOffset; }
set { _crossOffset = value; }
}
private readonly StringFormat _stringFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Center
};
private Color _closeButtonColor = Color.Red;
private Brush _closeButtonBrush;
[Category("Action Buttons")]
public Color CloseButtonColor
{
get { return _closeButtonColor; }
set
{
_closeButtonBrush.Dispose();
_closeButtonColor = value;
_closeButtonBrush = new SolidBrush(_closeButtonColor);
Invalidate();
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Bounds != RectangleF.Empty)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
for (int nIndex = 0; nIndex < TabCount; nIndex++)
{
Rectangle tabArea = GetTabRect(nIndex);
Rectangle closeBtnRect = GetCloseBtnRect(tabArea);
if (nIndex != SelectedIndex)
{
e.Graphics.DrawRectangle(Pens.DarkGray, closeBtnRect);
DrawCross(e, closeBtnRect, Color.DarkGray);
}
else
{
//Drawing Close Button
e.Graphics.FillRectangle(_closeButtonBrush, closeBtnRect);
e.Graphics.DrawRectangle(Pens.White, closeBtnRect);
DrawCross(e, closeBtnRect, Color.White);
}
string str = TabPages[nIndex].Text;
e.Graphics.DrawString(str, Font, new SolidBrush(TabPages[nIndex].ForeColor), tabArea, _stringFormat);
}
}
}
private void DrawCross(DrawItemEventArgs e, Rectangle btnRect, Color color)
{
using (Pen pen = new Pen(color, 2))
{
float x1 = btnRect.X + CrossOffset;
float x2 = btnRect.Right - CrossOffset;
float y1 = btnRect.Y + CrossOffset;
float y2 = btnRect.Bottom - CrossOffset;
e.Graphics.DrawLine(pen, x1, y1, x2, y2);
e.Graphics.DrawLine(pen, x1, y2, x2, y1);
}
}
private Rectangle GetCloseBtnRect(Rectangle tabRect)
{
Rectangle rect = new Rectangle(tabRect.X + tabRect.Width - ButtonWidth - 4, (tabRect.Height - ButtonWidth) / 2, ButtonWidth, ButtonWidth);
return rect;
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (!DesignMode)
{
Rectangle rect = GetTabRect(SelectedIndex);
rect = GetCloseBtnRect(rect);
Point pt = new Point(e.X, e.Y);
if (rect.Contains(pt))
{
CloseTab(SelectedTab);
}
}
}
public void CloseTab(int tabindex)
{
CloseTab(TabPages[tabindex]);
}
public void CloseTab(TabPage tp)
{
ClosingEventArgs args = new ClosingEventArgs(TabPages.IndexOf(tp));
OnTabClosing(args);
//Remove the tab and fir the event tot he client
if (!args.Cancel)
{
// close and remove the tab, dispose it too
TabPages.Remove(tp);
OnTabClosed(new ClosedEventArgs(tp));
tp.Dispose();
}
}
protected void OnTabClosed(ClosedEventArgs e)
{
if (TabClosed != null)
{
TabClosed(this, e);
}
}
protected void OnTabClosing(ClosingEventArgs e)
{
if (TabClosing != null)
TabClosing(this, e);
}
}
//Some support classes:
public class ClosingEventArgs
{
private readonly int _nTabIndex = -1;
public ClosingEventArgs(int nTabIndex)
{
_nTabIndex = nTabIndex;
Cancel = false;
}
public bool Cancel { get; set; }
/// <summary>
/// Get/Set the tab index value where the close button is clicked
/// </summary>
public int TabIndex
{
get
{
return _nTabIndex;
}
}
}
public class ClosedEventArgs : EventArgs
{
private readonly TabPage _tab;
public ClosedEventArgs(TabPage tab)
{
_tab = tab;
}
/// <summary>
/// Get/Set the tab index value where the close button is clicked
/// </summary>
public TabPage Tab
{
get
{
return _tab;
}
}
}
#endregion
}
Tag : .NET, C#, VS 2012 (.NET 4.x), Windows
|
|
|
|
|
|
Date :
2015-09-18 09:30:39 |
By :
lamaka.tor |
View :
1808 |
Reply :
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
โค้ดเยอะมากครับ
มีเบอร์สั่งแก๊สแถมมาด้วย
|
|
|
|
|
Date :
2015-09-18 10:06:56 |
By :
fonfire |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
จัดไปครับ
|
|
|
|
|
Date :
2015-09-18 20:56:03 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 02
|