连串化及反连串化的救助类SerializeUtil

XML 1XML 2    /**//// <summary>
XML 3    /// 连串化及反系列化的支援类
XML 4    /// </summary>
XML 5    public sealed class SerializeUtil
XML 6XML 7    XML 8{
XML 9        private SerializeUtil()
XML 10XML 11        XML 12{
XML 13        }
XML 14
XML 15XML 16        连串化操作函数#region 种类化操作函数
XML 17
XML 18XML 19        /**//// <summary>
XML 20        /// 将对象种类化为二进制字节
XML 21        /// </summary>
XML 22        /// <param name=”obj”>待体系化的目标</param>
XML 23        /// <returns></returns>
XML 24        public static byte[] SerializeToBinary(object obj)
XML 25XML 26        XML 27{
XML 28            byte[] bytes = new byte[2500];
XML 29            using (MemoryStream memoryStream = new MemoryStream())
XML 30XML 31            XML 32{
XML 33                BinaryFormatter bformatter = new BinaryFormatter();
XML 34                bformatter.Serialize(memoryStream, obj);
XML 35                memoryStream.Seek(0, 0);
XML 36
XML 37                if (memoryStream.Length > bytes.Length)
XML 38XML 39                XML 40{
XML 41                    bytes = new byte[memoryStream.Length];
XML 42                }
XML 43                bytes = memoryStream.ToArray();
XML 44            }
XML 45            return bytes;
XML 46        }
XML 47
XML 48XML 49        /**//// <summary>
XML 50        /// 将文件对象连串化到文件中
XML 51        /// </summary>
XML 52        /// <param name=”obj”>待体系化的目的</param>
XML 53        /// <param name=”path”>文件路径</param>
XML 54        /// <param name=”fileMode”>文件打开方式</param>
XML 55        public static void SerializeToBinary(object obj, string path, FileMode fileMode)
XML 56XML 57        XML 58{
XML 59            using (FileStream fs = new FileStream(path, fileMode))
XML 60XML 61            XML 62{
XML 63                // Construct a BinaryFormatter and use it to serialize the data to the stream.
XML 64                BinaryFormatter formatter = new BinaryFormatter();
XML 65                formatter.Serialize(fs, obj);
XML 66            }
XML 67        }
XML 68
XML 69XML 70        /**//// <summary>
XML 71        /// 将文件对象系列化到文件中
XML 72        /// </summary>
XML 73        /// <param name=”obj”>待系列化的靶子</param>
XML 74        /// <param name=”path”>文件路径</param>
XML 75        public static void SerializeToBinary(object obj, string path)
XML 76XML 77        XML 78{
XML 79            SerializeToBinary(obj, path, FileMode.Create);
XML 80        }
XML 81
XML 82
XML 83XML 84        /**//// <summary>
XML 85        /// 将对象种类化为Soap字符串
XML 86        /// </summary>
XML 87        /// <param name=”obj”>待体系化的对象</param>
XML 88        /// <returns>Soap字符串</returns>
XML 89        public static string SerializeToSoap(object obj)
XML 90XML 91        XML 92{
XML 93            string soap = string.Empty;
XML 94            using (MemoryStream memoryStream = new MemoryStream())
XML 95XML 96            XML 97{
XML 98                SoapFormatter sformatter = new SoapFormatter();
XML 99                sformatter.Serialize(memoryStream, obj);
XML 100                memoryStream.Seek(0, 0);
XML 101                soap = Encoding.ASCII.GetString(memoryStream.ToArray());
XML 102            }
XML 103
XML 104            return soap;
XML 105        }
XML 106
XML 107XML 108        /**//// <summary>
XML 109        /// 将指标系列化为Soap字符串,并保存到文件中
XML 110        /// </summary>
XML 111        /// <param name=”obj”>待种类化的目的</param>
XML 112        /// <param name=”path”>文件路径</param>
XML 113        /// <param name=”fileMode”>文件打开方式</param>
XML 114        public static void SerializeToSoap(object obj, string path, FileMode fileMode)
XML 115XML 116        XML 117{
XML 118            FileStream fs = new FileStream(path, fileMode);
XML 119
XML 120            // Construct a BinaryFormatter and use it to serialize the data to the stream.
XML 121            SoapFormatter formatter = new SoapFormatter();
XML 122            try
XML 123XML 124            XML 125{
XML 126                formatter.Serialize(fs, obj);
XML 127            }
XML 128            catch (SerializationException e)
XML 129XML 130            XML 131{
XML 132                Console.WriteLine(“Failed to serialize. Reason: ” + e.Message);
XML 133                throw;
XML 134            }
XML 135            finally
XML 136XML 137            XML 138{
XML 139                fs.Close();
XML 140            }
XML 141        }
XML 142
XML 143XML 144        /**//// <summary>
XML 145        /// 将目的连串化为Soap字符串,并保存到文件中
XML 146        /// </summary>
XML 147        /// <param name=”obj”>待系列化的指标</param>
XML 148        /// <param name=”path”>文件路径</param>
XML 149        public static void SerializeToSoap(object obj, string path)
XML 150XML 151        XML 152{
XML 153            SerializeToSoap(obj, path, FileMode.Create);
XML 154        }
XML 155
XML 156
XML 157XML 158        /**//// <summary>
XML 159        /// 将对象种类化为XML字符串
XML 160        /// </summary>
XML 161        /// <param name=”obj”>待种类化的指标</param>
XML 162        /// <returns>XML字符串</returns>
XML 163        public static string SerializeToXml(object obj)
XML 164XML 165        XML 166{
XML 167            string xml = “”;
XML 168            using (MemoryStream memoryStream = new MemoryStream())
XML 169XML 170            XML 171{
XML 172                XmlSerializer serializer = new XmlSerializer(obj.GetType());
XML 173                serializer.Serialize(memoryStream, obj);
XML 174                memoryStream.Seek(0, 0);
XML 175                xml = Encoding.ASCII.GetString(memoryStream.ToArray());
XML 176            }
XML 177
XML 178            return xml;
XML 179        }
XML 180
XML 181XML 182        /**//// <summary>
XML 183        /// 将指标连串化为XML字符串并保存到文件
XML 184        /// </summary>
XML 185        /// <param name=”obj”>待类别化的靶子</param>
XML 186        /// <param name=”path”>保存的文书路径</param>
XML 187        /// <param name=”fileMode”>文件打开情势</param>
XML 188        public static void SerializeToXmlFile(object obj, string path, FileMode fileMode)
XML 189XML 190        XML 191{
XML 192            using (FileStream fileStream = new FileStream(path, fileMode))
XML 193XML 194            XML 195{
XML 196                // Construct a BinaryFormatter and use it to serialize the data to the stream.
XML 197                XmlSerializer serializer = new XmlSerializer(obj.GetType());
XML 198                serializer.Serialize(fileStream, obj);
XML 199            }
XML 200        }
XML 201
XML 202XML 203        /**//// <summary>
XML 204        /// 将目的体系化为XML字符串并保存到文件
XML 205        /// </summary>
XML 206        /// <param name=”obj”>待连串化的目的</param>
XML 207        /// <param name=”path”>保存的公文路径</param>
XML 208        public static void SerializeToXmlFile(object obj, string path)
XML 209XML 210        XML 211{
XML 212            SerializeToXmlFile(obj, path, FileMode.Create);
XML 213        }
XML 214
XML 215        #endregion
XML 216
XML 217XML 218        反系列化操作函数#region 反体系化操作函数
XML 219
XML 220XML 221        /**//// <summary>
XML 222        /// 从XML文件中反类别化为Object对象
XML 223        /// </summary>
XML 224        /// <param name=”type”>对象的品种</param>
XML 225        /// <param name=”path”>XML文件</param>
XML 226        /// <returns>反系列化后取得的目的</returns>
XML 227        public static object DeserializeFromXmlFile(Type type, string path)
XML 228XML 229        XML 230{
XML 231            object result = new object();
XML 232            using (FileStream fileStream = new FileStream(path, FileMode.Open))
XML 233XML 234            XML 235{
XML 236                XmlSerializer serializer = new XmlSerializer(type);
XML 237                result = serializer.Deserialize(fileStream);
XML 238            }
XML 239
XML 240            return result;
XML 241        }
XML 242
XML 243XML 244        /**//// <summary>
XML 245        /// 从XML文件中反类别化为目的
XML 246        /// </summary>
XML 247        /// <param name=”type”>对象的档次</param>
XML 248        /// <param name=”xml”>XML字符串</param>
XML 249        /// <returns>反体系化后拿走的对象</returns>
XML 250        public static object DeserializeFromXml(Type type, string xml)
XML 251XML 252        XML 253{
XML 254            object result = new object();
XML 255            XmlSerializer serializer = new XmlSerializer(type);
XML 256            result = serializer.Deserialize(new StringReader(xml));
XML 257
XML 258            return result;
XML 259        }
XML 260
XML 261XML 262        /**//// <summary>
XML 263        /// 从Soap字符串中反种类化为目的
XML 264        /// </summary>
XML 265        /// <param name=”type”>对象的连串</param>
XML 266        /// <param name=”soap”>soap字符串</param>
XML 267        /// <returns>反体系化后获取的目的</returns>
XML 268        public static object DeserializeFromSoap(Type type, string soap)
XML 269XML 270        XML 271{
XML 272            object result = new object();
XML 273            using (MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(soap)))
XML 274XML 275            XML 276{
XML 277                SoapFormatter serializer = new SoapFormatter();
XML 278                result = serializer.Deserialize(memoryStream);
XML 279            }
XML 280
XML 281            return result;
XML 282        }
XML 283
XML 284XML 285        /**//// <summary>
XML 286        /// 从二进制字节中反体系化为目的
XML 287        /// </summary>
XML 288        /// <param name=”type”>对象的连串</param>
XML 289        /// <param name=”bytes”>字节数组</param>
XML 290        /// <returns>反类别化后收获的目的</returns>
XML 291        public static object DeserializeFromBinary(Type type, byte[] bytes)
XML 292XML 293        XML 294{
XML 295            object result = new object();
XML 296            using (MemoryStream memoryStream = new MemoryStream(bytes))
XML 297XML 298            XML 299{
XML 300                BinaryFormatter serializer = new BinaryFormatter();
XML 301                result = serializer.Deserialize(memoryStream);
XML 302            }
XML 303
XML 304            return result;
XML 305        }
XML 306
XML 307XML 308        /**//// <summary>
XML 309        /// 从二进制文件中反连串化为指标
XML 310        /// </summary>
XML 311        /// <param name=”type”>对象的门类</param>
XML 312        /// <param name=”path”>二进制文件路径</param>
XML 313        /// <returns>反类别化后拿走的靶子</returns>
XML 314        public static object DeserializeFromBinary(Type type, string path)
XML 315XML 316        XML 317{
XML 318            object result = new object();
XML 319            using (FileStream fileStream = new FileStream(path, FileMode.Open))
XML 320XML 321            XML 322{
XML 323                BinaryFormatter serializer = new BinaryFormatter();
XML 324                result = serializer.Deserialize(fileStream);
XML 325            }
XML 326
XML 327            return result;
XML 328        }
XML 329
XML 330        #endregion
XML 331
XML 332XML 333        /**//// <summary>
XML 334        /// 获取对象的转换为二进制的字节大小
XML 335        /// </summary>
XML 336        /// <param name=”obj”></param>
XML 337        /// <returns></returns>
XML 338        public static long GetByteSize(object obj)
XML 339XML 340        XML 341{
XML 342            long result;
XML 343            BinaryFormatter bFormatter = new BinaryFormatter();
XML 344            using (MemoryStream stream = new MemoryStream())
XML 345XML 346            XML 347{
XML 348                bFormatter.Serialize(stream, obj);
XML 349                result = stream.Length;
XML 350            }
XML 351            return result;
XML 352        }
XML 353
XML 354XML 355        /**//// <summary>
XML 356        /// 克隆1个对象
XML 357        /// </summary>
XML 358        /// <param name=”obj”>待克隆的靶子</param>
XML 359        /// <returns>克隆的八个新的靶子</returns>
XML 360        public static object Clone(object obj)
XML 361XML 362        XML 363{
XML 364            object cloned = null;
XML 365            BinaryFormatter bFormatter = new BinaryFormatter();
XML 366            using (MemoryStream memoryStream = new MemoryStream())
XML 367XML 368            XML 369{
XML 370                try
XML 371XML 372                XML 373{
XML 374                    bFormatter.Serialize(memoryStream, obj);
XML 375                    memoryStream.Seek(0, SeekOrigin.Begin);
XML 376                    cloned = bFormatter.Deserialize(memoryStream);
XML 377                }
XML 378                catch //(Exception e)
XML 379XML 380                XML 381{
XML 382                    ;
XML 383                }
XML 384            }
XML 385
XML 386            return cloned;
XML 387        }
XML 388
XML 389XML 390        /**//// <summary>
XML 391        /// 从文件中读取文本内容
XML 392        /// </summary>
XML 393        /// <param name=”path”>文件路径</param>
XML 394        /// <returns>文件的始末</returns>
XML 395        public static string ReadFile(string path)
XML 396XML 397        XML 398{
XML 399            string content = string.Empty;
XML 400            using (StreamReader reader = new StreamReader(path))
XML 401XML 402            XML 403{
XML 404                content = reader.ReadToEnd();
XML 405            }
XML 406
XML 407            return content;
XML 408        }
XML 409
XML 410XML 411        /**//// <summary>
XML 412        /// 读取嵌入财富的文本内容
XML 413        /// </summary>
XML 414        /// <param name=”fileWholeName”>包罗命名空间的放权财富文件名路径</param>
XML 415        /// <returns>文件中的文本内容</returns>
XML 416        public static string ReadFileFromEmbedded(string fileWholeName)
XML 417XML 418        XML 419{
XML 420            string result = string.Empty;
XML 421
XML 422            Assembly assembly = Assembly.GetEntryAssembly();
XML 423            using (TextReader reader = new StreamReader(assembly.GetManifestResourceStream(fileWholeName)))
XML 424XML 425            XML 426{
XML 427                result = reader.ReadToEnd();
XML 428            }
XML 429
XML 430            return result;
XML 431        }
XML 432    }

