常用.net程序方法

//Get MultiLanguage
public static string GetLanguageString(string key)
        {           
            if (null == languageHT[SessionUtil.LoginUserLanguageID])
            {
                languageHT.Add(SessionUtil.LoginUserLanguageID, new Hashtable());
            }
            Hashtable languageStringHT = (Hashtable)languageHT[SessionUtil.LoginUserLanguageID];
            if (null == languageStringHT[key])
            {
                XmlDocument LanguageDoc = new XmlDocument(); //定義一個XmlDocument對象。
                LanguageDoc.Load(HttpContext.Current.Server.MapPath(LanguageXmlFilePath));

                XmlNode MeaasgeNode = LanguageDoc.SelectSingleNode("//Meaasge[ID='" + key + "']");
                languageStringHT.Add(key, MeaasgeNode.ChildNodes.Item(SessionUtil.LoginUserLanguageID).InnerText);
            }
            return languageStringHT[key].ToString();
        }

//Write log
public static void Write(string fileName, string messageID, string message, string userID)
        {
           
            String folder = ConstUtility.GetAppSettingsValue("LogOutputFolder");
            if (userID == null || userID.Equals(String.Empty))
            {
                userID = "UNKNOWN";
            }
       
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            StringBuilder filePath = new StringBuilder(folder);
            filePath.Append("//");
            filePath.Append(fileName);
            
            
            if (!File.Exists(filePath.ToString()))
            {
                using (StreamWriter sw = File.CreateText(filePath.ToString()))
                {
                    sw.WriteLine("{0} {1} {2} {3}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), userID, messageID, message);
                }
            }

            else
            {
                using (StreamWriter w = File.AppendText(filePath.ToString()))
                {
                    w.WriteLine("{0} {1} {2} {3}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), userID, messageID, message);
                }
            }
        }

//獲取HTTP請求信息並處理
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Collections.Specialized;
using System.Collections;


/// <summary>
/// Summary description for HelloWorldHandler
/// </summary>

public class HelloWorldHandler : IHttpHandler
{
    HttpRequest Request;
    HttpResponse Response;

    public HelloWorldHandler()
    {
    }


    public void ProcessRequest(HttpContext context)
    {
        Request = context.Request;
        Response = context.Response;

 

        //獲得請求的類型
        int loop1, loop2;
        NameValueCollection coll = Request.QueryString;
        String[] arr1 = coll.AllKeys;
        ArrayList list = new ArrayList();

        for (loop1 = 0; loop1 < arr1.Length; loop1++)
        {
            String[] arr2 = coll.GetValues(arr1[loop1]);
            for (loop2 = 0; loop2 < arr2.Length; loop2++)
            {
                list.Add(arr2[loop2]);
            }
        }

        if (arr1.Length > 1)
        {
            if (arr1[0].Equals("action") && arr1[1].Equals("user"))
            {
                //獲得請求的輸入流內容
                Stream str = Request.InputStream;

                //接收消息主體字符串
                string message = string.Empty;

                //獲得流長度
                int strlen = Convert.ToInt32(str.Length);

                //接收流的字節組
                byte[] arr = new byte[strlen];


                //解碼實體
                Encoding encoding = Encoding.GetEncoding("utf-8");

                //獲得字符組
                char[] car;

                string mobile = string.Empty;
                string para = string.Empty;

                switch (Convert.ToString(list[0]))
                {
                    //登錄
                    case "L1":
                        //讀入字節組
                        str.Read(arr, 0, strlen);
                        //獲得字符組
                        car = encoding.GetChars(arr);

                        //接收內容
                        message = new string(car);

                        mobile = Convert.ToString(list[1]);

                        try
                        {
                            //用戶存在且在職
                            if (IsValidUser(mobile).Equals(2))
                            {
                                string time = DateTime.Now.ToString("yyyyMMdd");// Date.ToString().Replace("0:00:00", "");
                                Response.Write(time);
                            }
                            //用戶存在且離職
                            else if (IsValidUser(mobile).Equals(1))
                            {
                                Response.Write("2");
                            }
                            //用戶不存在
                            else
                            {
                                Response.Write("1");
                            }
                        }
                        catch (Exception ex)
                        {
                            Response.Write("1");
                        }


                        break;
                    case "U1":

                        //讀入字節組
                        str.Read(arr, 0, strlen);
                        //獲得字符組
                        car = encoding.GetChars(arr);

                        //接收內容
                        message = new string(car);

                        mobile = Convert.ToString(list[1]);
                        if (IsValidMobile(mobile))
                        {
                            //解析並插入數據
                            try
                            {
                                if (GetMessage(message, mobile).Equals(1))
                                {
                                    Response.Write("0");
                                }
                                else
                                {
                                    Response.Write("1");
                                }
                            }
                            catch (Exception ex)
                            {
                                Response.Write("1");
                            }
                        }
                        else
                        {
                            Response.Write("1");
                        }

                        break;

                    //獲得競爭對手信息
                    case "U2":

                        //解析字節流
                        try
                        {
                            //讀入字節組
                            str.Read(arr, 0, strlen);

                            //圖片路徑
                            string picPath = string.Empty;

                            if (strlen > 1)
                            {
                                if (Convert.ToInt32(arr[0]).Equals(0))//無圖片
                                {
                                    //獲得字符組
                                    car = encoding.GetChars(arr, 1, strlen - 1);

                                    //接收內容
                                    message = new string(car);
                                }
                                else if (Convert.ToInt32(arr[0]).Equals(1))//有圖片
                                {
                                    int count = BitConverter.ToInt32(arr, 1);

                                    //獲得字符組
                                    car = encoding.GetChars(arr, 5, count);

                                    //接收內容
                                    message = new string(car);

                                    //存儲圖片數組
                                    byte[] pictureArr = new byte[strlen - 5 - count];

                                    Array.Copy(arr, 5 + count, pictureArr, 0, strlen - 5 - count);

                                    //圖片路徑
                                    picPath = DateTime.Now.ToString("yyyyMMddHHmms") + ".jpeg";

                                    //保存圖片
                                    string path = Request.MapPath("~" + "/UI/CompetitorImg/") + picPath;

                                    System.IO.FileStream fs = System.IO.File.Create(path);

                                    fs.Write(pictureArr, 0, pictureArr.Length);

                                    fs.Close();

                                }
                                else
                                {
                                    Response.Write("8");
                                }
                                mobile = Convert.ToString(list[1]);

                                if (IsValidMobile(mobile))
                                {
                                    //解析並插入數據


                                    if (GetCompetitionMessage(message, mobile, picPath).Equals(1))
                                    {
                                        Response.Write("0");
                                    }
                                    else
                                    {
                                        Response.Write("1");
                                    }

                                }
                                else
                                {
                                    Response.Write("1");
                                }


                            }
                            else
                            {
                                Response.Write("9");
                            }
                        }
                        catch (Exception ex)
                        {
                            Response.Write("1");
                        }

                        break;

                    case "D1":
                        if (arr1.Length.Equals(3))
                        {
                            if (arr1[2].Equals("para"))
                            {
                                mobile = Convert.ToString(list[1]);
                                para = Convert.ToString(list[2]);
                                Response.Write("Mobile is: " + mobile);
                                Response.Write("Para is: " + para);
                            }
                        }

                        break;
                }
            }
        }

        //Response.Write("</body>");
        //Response.Write("</html>");


    }

    //解析數據
    private int GetMessage(string message, string mobile)
    {


        //消息數組
        string[] info = message.Split(new Char[] { ';' });

        //電話
        string mobileNo = mobile;

        if (info.Length > 3)
        {

            //個數
            int count = Convert.ToInt32(info[0]);

            string time = info[1].Substring(0, 4) + "-" + info[1].Substring(4, 2) + "-" + info[1].Substring(6, 2);
            //日期
            DateTime date = Convert.ToDateTime(time);

            //商品型號
            string pCode = string.Empty;

            //銷售數量
            int qTY = 0;

            //是否結束
            int flag = 1;

            //發送成功標誌
            int succ = 1;

            for (int i = 2; i < info.Length - 1; i++)
            {
                string[] detail = info[i].Split(new Char[] { ',' });

                //判斷是否最後一個
                if (i.Equals(info.Length - 2))
                {
                    if (detail.Length > 1)
                    {
                        pCode = detail[0];

                        qTY = Convert.ToInt32(detail[1]);

                        succ = InsertTable(mobile, date, count, pCode, qTY, 0);
                        if (succ.Equals(1))
                        {
                            return 1;//插入成功
                        }
                    }
                }
                else
                {

                    if (detail.Length > 1)
                    {
                        pCode = detail[0];

                        qTY = Convert.ToInt32(detail[1]);

                        InsertTable(mobile, date, count, pCode, qTY, flag);
                    }
                }

            }


        }
        return 0;//失敗
    }

    //驗證手機號
    private bool IsValidMobile(string mobile)
    {
        return new FacadeInterface().HaveMobilePhone(mobile);
    }

    //插入臨時表
    private int InsertTable(string mobile, DateTime date, int count, string proCode, int qTY, int flag)
    {
        return new FacadeInterface().InsertTable(mobile, date, count, proCode, qTY, flag);
    }

    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }

    //驗證用戶
    private int IsValidUser(string mobile)
    {
        return new FacadeInterface().IsSaleAssistant(mobile);
    }

    //解析競爭對手信息
    private int GetCompetitionMessage(string message, string mobile, string picPath)
    {
        //消息數組
        string[] info = message.Split(new Char[] { '#' });

        if (info.Length.Equals(5))
        {
            return InsertCompetition(mobile, info[0], info[1], Convert.ToDecimal(info[2]), info[3], picPath);
        }
        else
        {
            return 0;
        }
        //插入失敗
        return 0;
    }

    //插入競爭對手錶
    private int InsertCompetition(string mobile, string competitionName, string productName, decimal price, string remark, string picturePath)
    {
        //
        return new FacadeInterface().InsertCompetition(competitionName, productName, price, remark, mobile, picturePath);
    }
}


        /// 讀取Excel文件,並將讀入的記錄插入到懸案表中        
        public void InsertXuanAnFromExcel(ParameterT010B paraT010B)
        {
            //打開excel文件
            OleDbConnection Excelconn =
               new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + paraT010B.ImportFilePath + "';Extended Properties='Excel 8.0;HDR=NO;IMEX=1'" + ";");
            System.Data.OleDb.OleDbCommand cmd = null;
            System.Data.OleDb.OleDbDataReader rdr = null;

            try
            {
                //打開excel
                Excelconn.Open();
                cmd = Excelconn.CreateCommand();

                //共有幾個Sheet
                DataTable dt = Excelconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
               
                int Sheetnum = dt.Rows.Count;

                //彈出錯誤消息
                string message = string.Empty;

                //記錄是否新增成功
                bool succ = false;

                //讀取每個sheet
                for (int i = 0; i < Sheetnum; i++)
                {
                    //獲取文件中的sheet名稱
                    string sheetName = dt.Rows[i][2].ToString().Trim();

                    string newName = sheetName.Substring(0, sheetName.IndexOf("$")+2);

                    //.Print_Area,除去打印區域
                    if (sheetName.Trim().Equals(newName.Trim()))
                    {
                        cmd.CommandText = "SELECT * FROM " + "[" + sheetName + "]";
                       
                        rdr = cmd.ExecuteReader();
                       
                        rdr.Read();
                       
                        //記錄當前行
                        int countRow = 1;

                        //從第二行還是讀取
                        while (rdr.Read())
                        {
                            countRow++;

                            //如果一行都爲空,則返回執行下一行
                            if (rdr.GetValue(0).ToString().Trim().Equals(string.Empty) && rdr.GetValue(1).ToString().Trim().Equals(string.Empty) && rdr.GetValue(2).ToString().Trim().Equals(string.Empty) && rdr.GetValue(3).ToString().Trim().Equals(string.Empty) && rdr.GetValue(4).ToString().Trim().Equals(string.Empty) && rdr.GetValue(5).ToString().Trim().Equals(string.Empty) && rdr.GetValue(6).ToString().Trim().Equals(string.Empty) && rdr.GetValue(7).ToString().Trim().Equals(string.Empty))
                            {
                                continue;
                            }
                           
                            //CustomerNo 
                            if (rdr.GetValue(0).ToString().Trim() != string.Empty)
                            {
                                paraT010B.CustomerNO = rdr.GetValue(0).ToString().Trim();   
                            }
                            else
                            {
                                paraT010B.CustomerNO = null;
                            }

                            //Proposer 
                            if (rdr.GetValue(1).ToString().Trim() != string.Empty)
                            {
                                paraT010B.Presenter = rdr.GetValue(1).ToString();
                            }
                            else
                            {
                                message += "第"+countRow+"行中,單元格2不能爲空!";
                                continue;//執行下一行
                            }

                            //ProposerDate
                            if (rdr.GetValue(2).ToString() != string.Empty)
                            {
                                try
                                {
                                    DateTime presentTime = ConvertExcelDateToDate(rdr.GetValue(2).ToString());

                                    paraT010B.PresentTime = presentTime;
                                }
                                catch
                                {
                                    message += "第" + countRow + "行中,單元格3格式不對!";
                                    continue;//執行下一行
                                }
                            }
                            else
                            {
                                message += "第" + countRow + "行中,單元格3格式不對!";
                                continue;//執行下一行
                            }

                            //DeadLineDate
                            if (rdr.GetValue(3).ToString() != string.Empty)
                            {
                                try
                                {
                                    DateTime deadline = ConvertExcelDateToDate(rdr.GetValue(3).ToString());

                                    paraT010B.Deadline = deadline;
                                }
                                catch
                                {
                                    message += "第" + countRow + "行中,單元格4格式不對!";
                                    continue;//執行下一行
                                }
                            }
                            else
                            {
                                message += "第" + countRow + "行中,單元格4格式不對!";
                                continue;//執行下一行
                            }
                           
                            //Module
                            if (!rdr.GetValue(4).ToString().Equals(string.Empty))
                            {
                                paraT010B.ModuleID = Convert.ToInt32(rdr.GetValue(11));
                            }
                            else
                            {
                                message += "第" + countRow + "行中,單元格5不能爲空!";
                                continue;//執行下一行
                            }

                            //IssueType
                            if (!rdr.GetValue(5).ToString().Equals(string.Empty))
                            {
                                paraT010B.ReportTypeID = Convert.ToInt32(rdr.GetValue(12));
                            }
                            else
                            {
                                message += "第" + countRow + "行中,單元格6不能爲空!";
                                continue;//執行下一行
                            }

                            //Topic
                            if (rdr.GetValue(6).ToString().Trim() != string.Empty)
                            {
                                paraT010B.Subject = rdr.GetValue(6).ToString();
                            }
                            else
                            {
                                paraT010B.Subject = null;
                                message += "第" + countRow + "行中,單元格7不能爲空!";
                                continue;//執行下一行
                            }

                            //Details
                            if (rdr.GetValue(7).ToString().Trim() != string.Empty)
                            {
                                paraT010B.Content = rdr.GetValue(7).ToString();
                            }
                            else
                            {
                                paraT010B.Content = null;
                            }

                            //插入新建的懸案
                            InsertXuanAnRecord(paraT010B);
                            succ = true;
                        }
                        rdr.Close();
                    }
                }
                if (message != string.Empty)
                {
                    DeException dex = new DeException();
                    dex.Msg = "批量上載出錯:"+message;
                    throw dex;
                }
                else if (message == string.Empty && succ)
                {
                    DeException dex = new DeException();
                    dex.Msg = "批量上載成功!";
                    throw dex;
                }
                else
                {
                    DeException dex = new DeException();
                    dex.Msg = "批量上載失敗,請檢查要上載的數據!";
                    throw dex;
                }
            }
            catch (DeException dex)
            {
                //拋出異常
                throw dex;
            }
            catch (Exception ex)
            {
                //拋出異常
                throw new DeException(GetType().Name, ex.ToString(), MessageType.SystemError);
            }
        finally
        {
            //關閉連接
            //rdr.Close();
            Excelconn.Close();
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章