我的程序我做主
~天~注~定~
posts - 5,comments - 44,trackbacks - 0

在网上看到些这方面的函数 但都觉得过于复杂 于是便自己写了一套 精度不高到亿 大家可以自己扩展


        public static string fnConvertToBig(string MoneyValue)
        {
            if (MoneyValue == "") return "";
            string mMinus = "";
            if (MoneyValue.StartsWith("-")) { mMinus = "负"; MoneyValue = MoneyValue.Substring(1, MoneyValue.Length - 1); }
            string[] getBit = new string[] { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿" };
            string[] getToh = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            string strTemp = "";
            string strValue = "";

                while (MoneyValue.Substring(MoneyValue.Length - 1, 1) == "0")
                {
                    MoneyValue = MoneyValue.Substring(0, MoneyValue.Length - 1);
                    if (MoneyValue == "") return "";
                }
                if (MoneyValue.Substring(MoneyValue.Length - 1, 1) == ".") MoneyValue = MoneyValue.Substring(0, MoneyValue.Length - 1);
                if (MoneyValue == "") return "";

                int iLen = (MoneyValue.IndexOf(".") < 0) ? MoneyValue.Length + 1 : MoneyValue.IndexOf(".") + 1;
                for (int i = 0; i < MoneyValue.Length; i++)
                {
                    strTemp = MoneyValue.Substring(i, 1);
                    if (strTemp == ".") continue;

                    if (i < MoneyValue.Length - 1)
                        if (strTemp == "0" && MoneyValue.Substring(i + 1, 1) == "0" && iLen != 6) { iLen--; continue; }

                    if ((iLen == 2 || iLen == 6) && strTemp == "0")
                        strValue += getBit[iLen];
                    else if (strTemp == "0")
                        strValue += getToh[Convert.ToInt16(strTemp)];
                    else
                        strValue += getToh[Convert.ToInt16(strTemp)] + getBit[iLen];

                    iLen--;
                }
                if (strValue.EndsWith("元")) strValue += "整";

            return mMinus + strValue;
        }

posted @ 2007-06-28 16:52 王学军 阅读(122) 评论(2) 编辑

这个是我写的公用函数,它将DataTable中的数据直接显示到GridView中,GV拖过来后不需要任何设置

我这个函数有几个强大的功能,一般DT中的数据是从存储过程中取出来的,有时因为各种显示的需求,
所以需要做不同的设置,
如有一个表table中有列id,name,age,address,money,car
存储过程中这样写:
select id,name as '姓名',age as '年龄',address as '地址',money as 'Sum存款',car as 'Hide车牌号'
注意:
1.别名用中文名,因为GV中的列名就是这个名字
2.别名前加一些特殊字符,表示不同的意义,如Sum表示要对这列求和,Hide表示不显示这列

我目前开发的意义有:
Sum 求和  Hide隐藏 Fixed固定列 Last置为最后一列  

最后说明一个功能:
ShowTotal  为真表示不显示下面的求和Footer,而是自动产生一行记录叫“总计”,并在这行里求和 如果不懂自己试试就明白了

       public void GridViewShowTable(GridView gv, DataTable dt,bool ShowTotal )
        {
            if (ShowTotal && dt.Columns.Count > 0)
            {
                bool showTotal = false;
                bool showTitle = false;
                DataRow dr = dt.NewRow();
                dr[0] = Guid.Empty;
                for (int i = 1; i < dt.Columns.Count; i++)
                {
                    string colName = dt.Columns[i].ColumnName;
                    if (colName.IndexOf("Sum") >= 0)
                    {
                        decimal tmpDec = 0;
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (dt.Rows[j][colName] != Convert.DBNull)
                                tmpDec += Convert.ToDecimal(dt.Rows[j][colName]);
                        }
                        dr[colName] = tmpDec;
                        showTotal = true;
                    }
                    else
                    {
                        if (!showTitle && dt.Columns[i].DataType == Type.GetType("System.String"))
                        {
                            dr[colName] = "总计 (共" + dt.Rows.Count.ToString() + "条)";
                            showTitle = true;
                        }
                        else
                            dr[colName] = Convert.DBNull;
                    }
                }
                if (showTotal) dt.Rows.Add(dr);
            }

            int LastIndex = -1;
            int Flag_Fixed = 0;
            int Flag_Sum = 0;
            int Flag_Hide = 0;
            int Flag_NoFilter = 0;

            gv.Columns.Clear();
            gv.OptionsBehavior.Editable = false;
            for (int i = 0; i < dt.Columns.Count || LastIndex >= 0; i++)
            {
                if (i >= dt.Columns.Count)
                {
                    if (LastIndex >= 0)
                        i = LastIndex;
                    else
                        break;
                    LastIndex = -2;
                }
                EsGridColumn col = new EsGridColumn();
                col.Name = "tmpColumn" + i.ToString();

                Flag_Fixed = 0;
                Flag_Sum = 0;
                Flag_NoFilter = 0;
                Flag_Hide = 0;
                string colName = dt.Columns[i].ColumnName;
                if (colName.IndexOf("Last") >= 0)
                {
                    if (LastIndex == -1)
                    {
                        LastIndex = i;
                        continue;
                    }
                    colName = colName.Replace("Last", "");
                }
                if (colName.IndexOf("Fixed") >= 0)
                {
                    Flag_Fixed = 1;
                    colName = colName.Replace("Fixed", "");
                }
                if (colName.IndexOf("Hide") >= 0)
                {
                    Flag_Hide = 1;
                    colName = colName.Replace("Hide", "");
                }
                if (colName.IndexOf("NoFilter") >= 0)
                {
                    Flag_NoFilter = 1;
                    colName = colName.Replace("NoFilter", "");
                }
                if (colName.IndexOf("SumNo") >= 0)
                {
                    Flag_Sum = 1;
                    Flag_NoFilter = 1;
                    colName = colName.Replace("SumNo", "");
                }
                if (colName.IndexOf("Sum") >= 0)
                {
                    Flag_Sum = 1;
                    colName = colName.Replace("Sum", "");
                }
                if (colName == "") colName = "无列名";

                dt.Columns[i].ColumnName = colName;
                col.Caption = colName;
                col.FieldName = colName;

                if (i == 0 || Flag_Hide == 1)
                {
                    col.Visible = false;
                    col.VisibleIndex = -1;
                }
                else
                {
                    col.Visible = true;
                    col.VisibleIndex = gv.Columns.Count;
                    col.OptionsColumn.AllowEdit = false;
                    col.OptionsColumn.AllowFocus = false;
                    col.OptionsColumn.ReadOnly = true;
                    if (Flag_Fixed == 1)
                    {
                        col.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
                    }
                    if (Flag_Sum == 1)
                    {
                        col.SummaryItem.FieldName = col.FieldName;
                        col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    }
                    else if (i == 1)
                    {
                        col.SummaryItem.FieldName = col.FieldName;
                        col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                    }
                    if (Flag_NoFilter == 1)
                    {
                        col.OptionsFilter.AllowFilter = false;
                    }
                }
                gv.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { col });
                if (LastIndex == -2) { LastIndex = i; break; }
            }
            gv.OptionsView.ShowFooter = !ShowTotal;
            gv.GridControl.DataSource = dt;
            gv.BestFitColumns();
        }

