K3调用登录界面

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using k3Login;
using System.Data.SqlClient;
using System.Threading;
using System.Data;
using System.IO;

namespace CBCalcSys
{
    
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        
        public static void Main()
        {
            //原程序入口                
            //验证通过
            bool runone;
            System.Threading.Mutex run = new System.Threading.Mutex(true, "K/3Help", out runone);
            if (runone)
            {
                run.ReleaseMutex();
                //现在程序入口                
                loadMain();
            }
            else
            {
                loadMain();
            }
        }
        private static IniFiles ini = new IniFiles("config.ini");
        /// <summary>
        /// 加载帐套
        /// </summary>
        /// <param name="uesrNameTemp"></param>
        /// <param name="login1"></param>
        public static void loadMain()
        {
            string[] uesrNameTemp = null;
            ClsLoginClass login1 = new ClsLoginClass();

            if (login1.CheckLogin())
            {
                //Thread.Sleep(1000);
                try
                {
                    string connString = getConnection(login1.PropsString);  //获得K3连接字符串
                    string conn = login1.PropsString;
                    //ini.WriteString("链接字符串", "wid", conn);
                    //MessageBox.Show(conn);
                    //ini.WriteString("链接字符串", "wid1", connString);
                    uesrNameTemp = login1.PropsString.Split(';');//分割字符串
                    uesrNameTemp[5] = uesrNameTemp[5].Substring(0, uesrNameTemp[5].Length - 1);

                    DBHelper.InitConn(connString);          //初始化连接
                    DBHelper.cyName = getUser(uesrNameTemp[6]);  //获得用户名
                    //ini.WriteString("链接字符串", "wid", connString);
                    connString = uesrNameTemp[4] + ";" + uesrNameTemp[5] + ";" + uesrNameTemp[2] + ";" + uesrNameTemp[3];        //获得连接字符串
                    DBHelper.strConn = connString;

                    DBHelper.conn = new SqlConnection(connString);  //连接初始化

                    Application.Run(new MainForm());
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }finally{
                    Application.Run(new MainForm());
                }

            }
        }
        /// <summary>
        /// 获得次数
        /// </summary>
        private static bool getTime()
        {
            DBHelper.JieMi(DBHelper.strurl, @"d:\1-1.lcl");
            bool vali = false;
            string sql = string.Format("select Fnum,Fdate from t_key where FitemID=1");
            DataTable dt=DBHelper.QueryOle(sql).Tables[0];
            DBHelper.Fnum = Convert.ToInt32(dt.Rows[0][0]);
            DBHelper.FDate = Convert.ToDateTime(dt.Rows[0][1]);
            sql = "select getDate()";

            DBHelper.FSDate = Convert.ToDateTime(DBHelper.ExecuteScalar(sql));
            DBHelper.Fnum--;
            if (DBHelper.Fnum < 10 || DBHelper.FSDate > DBHelper.FDate)
            {
                vali= false;
            }else{
                sql = string.Format("update t_key set FNum=" + DBHelper.Fnum +" where FitemID=1");
                DBHelper.DoUpdate1(sql);
                vali=true;
            }

            DBHelper.JiaMi(DBHelper.strurl, @"d:\1-1.lcl");
            return vali;
        }
        /// <summary>
        /// 获得连接字符串
        /// </summary>
        /// <param name="cnStr"></param>
        /// <returns></returns>
        public static string getConnection(string cnStr)
        {
            int i, j;
            i = cnStr.IndexOf('{')+1;
            j = cnStr.IndexOf('}');
            cnStr = cnStr.Substring(i, j - i);
            return cnStr;
        }
        /// <summary>
        /// 获得SQLConnection连接字符串
        /// </summary>
        /// <param name="cnStr"></param>
        /// <returns></returns>
        public static string getConnection1(string cnStr)
        {
            int i, j;
            i = cnStr.IndexOf(';') + 1;
            j=cnStr.Length;
            cnStr = cnStr.Substring(47, j - 47);
            
            string str1 = cnStr.Substring(0,24);
            string str2 = cnStr.Substring(25);
            cnStr = str2+";"+ str1;
            return cnStr;
        }
        /// <summary>
        /// 获得登录的用户名
        /// </summary>
        /// <param name="cnStr"></param>
        /// <returns></returns>
        private static string getName(string cnStr)
        {
            int i, j;
            i = cnStr.IndexOf('}');
           
            string str1 = cnStr.Substring(i+11);
            i = str1.IndexOf(';');
            str1 = str1.Substring(0,i);
            return str1;
        }
        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <param name="cnStr"></param>
        /// <returns></returns>
        private static string getUser(string cnStr)
        {
            string str1 = cnStr.Substring(9);
            return str1;
        }
        /// <summary>
        /// 获得会计期间 及其年月
        /// </summary>
        private static void getDate()
        {
            string sql = "select fvalue from t_systemprofile where  (fkey='CurrentPeriod' and fcategory ='IC') or (fcategory ='IC' and fkey='CurrentYear') order by fvalue";
            DataTable dt = DBHelper.Query(sql).Tables[0];
            DBHelper.dMonth=dt.Rows[0][0].ToString();
            DBHelper.dYear = dt.Rows[1][0].ToString();
            sql = "select FStartDate,FEndDate from T_PeriodDate where FPeriod=" + DBHelper.dMonth + " and fyear=" + DBHelper.dYear + "";
            dt = DBHelper.Query(sql).Tables[0];
            DBHelper.fromDate = dt.Rows[0][0].ToString();
            DBHelper.toDate = dt.Rows[0][1].ToString();

        }
        /*
         * 查看帐套某月始末日期
         * select FStartDate,FEndDate from T_PeriodDate where FPeriod=12 and fyear=2011
         * 
         *     '账套名称
    Rs1.Open "select fvalue from t_systemprofile where fcategory ='General' and fkey='CompanyName'", Public_cn
    If Rs1.RecordCount > 0 Then
        Pub_CompanyName = Trim(Rs1.Fields("fvalue"))
    End If
    '会计年度
    Set Rs1 = Nothing
    Rs1.Open "select fvalue from t_systemprofile where fcategory ='IC' and fkey='CurrentYear'", Public_cn
    If Rs1.RecordCount > 0 Then
        Pub_CurrentYear = Trim(Rs1.Fields("fvalue"))
    End If
    '会计期间
    Set Rs1 = Nothing
    Rs1.Open "select fvalue from t_systemprofile where fcategory ='IC' and fkey='CurrentPeriod'", Public_cn
    If Rs1.RecordCount > 0 Then
        Pub_CurrentPeriod = Trim(Rs1.Fields("fvalue"))
    End If
         */
    }
        
}
using System;
using System.Collections.Generic;
using System.Text;
using ADODB;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Security.Cryptography;
using System.Data.OleDb;
using System.Collections;