系列化及反系列化的帮手类SerializeUtil测试代码

XML 433    public class TestSerializeUtil
XML 434XML 435    XML 436{
XML 437        public static string Execute()
XML 438XML 439        XML 440{
XML 441            string result = string.Empty;
XML 442            result += “使用塞里alizeUtil连串化及反类别化的协理类:” + “\r\n”;
XML 443            
XML 444            Person person = new Person();
XML 445            person.Name = “wuhuacong”;
XML 446            person.Age = 20;
XML 447            
XML 448            byte[] bytes = SerializeUtil.SerializeToBinary(person);
XML 449            Person person2 = SerializeUtil.DeserializeFromBinary(typeof (Person), bytes) as Person;
XML 450            result += ReflectionUtil.GetProperties(person2) + “\r\n”;
XML 451            
XML 452            string xml = SerializeUtil.SerializeToXml(person);
XML 453            Person person3 = SerializeUtil.DeserializeFromXml(typeof (Person), xml) as Person;
XML 454            result += “person3:\r\n” + ReflectionUtil.GetProperties(person3) + “\r\n”;
XML 455            
XML 456            result += “SerializeUtil.GetByteSize(person3):” + SerializeUtil.GetByteSize(person3) + “\r\n”;
XML 457            
XML 458            Person person4 = SerializeUtil.Clone(person3) as Person;
XML 459            result += “person4:\r\n” + ReflectionUtil.GetProperties(person4) + “\r\n”;
XML 460            
XML 461            result += “Util.AreObjectsEqual(person3, person4):” + Util.AreObjectsEqual(person3, person4)+ “\r\n”;
XML 462            
XML 463            SerializeUtil.SerializeToXmlFile(person3, Util.CurrentPath + “person3.xml”, FileMode.Create);
XML 464            Person person5 = SerializeUtil.DeserializeFromXmlFile(typeof (Person), Util.CurrentPath + “person3.xml”) as Person;
XML 465            result += “person5:\r\n” + ReflectionUtil.GetProperties(person5) + “\r\n\r\n”;
XML 466            
XML 467            result += SerializeUtil.ReadFile(Util.CurrentPath + “person3.xml”) + “\r\n\r\n”;
XML 468            result += SerializeUtil.ReadFileFromEmbedded(“TestUtilities.EmbedFile.xml”) + “\r\n\r\n”;
XML 469
XML 470            return result;
XML 471        }
XML 472    }

 