posted @ 2007-06-28 16:51 王学军 阅读(1016) 评论(3) 编辑

其中mRegistryRootKey 为软件的注册表位置

// 函数1 用于设置并将设置结果保存到注册表中 例子中只保存了上下左右,如果你有更多需要保存的自己扩展
            PageSetupDialog psDlg = new PageSetupDialog();
            PrinterSettings ps = new PrinterSettings();
            psDlg.PageSettings = ps.DefaultPageSettings;
            RegistryKey regPrint = Registry.LocalMachine.OpenSubKey(mRegistryRootKey + "PrintSetup\\", true);
            if (regPrint != null)
            {
                Margins ms = new Margins();
                ms.Left = Convert.ToInt32(regPrint.GetValue("Left", 100));
                ms.Top = Convert.ToInt32(regPrint.GetValue("Top", 100));
                ms.Right = Convert.ToInt32(regPrint.GetValue("Right", 100));
                ms.Bottom = Convert.ToInt32(regPrint.GetValue("Bottom", 100));
                if (System.Globalization.RegionInfo.CurrentRegion.IsMetric)
                   ms = PrinterUnitConvert.Convert(ms, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter);
                psDlg.PageSettings.Margins = ms;
            }
            else
            {
                regPrint = Registry.LocalMachine.CreateSubKey(mRegistryRootKey + "PrintSetup\\");
            }
            if (psDlg.ShowDialog() == DialogResult.OK)
            {
                regPrint.SetValue("Left", psDlg.PageSettings.Margins.Left, RegistryValueKind.String);
                regPrint.SetValue("Top", psDlg.PageSettings.Margins.Top, RegistryValueKind.String);
                regPrint.SetValue("Right", psDlg.PageSettings.Margins.Right, RegistryValueKind.String);
                regPrint.SetValue("Bottom", psDlg.PageSettings.Margins.Bottom, RegistryValueKind.String);
            }
            psDlg.Dispose();

 