namespace CBCalcSys
{
    class DBHelper
    {
        public static int Fnum = 0;//软件可用的次数
        public static DateTime FDate = Convert.ToDateTime("2050-03-02");
        public static DateTime FSDate = System.DateTime.Now;
        public static Recordset rs=new Recordset();
        public static ADODB.Connection connDB = new ADODB.Connection();
        public static string strConn="";
        public static SqlConnection conn = null; //数据库连接字符串
        public static string strCPNum=null;     //产成品代码
        public static string cyName = null;   //公司名称
        public static bool load = false;  //判断是否加载信息
        public static string SearchSql = "";//判断条件
        public static bool valiRun = false;//判断程序运行
        public static string fromDate = "";
        public static string toDate = "";
        public static string dYear = "";
        public static string dMonth = "";
        public static string strurl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\Inter.dll";
        public static string strtourl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\linshi.dll";
        public static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Inter.dll;Jet OLEDB:Database Password=whwdgjlclong";
        public static OleDbConnection connection = new OleDbConnection(connectionString);
        public static string[] vsling = new string[32];
        public static bool valiLoading = false;//判断程序运行

        /// <summary>
        /// 解密判断
        /// </summary>
        /// <returns></returns>
        public static int JieMiPro()
        {
            int m = -1;
            bool projectlist = File.Exists(strurl);
            if (projectlist == true)
            {
                try
                {
                    JieMi(strurl, strtourl);
                    m = 1;
                }
                catch
                {
                    JiaMi(strurl, strtourl);
                    JieMi(strurl, strtourl);
                    m = 1;
                }
            }
            else
            { m = -1; }
            return m;
        }