数据库字段NULL值转换帮忙类斯马特DataReader

XML 473XML 474    /**//// <summary>
XML 475    /// 用来更换含有NULL值的字段为合适值的帮扶类
XML 476    /// </summary>
XML 477    public sealed class SmartDataReader
XML 478XML 479    XML 480{
XML 481        private DateTime defaultDate;
XML 482
XML 483        public SmartDataReader(IDataReader reader)
XML 484XML 485        XML 486{
XML 487            defaultDate = Convert.ToDateTime(“01/01/1900”);
XML 488            this.reader = reader;
XML 489        }
XML 490
XML 491        public int GetInt32(String column)
XML 492XML 493        XML 494{
XML 495            int data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (int) 0 : (int) reader[column];
XML 496            return data;
XML 497        }
XML 498
XML 499        public short GetInt16(String column)
XML 500XML 501        XML 502{
XML 503            short data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (short) 0 : (short) reader[column];
XML 504            return data;
XML 505        }
XML 506
XML 507        public byte GetByte(String column)
XML 508XML 509        XML 510{
XML 511            byte data = (reader.IsDBNull(reader.GetOrdinal(column))) ? (byte) 0 : (byte) reader[column];
XML 512            return data;
XML 513        }
XML 514
XML 515        public float GetFloat(String column)
XML 516XML 517        XML 518{
XML 519            float data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : float.Parse(reader[column].ToString());
XML 520            return data;
XML 521        }
XML 522
XML 523        public double GetDouble(String column)
XML 524XML 525        XML 526{
XML 527            double data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : double.Parse(reader[column].ToString());
XML 528            return data;
XML 529        }
XML 530
XML 531        public decimal GetDecimal(String column)
XML 532XML 533        XML 534{
XML 535            decimal data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : decimal.Parse(reader[column].ToString());
XML 536            return data;
XML 537        }
XML 538
XML 539        public Single GetSingle(String column)
XML 540XML 541        XML 542{
XML 543            Single data = (reader.IsDBNull(reader.GetOrdinal(column))) ? 0 : Single.Parse(reader[column].ToString());
XML 544            return data;
XML 545        }
XML 546
XML 547        public bool GetBoolean(String column)
XML 548XML 549        XML 550{
XML 551            bool data = (reader.IsDBNull(reader.GetOrdinal(column))) ? false : (bool) reader[column];
XML 552            return data;
XML 553        }
XML 554
XML 555        public String GetString(String column)
XML 556XML 557        XML 558{
XML 559            String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
XML 560            return data;
XML 561        }
XML 562
XML 563        public byte[] GetBytes(String column)
XML 564XML 565        XML 566{
XML 567            String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
XML 568            return Encoding.UTF8.GetBytes(data);
XML 569        }
XML 570
XML 571        public Guid GetGuid(String column)
XML 572XML 573        XML 574{
XML 575            String data = (reader.IsDBNull(reader.GetOrdinal(column))) ? null : reader[column].ToString();
XML 576            Guid guid = Guid.Empty;
XML 577            if (data != null)
XML 578XML 579            XML 580{
XML 581                guid = new Guid(data);
XML 582            }
XML 583            return guid;
XML 584        }
XML 585
XML 586        public DateTime GetDateTime(String column)
XML 587XML 588        XML 589{
XML 590            DateTime data = (reader.IsDBNull(reader.GetOrdinal(column))) ? defaultDate : (DateTime) reader[column];
XML 591            return data;
XML 592        }
XML 593
XML 594        public bool Read()
XML 595XML 596        XML 597{
XML 598            return reader.Read();
XML 599        }
XML 600
XML 601        private IDataReader reader;
XML 602    }