开始使用了  例子中是给XtraReport用 
        private void fnSetPrintCustom(XtraReport report)
        {
            RegistryKey regPrint = Registry.LocalMachine.OpenSubKeymRegistryRootKey +"PrintSetup\\", false);
            if (regPrint != null)
            {
                int esLeft = Convert.ToInt32(regPrint.GetValue("Left", "-9999"));
                int esTop = Convert.ToInt32(regPrint.GetValue("Top", "-9999"));
                int esRight = Convert.ToInt32(regPrint.GetValue("Right", "-9999"));
                int esBottom = Convert.ToInt32(regPrint.GetValue("Bottom", "-9999"));
                if (esLeft != -99999) report.PrintingSystem.PageSettings.LeftMargin = esLeft;
                if (esTop != -99999) report.PrintingSystem.PageSettings.TopMargin = esTop;
                if (esRight != -99999) report.PrintingSystem.PageSettings.RightMargin = esRight;
                if (esBottom != -99999) report.PrintingSystem.PageSettings.BottomMargin = esBottom;
            }
        }

其实很简单

posted @ 2007-06-28 16:51 王学军 阅读(187) 评论(0) 编辑

说到C#.NET的更动更新 大家都想到了ClickOnce,但很多时候它的功能并没有我们需要的足够的强大。其实它的原理很简单,为什么我们不自己开发一套呢?下面以我的开发实例与大家交流一下。

原理:
1.服务器有一虚拟目录Update,里面放置客户端的所有程序(由于IIS限制,不能升级.config文件,如需要则改IIS相应配置)
2.Update目录里再放置一Default.aspx文件,用来取出当前文件夹下的文件列表和文件修改时间,并形成一个XML返回出来。
3.客户端升级程序使用HttpWebRequest对象访问这个http://server/Update/Default.asp,并获得返回的XML。将XML解析后与本地文件时间比较,如果不同则下载。

代码:
(Update/Default.aspx文件)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<%
    SortedList FileList = new SortedList();
    string UpdatePath = AppDomain.CurrentDomain.BaseDirectory + "\\update\\";

        DirectoryInfo di = new DirectoryInfo(UpdatePath);
        foreach (FileInfo fi in di.GetFiles())
        {
           // 判断如果是Default.aspx则不下载到客户端
            if (fi.Name == "Default.aspx") continue;
            FileList.Add(fi.Name, fi.LastWriteTime.ToString());
        }

    string retValue = "<xml>";
    for (int i = 0; i < FileList.Count; i++)
    {
            retValue += "<row File='" + FileList.GetKey(i).ToString() + "' Date='" + FileList.GetValue(i).ToString() + "' />";
    }
    retValue += "</xml>";

    Response.Write(retValue);
%>

好,上面的代码很简单,就是获得服务器更新目录里的所有文件列表与文件的修改时间返回出来。

客户端检查更新的代码:
引用:
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Xml;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Threading;

全局变量:
private SortedList DirectoryList = new SortedList();
private int m_FileNum = 1;