        /// <summary>
        /// 加密判断
        /// </summary>
        /// <returns></returns>
        public static int JiaMiPro()
        {
            int m = -1;
            bool projectlist = File.Exists(strurl);
            if (projectlist == true)
            {
                try
                {
                    string str = "select * from tab_LineType";
                    Query(str);

                    JiaMi(strurl, strtourl);
                    m = 1;
                }
                catch
                {

                    JieMi(strurl, strtourl);
                    JiaMi(strurl, strtourl);
                    m = 1;
                }

            }
            else
            {
                m = -1;
            }
            return m;
        }
        #region 新加密解密
        private const ulong FC_TAG = 0xFC010203040506CF;
        private const int BUFFER_SIZE = 128 * 1024;
        /// <summary>
        /// 检验两个Byte数组是否相同
        /// </summary>
        /// <param name="b1">Byte数组</param>
        /// <param name="b2">Byte数组</param>
        /// <returns>true-相等</returns>
        private static bool CheckByteArrays(byte[] b1, byte[] b2)
        {
            if (b1.Length == b2.Length)
            {
                for (int i = 0; i < b1.Length; ++i)
                {
                    if (b1[i] != b2[i])
                        return false;
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 创建Rijndael SymmetricAlgorithm
        /// </summary>
        /// <param name="password">密码</param>
        /// <param name="salt"></param>
        /// <returns>加密对象</returns>
        private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);

            SymmetricAlgorithm sma = Rijndael.Create();
            sma.KeySize = 256;
            sma.Key = pdb.GetBytes(32);
            sma.Padding = PaddingMode.PKCS7;
            return sma;
        }
        /// <summary>
        /// 加密文件随机数生成
        /// </summary>
        private static RandomNumberGenerator rand = new RNGCryptoServiceProvider();
        /// <summary>
        /// 生成指定长度的随机Byte数组
        /// </summary>
        /// <param name="count">Byte数组长度</param>
        /// <returns>随机Byte数组</returns>
        private static byte[] GenerateRandomBytes(int count)
        {
            byte[] bytes = new byte[count];
            rand.GetBytes(bytes);
            return bytes;
        }
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="inFile">待加密文件</param>
        /// <param name="outFile">加密后输入文件</param>
        /// <param name="password">加密密码</param>
        public static void EncryptFile(string inFile, string outFile)
        {
            string password = "123";
            using (FileStream fin = File.OpenRead(inFile),
                fout = File.OpenWrite(outFile))
            {
                long lSize = fin.Length; // 输入文件长度
                int size = (int)lSize;
                byte[] bytes = new byte[BUFFER_SIZE]; // 缓存
                int read = -1; // 输入文件读取数量
                int value = 0;

                // 获取IV和salt
                byte[] IV = GenerateRandomBytes(16);
                byte[] salt = GenerateRandomBytes(16);

                // 创建加密对象
                SymmetricAlgorithm sma = CreateRijndael(password, salt);
                sma.IV = IV;

                // 在输出文件开始部分写入IV和salt
                fout.Write(IV, 0, IV.Length);
                fout.Write(salt, 0, salt.Length);

                // 创建散列加密
                HashAlgorithm hasher = SHA256.Create();
                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                    chash = new CryptoStream(System.IO.Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    BinaryWriter bw = new BinaryWriter(cout);
                    bw.Write(lSize);

                    bw.Write(FC_TAG);
                    // 读写字节块到加密流缓冲区
                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        cout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                    }
                    // 关闭加密流
                    chash.Flush();
                    chash.Close();
                    // 读取散列
                    byte[] hash = hasher.Hash;

                    // 输入文件写入散列
                    cout.Write(hash, 0, hash.Length);
                    // 关闭文件流
                    cout.Flush();
                    cout.Close();
                }
            }
        }
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="inFile">待解密文件</param>
        /// <param name="outFile">解密后输出文件</param>
        /// <param name="password">解密密码</param>
        public static void DecryptFile(string inFile, string outFile)
        {
            string password = "123";
            // 创建打开文件流
            using (FileStream fin = File.OpenRead(inFile),
                fout = File.OpenWrite(outFile))
            {
                int size = (int)fin.Length;
                byte[] bytes = new byte[BUFFER_SIZE];
                int read = -1;
                int value = 0;
                int outValue = 0;
                byte[] IV = new byte[16];
                fin.Read(IV, 0, 16);
                byte[] salt = new byte[16];
                fin.Read(salt, 0, 16);

                SymmetricAlgorithm sma = CreateRijndael(password, salt);
                sma.IV = IV;
                value = 32;
                long lSize = -1;

                // 创建散列对象, 校验文件
                HashAlgorithm hasher = SHA256.Create();
                using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                    chash = new CryptoStream(System.IO.Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    // 读取文件长度
                    BinaryReader br = new BinaryReader(cin);
                    lSize = br.ReadInt64();
                    ulong tag = br.ReadUInt64();

                    if (FC_TAG != tag)
                        throw new CryptoHelpException("文件被破坏");

                    long numReads = lSize / BUFFER_SIZE;
                    long slack = (long)lSize % BUFFER_SIZE;

                    for (int i = 0; i < numReads; ++i)
                    {
                        read = cin.Read(bytes, 0, bytes.Length);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                        outValue += read;
                    }
                    if (slack > 0)
                    {
                        read = cin.Read(bytes, 0, (int)slack);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value += read;
                        outValue += read;
                    }
                    chash.Flush();
                    chash.Close();
                    fout.Flush();
                    fout.Close();
                    byte[] curHash = hasher.Hash;
                    // 获取比较和旧的散列对象
                    byte[] oldHash = new byte[hasher.HashSize / 8];
                    read = cin.Read(oldHash, 0, oldHash.Length);
                    if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                        throw new CryptoHelpException("文件被破坏");
                }
                if (outValue != lSize)
                    throw new CryptoHelpException("文件大小不匹配");
            }
        }
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="fromUrl">要加密的文件地址</param>
        /// <param name="toUrl">临时地址</param>
        public static void JiaMi(string fromUrl, string toUrl)
        {
            //执行文件加密
            try
            {
                EncryptFile(fromUrl, toUrl);
                File.Delete(fromUrl);
                File.Move(toUrl, fromUrl);
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                File.Delete(toUrl);
            }
        }
        /// <summary>
        /// 解密算法
        /// </summary>
        /// <param name="fromUrl">要解密的文件地址</param>
        /// <param name="toUrl">临时地址</param>
        public static void JieMi(string fromUrl, string toUrl)
        {
            try
            {
                //解密文件
                DecryptFile(fromUrl, toUrl);
                File.Delete(fromUrl);
                File.Move(toUrl, fromUrl);
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                File.Delete(toUrl);
            }
        }
        #endregion