数据库字段NULL值转换援助类斯马特DataReader测试代码

XML 603    public class TestSmartDataReader
XML 604XML 605    XML 606{
XML 607        public static string Execute()
XML 608XML 609        XML 610{
XML 611            string result = string.Empty;
XML 612            result += “使用SmartDataReader辅助类:” + “\r\n”;
XML 613
XML 614            try
XML 615XML 616            XML 617{
XML 618                TestInfo person = SelectOne();
XML 619                result += ReflectionUtil.GetProperties(person) + “\r\n \r\n”;
XML 620            }
XML 621            catch (Exception ex)
XML 622XML 623            XML 624{
XML 625                result += string.Format(“发生错误:{0}!\r\n \r\n”, ex.Message);
XML 626            }
XML 627            return result;
XML 628        }
XML 629        
XML 630XML 631        /**//// <summary>
XML 632        /// 将DataReader的属性值转化为实体类的属性值,重返实体类
XML 633        /// </summary>
XML 634        /// <param name=”dataReader”>有效的DataReader对象</param>
XML 635        /// <returns>实体类对象</returns>
XML 636        private static TestInfo DataReaderToEntity(IDataReader dataReader)
XML 637XML 638        XML 639{
XML 640            TestInfo testInfo = new TestInfo();
XML 641            SmartDataReader reader = new SmartDataReader(dataReader);
XML 642            
XML 643            testInfo.ID = reader.GetInt32(“ID”);
XML 644            testInfo.Name = reader.GetString(“Name”);
XML 645            testInfo.Age = reader.GetInt32(“Age”);
XML 646            testInfo.Man = reader.GetBoolean(“Man”);
XML 647            testInfo.Birthday = reader.GetDateTime(“Birthday”);
XML 648            
XML 649            return testInfo;
XML 650        }
XML 651        
XML 652        public static TestInfo SelectOne()
XML 653XML 654        XML 655{
XML 656            TestInfo testInfo = null;
XML 657            string sqlCommand = ” Select top 1 * from Test”;
XML 658
XML 659            string connectionString = “Server=localhost;Database=Test;uid=sa;pwd=123456”;
XML 660            using(SqlConnection connection = new SqlConnection(connectionString))
XML 661XML 662            XML 663{
XML 664                connection.Open();
XML 665                SqlCommand com = new SqlCommand(sqlCommand, connection);
XML 666                using (IDataReader reader = com.ExecuteReader())
XML 667XML 668                XML 669{
XML 670                    if (reader.Read())
XML 671XML 672                    XML 673{
XML 674                        testInfo = DataReaderToEntity(reader);
XML 675                    }
XML 676                }
XML 677            }
XML 678            return testInfo;
XML 679        }
XML 680    }