// 函数fnDoUpdate
private void fnDoUpdate()
{
      try
        {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://server/update/Default.aspx");
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                Stream ReceiveStream = myResponse.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader sr = new StreamReader(ReceiveStream, encode);
                Char[] read = new Char[256];
                string strResult = "";
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    strResult += str;
                    count = sr.Read(read, 0, 256);
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strResult);
    // 这个Resource是自己定义的一个类  基本具有下面几个属性:Name,Url,LastModified 我就不定义了
                Resource tempResource;
                foreach (XmlNode xn in doc.SelectNodes("//row"))
                {
                    tempResource = new Resource();
                    tempResource.Name = xn.Attributes["File"].Value;
                    tempResource.Url = ClientConfiguration.AppServerUrl + "update/" + tempResource.Name;
                    tempResource.LastModified = Convert.ToDateTime(xn.Attributes["Date"].Value);
                    DirectoryList.Add(tempResource.Url, tempResource);
                }
// 好了 DirectoryList就是服务器的文件列表了 下面开始与本地文件进行比较了
                for (int i = 1; i <= DirectoryList.Count; i++)
                {
                    Resource currentResource = (Resource)DirectoryList.GetByIndex(i - 1);
                    string newFilePath = Application.StartupPath + "\\" + currentResource.Name;
// 删除掉时间相同的 因为不需要下载 这里用到了CheckDateTime函数是我们自己定义的 后面符带了
                    if (File.Exists(newFilePath) && CheckDateTime(currentResource.LastModified, LastModFromDisk(newFilePath)))
                        DownloadList.Remove(currentResource.Url);
               }

// 好了 到这里就得到了 我们需要更新的文件列表 DownloadList  开始下载了
// 下载过程的处理比较麻烦 使用多线程要出问题 我研究了很久想出这个办法
                m_FileNum = 1;  // 这个用来定位当前下载第几个文件
                progressBar1.EditValue = 0; //进度条规0
                progressBar1.Properties.Maximum = DownloadList.Count;
                StartDownload();
            }
      catch (Exception ex)
      {
              // 异常处理
       }
}

// 函数StartDownload 用于下载单个文件
        private void StartDownload()
        {
            try
            {
                Resource currentResource = (Resource)DownloadList.GetByIndex(m_FileNum - 1);
                string newFilePath = Application.StartupPath +"\\"+ currentResource.Name;
                if (File.Exists(newFilePath)) File.Delete(newFilePath);
                progressBar1.EditValue = m_FileNum ;
                WebClient client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                Uri dUri = new Uri(currentResource.Url);
                client.DownloadFileAsync(dUri, newFilePath);
            }
            catch (Exception ex)
            {
                // 异常处理
            }
        }

// 下面二个事件 是WebClient对象的下载事件
        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs args)
        {
                // 要做得漂亮点 这里放些计算速度的 或时时显示下载进度的处理
               // 常用的有:args.ProgressPercentage 下载进度百分比 args.BytesReceived 已下载字节数
               // ts.TotalMilliseconds 总字节数
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs args)
        {
            Resource currentResource = (Resource)DownloadList.GetByIndex(m_FileNum - 1);
            string newFilePath = Application.StartupPath +"\\"+ currentResource.Name;
            // 将下载回来的文件修改时间更正 WebClient不会做这事只有我们来做了
            FileInfo f = new FileInfo(newFilePath);
            f.LastWriteTime = currentResource.LastModified;

            m_FileNum++;
            if (m_FileNum > DownloadList.Count)
            {
                    // 文件更新完成 这里写完成后的处理
            }
            else
            {
                // 没下完则继续下载下一个
                StartDownload();
            }
}

// 函数 LastModFromDisk 获取本地文件修改时间
  private DateTime LastModFromDisk(string filePath)
  {
   FileInfo f = new FileInfo(filePath);
   return (f.LastWriteTime);
  }


// 好了 到这里需要做的都写完了 下面是调用了 一定要用多线程来调用
                Thread t = new Thread(new ThreadStart(fnDoUpdate));
                t.Start();


好了,简单的自动更新功能就这么简单的完成了,你可以根据需要修改其中任意环节为自己想要的。
上面的代码是我在复杂的代码中把复杂的部分去掉了,也许你直接COPY过去用会编译不过,但我想
应该容易修改正确,希望大家多多指正。

大家不要置疑这思路的正确性,因为我开发的这段代码正在我公司的产品中使用,它的最大好处就是
我们可以随心所欲的修改下载的判断,或增加不同的需求。

posted @ 2007-06-28 16:50 王学军 阅读(4060) 评论(36) 编辑
今天是2007年5月29日 第一篇文章 希望以后会坚持
posted @ 2007-05-29 14:06 王学军 阅读(43) 评论(2) 编辑