        public static  void InitConn(string cnStr)
        {            
            connDB.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
            connDB.ConnectionString = cnStr;
            connDB.Open();
        }
        public static void CloseConn()
        {
            connDB.Close();
        }
        /// <summary>
        /// 测试是否存在字段
        /// </summary>
        public static void TestConn()
        {
            Object j;
            try
            {
                connDB.Execute("Alter table t_ICItemCore add FjsPrice decimal(18, 10),FcbPrice decimal(18, 10)", out j, -1);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 保留小数位数
        /// </summary>
        /// <returns></returns>
        public static string getNumP(string str,int j)
        {
            decimal strN=0;
            try
            {
                strN = Convert.ToDecimal(str);
                strN = Math.Round(strN, j);
            }
            catch (Exception)
            {
            }
            return strN.ToString();
        }
        /// <summary>
        /// 更新表
        /// </summary>
        /// <param name="myConn">连接SQLConnection</param>
        /// <param name="sql">SQL语句</param>
        /// <param name="myTableName">表名称</param>
        /// <param name="ds1"></param>
        /// <returns></returns>
        public static DataSet SelectSqlSrvRows(string sql, DataSet ds1)
        {
            DataSet ds = new DataSet();
            try
            {
                SqlDataAdapter myDataAdapter = new SqlDataAdapter();
                myDataAdapter.SelectCommand = new SqlCommand(sql, conn);
                SqlCommandBuilder cb = new SqlCommandBuilder(myDataAdapter);
                conn.Open();
                myDataAdapter.Fill(ds, "ds");
                myDataAdapter.Update(ds1, "ds");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }

        /// <summary>    
        /// 执行查询语句,返回DataSet    
        /// </summary>    
        /// <param name="SQLString">查询语句</param>    
        /// <returns>DataSet</returns>    
        public static DataSet Query(string SQLString)
        {
            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                SqlDataAdapter command = new SqlDataAdapter(SQLString, conn);
                command.Fill(ds, "ds");
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return ds;            
        }
        /// <summary>    
        /// 执行查询语句,返回int   
        /// </summary>    
        /// <param name="SQLString">查询语句</param>    
        /// <returns>相应数目</returns>    
        public static object ExecuteScalar(string SQLString)
        {
            object num = 0;
            try
            {
                conn.Open();
                SqlCommand command = new SqlCommand(SQLString, conn);
                num = (object)command.ExecuteScalar();
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return num;            
        }
        /// <summary>
        /// "更新"数据库
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool DoUpdate(string sql,OleDbConnection conn)
        {
            //执行文件解密
            OleHelperL.JieMi(strurl, @"d:\1-1.lcl");
            OleDbCommand comm = new OleDbCommand(sql, conn);
            try
            {
                conn.Open();
                int result = comm.ExecuteNonQuery();
                if (result == 1)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
            }
            finally
            {
                conn.Close();
                //执行文件加密
                OleHelperL.JiaMi(strurl, @"d:\1-1.lcl");
            }
            return false;
        }
        /// <summary>    
        /// 执行查询语句,返回DataSet    
        /// </summary>    
        /// <param name="SQLString">查询语句</param>    
        /// <returns>DataSet</returns>    
        public static DataSet QueryOle(string SQLString)
        {

            DataSet ds = new DataSet();
            try
            {
                connection.Open();
                OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
                command.Fill(ds, "ds");
            }
            catch (System.Data.OleDb.OleDbException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return ds;

        }
        /// <summary>
        /// "更新"数据库
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool DoUpdate1(string sql)
        {
            //执行文件解密

            OleDbCommand comm = new OleDbCommand(sql, connection);
            try
            {
                connection.Open();
                int result = comm.ExecuteNonQuery();
                if (result == 1)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }

            return false;
        }
    }
}
posted @ 2012-08-03 16:33  辣椒粉  阅读(1487)  评论(0编辑  收藏  举报