字符串操作扶助类

XML 681XML 682    /**//// <summary>
XML 683    /// 字符串操作协助类
XML 684    /// </summary>
XML 685    public class StringUtil
XML 686XML 687    XML 688{
XML 689XML 690        一些基本的标志常量#region 一些为主的号子常量
XML 691
XML 692XML 693        /**//// <summary>
XML 694        /// 点符号 .
XML 695        /// </summary>
XML 696        public const string Dot = “.”;
XML 697
XML 698XML 699        /**//// <summary>
XML 700        /// 下划线 _
XML 701        /// </summary>
XML 702        public const string UnderScore = “_”;
XML 703
XML 704XML 705        /**//// <summary>
XML 706        /// 逗号加空格 , 
XML 707        /// </summary>
XML 708        public const string CommaSpace = “, “;
XML 709
XML 710XML 711        /**//// <summary>
XML 712        /// 逗号 ,
XML 713        /// </summary>
XML 714        public const string Comma = “,”;
XML 715
XML 716XML 717        /**//// <summary>
XML 718        /// 左括号 (
XML 719        /// </summary>
XML 720        public const string OpenParen = “(“;
XML 721
XML 722XML 723        /**//// <summary>
XML 724        /// 右括号 )
XML 725        /// </summary>
XML 726        public const string ClosedParen = “)”;
XML 727
XML 728XML 729        /**//// <summary>
XML 730        /// 单引号 ‘
XML 731        /// </summary>
XML 732        public const string SingleQuote = “\'”;
XML 733
XML 734XML 735        /**//// <summary>
XML 736        /// 斜线 \
XML 737        /// </summary>
XML 738        public const string Slash = @”\”;
XML 739
XML 740        #endregion
XML 741
XML 742        private StringUtil()
XML 743XML 744        XML 745{
XML 746        }
XML 747
XML 748XML 749        /**//// <summary>
XML 750        /// 移除空格并首字母小写的Camel样式
XML 751        /// </summary>
XML 752        /// <param name=”name”></param>
XML 753        /// <returns></returns>
XML 754        public static string ToCamel(string name)
XML 755XML 756        XML 757{
XML 758            string clone = name.TrimStart(‘_’);
XML 759            clone = RemoveSpaces(ToProperCase(clone));
XML 760            return String.Format(“{0}{1}”, Char.ToLower(clone[0]), clone.Substring(1, clone.Length – 1));
XML 761        }
XML 762
XML 763XML 764        /**//// <summary>
XML 765        /// 移除空格并首字母大写的帕斯Carl样式
XML 766        /// </summary>
XML 767        /// <param name=”name”></param>
XML 768        /// <returns></returns>
XML 769        public static string ToCapit(string name)
XML 770XML 771        XML 772{
XML 773            string clone = name.TrimStart(‘_’);
XML 774            return RemoveSpaces(ToProperCase(clone));
XML 775        }
XML 776
XML 777
XML 778XML 779        /**//// <summary>
XML 780        /// 移除最终的字符
XML 781        /// </summary>
XML 782        /// <param name=”s”></param>
XML 783        /// <returns></returns>
XML 784        public static string RemoveFinalChar(string s)
XML 785XML 786        XML 787{
XML 788            if (s.Length > 1)
XML 789XML 790            XML 791{
XML 792                s = s.Substring(0, s.Length – 1);
XML 793            }
XML 794            return s;
XML 795        }
XML 796
XML 797XML 798        /**//// <summary>
XML 799        /// 移除最后的逗号
XML 800        /// </summary>
XML 801        /// <param name=”s”></param>
XML 802        /// <returns></returns>
XML 803        public static string RemoveFinalComma(string s)
XML 804XML 805        XML 806{
XML 807            if (s.Trim().Length > 0)
XML 808XML 809            XML 810{
XML 811                int c = s.LastIndexOf(“,”);
XML 812                if (c > 0)
XML 813XML 814                XML 815{
XML 816                    s = s.Substring(0, s.Length – (s.Length – c));
XML 817                }
XML 818            }
XML 819            return s;
XML 820        }
XML 821
XML 822XML 823        /**//// <summary>
XML 824        /// 移除字符中的空格
XML 825        /// </summary>
XML 826        /// <param name=”s”></param>
XML 827        /// <returns></returns>
XML 828        public static string RemoveSpaces(string s)
XML 829XML 830        XML 831{
XML 832            s = s.Trim();
XML 833            s = s.Replace(” “, “”);
XML 834            return s;
XML 835        }
XML 836
XML 837XML 838        /**//// <summary>
XML 839        /// 字符串首字母大写
XML 840        /// </summary>
XML 841        /// <param name=”s”></param>
XML 842        /// <returns></returns>
XML 843        public static string ToProperCase(string s)
XML 844XML 845        XML 846{
XML 847            string revised = “”;
XML 848            if (s.Length > 0)
XML 849XML 850            XML 851{
XML 852                if (s.IndexOf(” “) > 0)
XML 853XML 854                XML 855{
XML 856                    revised = Strings.StrConv(s, VbStrConv.ProperCase, 1033);
XML 857                }
XML 858                else
XML 859XML 860                XML 861{
XML 862                    string firstLetter = s.Substring(0, 1).ToUpper(new CultureInfo(“en-US”));
XML 863                    revised = firstLetter + s.Substring(1, s.Length – 1);
XML 864                }
XML 865            }
XML 866            return revised;
XML 867        }
XML 868
XML 869XML 870        /**//// <summary>
XML 871        /// 判断字符是或不是NULL可能为空
XML 872        /// </summary>
XML 873        public static bool IsNullOrEmpty(string value)
XML 874XML 875        XML 876{
XML 877            if (value == null || value == string.Empty)
XML 878XML 879            XML 880{
XML 881                return true;
XML 882            }
XML 883
XML 884            return false;
XML 885        }
XML 886    }

字符串操作帮助类测试代码

XML 887    public class TestStringUtil
XML 888XML 889    XML 890{
XML 891        public static string Execute()
XML 892XML 893        XML 894{
XML 895            string value = “test String,”;
XML 896            
XML 897            string result = string.Empty;
XML 898            result += “使用StringUtil字符串操作援救类:” + “\r\n”;
XML 899            result += “原字符串为:” + value + “\r\n”;
XML 900            result += “StringUtil.IsNullOrEmpty:” + StringUtil.IsNullOrEmpty(value) + “\r\n”;
XML 901            result += “StringUtil.ToCamel:” + StringUtil.ToCamel(value) + “\r\n”;
XML 902            result += “StringUtil.ToCapit:” + StringUtil.ToCapit(value) + “\r\n”;
XML 903            result += “StringUtil.RemoveSpaces:” + StringUtil.RemoveSpaces(value) + “\r\n”;
XML 904            result += “StringUtil.RemoveFinalChar:” + StringUtil.RemoveFinalChar(value) + “\r\n”;
XML 905            result += “StringUtil.ToProperCase:” + StringUtil.ToProperCase(value) + “\r\n”;
XML 906            
XML 907            result += “\r\n\r\n”;
XML 908            return result;
XML 909        }

Web界面层操作的帮衬类

XML 910XML 911    /**//// <summary>
XML 912    /// Web界面层操作的援助类
XML 913    /// </summary>
XML 914    public sealed class UIHelper
XML 915XML 916    XML 917{
XML 918        private static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
XML 919
XML 920        private UIHelper()
XML 921XML 922        XML 923{
XML 924        }
XML 925
XML 926XML 927        /**//// <summary>
XML 928        /// 提醒音讯,要是不行为HWException类型,则记录到日志
XML 929        /// </summary>
XML 930        /// <param name=”page”>当前的页面</param>
XML 931        /// <param name=”ex”>万分对象</param>
XML 932        /// <param name=”Close”>是还是不是关闭</param>
XML 933        public static void ShowError(Page page, Exception ex, bool Close)
XML 934XML 935        XML 936{
XML 937            logger.Error(“Exception:” + page.ID, ex);
XML 938
XML 939            string errorMsg = ex.Message;
XML 940            errorMsg = errorMsg.Replace(“\n”, ” “);
XML 941            if (Close)
XML 942XML 943            XML 944{
XML 945                AlertAndClose(page, errorMsg);
XML 946            }
XML 947            else
XML 948XML 949            XML 950{
XML 951                Alerts(page, errorMsg);
XML 952            }
XML 953        }
XML 954
XML 955XML 956        /**//// <summary>
XML 957        /// 提示新闻
XML 958        /// </summary>
XML 959        /// <param name=”control”>当前的页面</param>
XML 960        /// <param name=”message”>提醒音信</param>
XML 961        public static void Alerts(Control control, string message)
XML 962XML 963        XML 964{
XML 965XML 966            string script = string.Format(“<script>javascript:alert(\”XML 967{0}\”);</script>”, message).Replace(“\r\n”, “”);
XML 968            control.Page.RegisterStartupScript(“”, script);
XML 969        }
XML 970
XML 971XML 972        /**//// <summary>
XML 973        /// 提醒音信并关闭窗口
XML 974        /// </summary>
XML 975        /// <param name=”control”>当前的页面</param>
XML 976        /// <param name=”message”>提醒消息</param>
XML 977        public static void AlertAndClose(Control control, string message)
XML 978XML 979        XML 980{
XML 981            string script =
XML 982XML 983                string.Format(“<script>javascript:alert(\”XML 984{0}\”);window.close();</script>”, message).Replace(“\r\n”, “”);
XML 985            control.Page.RegisterStartupScript(“”, script);
XML 986        }
XML 987
XML 988XML 989        /**//// <summary>
XML 990        /// 将错误消息记录到事件日志中
XML 991        /// </summary>
XML 992        /// <param name=”errorMessage”>文本音讯</param>
XML 993        public static void LogError(string errorMessage)
XML 994XML 995        XML 996{
XML 997            logger.Error(errorMessage);
XML 998        }
XML 999
XML 1000XML 1001        /**//// <summary>
XML 1002        /// 将错误音信记录到事件日志中
XML 1003        /// </summary>
XML 1004        /// <param name=”ex”>错误对象</param>
XML 1005        public static void LogError(Exception ex)
XML 1006XML 1007        XML 1008{
XML 1009            try
XML 1010XML 1011            XML 1012{
XML 1013                logger.Error(ex.Message + “\n” + ex.Source + “\n” + ex.StackTrace);
XML 1014            }
XML 1015            catch
XML 1016XML 1017            XML 1018{
XML 1019            }
XML 1020        }
XML 1021
XML 1022XML 1023        /**//// <summary>
XML 1024        /// 弹出提醒消息
XML 1025        /// </summary>
XML 1026        /// <param name=”key”>key</param>
XML 1027        /// <param name=”message”>提醒消息</param>
XML 1028        /// <param name=”page”>当前乞请的page</param>
XML 1029        public static void Alert(string key, string message, Page page)
XML 1030XML 1031        XML 1032{
XML 1033XML 1034            string msg = string.Format(“<script language=\”javascript\”>alert(\”XML 1035{0}\”);</script>”, message);
XML 1036
XML 1037            page.RegisterStartupScript(key, msg);
XML 1038        }
XML 1039
XML 1040XML 1041        /**//// <summary>
XML 1042        /// 弹出提醒消息
XML 1043        /// </summary>
XML 1044        /// <param name=”message”></param>
XML 1045        /// <param name=”page”></param>
XML 1046        public static void Alert(string message, Page page)
XML 1047XML 1048        XML 1049{
XML 1050            Alert(“message”, message, page);
XML 1051        }
XML 1052
XML 1053XML 1054        /**//// <summary>
XML 1055        /// 定位到钦命的页面
XML 1056        /// </summary>
XML 1057        /// <param name=”GoPage”>目的页面</param>
XML 1058        public static void GoTo(string GoPage)
XML 1059XML 1060        XML 1061{
XML 1062            HttpContext.Current.Response.Redirect(GoPage);
XML 1063        }
XML 1064
XML 1065XML 1066        /**//// <summary>
XML 1067        /// 定位到内定的页面
XML 1068        /// </summary>
XML 1069        /// <param name=”control”>当前央浼的page</param>
XML 1070        /// <param name=”page”>目的页面</param>
XML 1071        public static void Location(Control control, string page)
XML 1072XML 1073        XML 1074{
XML 1075            string js = “<script language=’JavaScript’>”;
XML 1076            js += “top.location='” + page + “‘”;
XML 1077            js += “</script>”;
XML 1078            control.Page.RegisterStartupScript(“”, js);
XML 1079        }
XML 1080
XML 1081XML 1082        /**//// <summary>
XML 1083        /// 提醒新闻并平昔到钦点的页面
XML 1084        /// </summary>
XML 1085        /// <param name=”control”>当前伏乞的page</param>
XML 1086        /// <param name=”page”>指标页面</param>
XML 1087        /// <param name=”message”>提示消息</param>
XML 1088        public static void AlertAndLocation(Control control, string page, string message)
XML 1089XML 1090        XML 1091{
XML 1092            string js = “<script language=’JavaScript’>”;
XML 1093            js += “alert(‘” + message + “‘);”;
XML 1094            js += “top.location='” + page + “‘”;
XML 1095            js += “</script>”;
XML 1096            control.Page.RegisterStartupScript(“”, js);
XML 1097        }
XML 1098
XML 1099XML 1100        /**//// <summary>
XML 1101        /// 关闭页面,并再次回到钦赐的值
XML 1102        /// </summary>
XML 1103        /// <param name=”control”></param>
XML 1104        /// <param name=”returnValue”></param>
XML 1105        public static void CloseWin(Control control, string returnValue)
XML 1106XML 1107        XML 1108{
XML 1109            string js = “<script language=’JavaScript’>”;
XML 1110            js += “window.parent.returnValue='” + returnValue + “‘;”;
XML 1111            js += “window.close();”;
XML 1112            js += “</script>”;
XML 1113            control.Page.RegisterStartupScript(“”, js);
XML 1114        }
XML 1115
XML 1116XML 1117        /**//// <summary>
XML 1118        /// 获取Html的锚点
XML 1119        /// </summary>
XML 1120        /// <param name=”innerText”></param>
XML 1121        /// <param name=”href”></param>
XML 1122        /// <returns></returns>
XML 1123        public static HtmlAnchor GetHtmlAnchor(string innerText, string href)
XML 1124XML 1125        XML 1126{
XML 1127            HtmlAnchor htmlAnchor = new HtmlAnchor();
XML 1128            htmlAnchor.InnerText = innerText;
XML 1129            htmlAnchor.HRef = href;
XML 1130
XML 1131            return htmlAnchor;
XML 1132        }
XML 1133
XML 1134XML 1135        /**//// <summary>
XML 1136        /// 判断输入的字符是不是为数字
XML 1137        /// </summary>
XML 1138        /// <param name=”strValue”></param>
XML 1139        /// <returns></returns>
XML 1140        public static bool IsNumerical(string strValue)
XML 1141XML 1142        XML 1143{
XML 1144            return Regex.IsMatch(strValue, @”^[0-9]*$”);
XML 1145        }
XML 1146
XML 1147XML 1148        /**//// <summary>
XML 1149        /// 判断字符串是或不是是NULL或许string.Empty
XML 1150        /// </summary>
XML 1151        /// <param name=”text”></param>
XML 1152        /// <returns></returns>
XML 1153        public static bool IsNullorEmpty(string text)
XML 1154XML 1155        XML 1156{
XML 1157            return text == null || text.Trim() == string.Empty;
XML 1158        }
XML 1159
XML 1160XML 1161        /**//// <summary>
XML 1162        /// 获取DataGrid控件中选拔的品种的ID字符串(供给DataGrid设置datakey田野(field)=”ID”)
XML 1163        /// </summary>
XML 1164        /// <returns>假若没有采取, 那么再次来到为空字符串, 不然赶回逗号分隔的ID字符串(如1,2,3)</returns>
XML 1165        public static string GetDatagridItems(DataGrid dg)
XML 1166XML 1167        XML 1168{
XML 1169            string idstring = string.Empty;
XML 1170            foreach (DataGridItem item in dg.Items)
XML 1171XML 1172            XML 1173{
XML 1174                string key = dg.DataKeys[item.ItemIndex].ToString();
XML 1175                bool isSelected = ((CheckBox) item.FindControl(“cbxDelete”)).Checked;
XML 1176                if (isSelected)
XML 1177XML 1178                XML 1179{
XML 1180                    idstring += “‘” + key + “‘” + “,”; //前后追加单引号,能够其余非数值的ID
XML 1181                }
XML 1182            }
XML 1183            idstring = idstring.Trim(‘,’);
XML 1184
XML 1185            return idstring;
XML 1186        }
XML 1187
XML 1188
XML 1189XML 1190        /**//// <summary>
XML 1191        /// 设置下列列表控件的SelectedValue
XML 1192        /// </summary>
XML 1193        /// <param name=”control”>DropDownList控件</param>
XML 1194        /// <param name=”strValue”>SelectedValue的值</param>
XML 1195        public static void SetDropDownListItem(DropDownList control, string strValue)
XML 1196XML 1197        XML 1198{
XML 1199            if (!IsNullorEmpty(strValue))
XML 1200XML 1201            XML 1202{
XML 1203                control.ClearSelection();
XML 1204                ListItem item = control.Items.FindByValue(strValue);
XML 1205                if (item != null)
XML 1206XML 1207                XML 1208{
XML 1209                    control.SelectedValue = item.Value;
XML 1210                }
XML 1211            }
XML 1212        }
XML 1213    }

Web界面层操作的帮忙类测试代码

XML 1214        private void btnShowError_Click(object sender, EventArgs e)
XML 1215XML 1216        XML 1217{
XML 1218            try
XML 1219XML 1220            XML 1221{
XML 1222                throw new Exception(“测试错误”);
XML 1223            }
XML 1224            catch (Exception ex)
XML 1225XML 1226            XML 1227{
XML 1228                UIHelper.ShowError(this, ex, false);
XML 1229                return;
XML 1230            }
XML 1231        }
XML 1232
XML 1233        private void btnAlert_Click(object sender, EventArgs e)
XML 1234XML 1235        XML 1236{
XML 1237            UIHelper.Alert(“那是一个提示新闻”, this);
XML 1238        }

相关文章

网站地图xml地图