D3.js 制作中国地图 .net 公共基础类

D3.js 制作中国地图

from:  http://d3.decembercafe.org/pages/map/index.html

GeoJSON is a format for encoding a variety of geographic data structures.

http://geojson.org/

https://msdn.microsoft.com/en-us/library/mt712806.aspx

GeoJSON 是用于描述地理空间信息的数据格式。GeoJSON 不是一种新的格式,其语法规范是符合 JSON 格式的,只不过对其名称进行了规范,专门用于表示地理信息。

GeoJSON 的最外层是一个单独的对象(object)。这个对象可表示:

几何体(Geometry)。

特征(Feature)。

特征集合(FeatureCollection)。

最外层的 GeoJSON 里可能包含有很多子对象,每一个 GeoJSON 对象都有一个 type 属性,表示对象的类型,type 的值必须是下面之一。

Point:点。

MultiPoint:多点。

LineString:线。

MultiLineString:多线。

Polygon:面。

MultiPolygon:多面。

GeometryCollection:几何体集合。

Feature:特征。

FeatureCollection:特征集合。

在线工具

在线生成 GeoJSON:http://geojson.io/

简化、转换 GeoJSON 和 TopoJSON:http://mapshaper.org/

 https://pypi.org/project/geojson/

https://github.com/d3/d3/wiki

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<! DOCTYPE  html>
< html  lang="en">
   < head
         < meta  charset="utf-8"> 
         < title >中国地图</ title
   </ head >
< style >
 
</ style >
< body >
< script  src="d3.v3.min.js"></ script >
< script >
     var width  = 1000;
     var height = 1000;
     
     var svg = d3.select("body").append("svg")
         .attr("width", width)
         .attr("height", height)
         .append("g")
         .attr("transform", "translate(0,0)");
     
     var projection = d3.geo.mercator()
                         .center([107, 31])
                         .scale(850)
                         .translate([width/2, height/2]);
     
     var path = d3.geo.path()
                     .projection(projection);
     
     
     var color = d3.scale.category20();
     
     
     d3.json("china.geojson", function(error, root) {
         
         if (error)
             return console.error(error);
         console.log(root.features);
         
         svg.selectAll("path")
             .data( root.features )
             .enter()
             .append("path")
             .attr("stroke","#000")
             .attr("stroke-width",1)
             .attr("fill", function(d,i){
                 return color(i);
             })
             .attr("d", path )
             .on("mouseover",function(d,i){
                 d3.select(this)
                     .attr("fill","yellow");
             })
             .on("mouseout",function(d,i){
                 d3.select(this)
                     .attr("fill",color(i));
             });
         
     });
 
</ script >
     
</ body
</ html

  https://www.webdesignerdepot.com/2009/06/50-great-examples-of-data-visualization/

 

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)成功.---Geovin Du(涂聚文)
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
using  WL.Infrastructure.Http;
using  System;
using  System.Collections.Generic;
using  System.IO;
using  System.Linq;
using  System.Text;
using  System.Text.RegularExpressions;
using  System.Web;
using  System.Drawing;
using  System.Drawing.Imaging;
using  System.Drawing.Drawing2D;
 
namespace  WL.Infrastructure.Common
{
     public  class  Common
     {
         private  static  int  seed = 1;
         private  static  int  key_seed = 1;
         private  static  int  noseed = 1;
         private  static  int  domseed = 1;
         private  static  int  geseed = 1;
         /// <summary>
         /// 取得客户端真实IP。如果有代理则取第一个非内网地址
         /// </summary>
         public  static  string  IPAddress
         {
             get
             {
                 string  result = String.Empty;
 
                 result = HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ];
                 if  (result !=  null  && result != String.Empty)
                 {
                     //可能有代理;
                     if  (result.IndexOf( "." ) == -1)     //没有“.”肯定是非IPv4格式;
                         result =  null ;
                     else
                     {
                         if  (result.IndexOf( "," ) != -1)
                         {
                             //有“,”,估计多个代理。取第一个不是内网的IP。;
                             result = result.Replace( " " "" ).Replace( "'" "" );
                             string [] temparyip = result.Split( ",;" .ToCharArray());
                             for  ( int  i = 0; i < temparyip.Length; i++)
                             {
                                 if  (IsIPAddress(temparyip[i])
                                     && temparyip[i].Substring(0, 3) !=  "10."
                                     && temparyip[i].Substring(0, 7) !=  "192.168"
                                     && temparyip[i].Substring(0, 7) !=  "172.16." )
                                 {
                                     return  temparyip[i];     //找到不是内网的地址 ;
                                 }
                             }
                         }
                         else  if  (IsIPAddress(result))  //代理即是IP格式;
                             return  result;
                         else
                             result =  null ;     //代理中的内容 非IP,取IP ;
                     }
 
                 }
 
                 string  IpAddress = (HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ] !=  null  && HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ] != String.Empty) ? HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ] : HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR" ];
 
 
 
                 if  ( null  == result || result == String.Empty)
                     result = HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR" ];
 
                 if  (result ==  null  || result == String.Empty)
                     result = HttpContext.Current.Request.UserHostAddress;
                 if  (result ==  "::1" )
                 {
                     result =  "127.0.0.1" ;
                 }
                 return  result;
             }
         }
         /// <summary>
         /// 绕过cnd获取真实ip
         /// </summary>
         /// <returns></returns>
         public  static  string  GetUserIp()
         {
             string  userIP =  "未获取用户IP" ;
 
             try
             {
                 if  (HttpContext.Current ==  null
             || HttpContext.Current.Request ==  null
             || HttpContext.Current.Request.ServerVariables ==  null )
                     return  "" ;
 
                 string  CustomerIP =  "" ;
 
                 //CDN加速后取到的IP 
                 CustomerIP = HttpContext.Current.Request.Headers[ "Cdn-Src-Ip" ];
                 if  (! string .IsNullOrEmpty(CustomerIP))
                 {
                     return  CustomerIP;
                 }
 
                 CustomerIP = HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ];
 
                 if  (!String.IsNullOrEmpty(CustomerIP))
                     return  CustomerIP;
 
                 if  (HttpContext.Current.Request.ServerVariables[ "HTTP_VIA" ] !=  null )
                 {
                     CustomerIP = HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ];
                     if  (CustomerIP ==  null )
                         CustomerIP = HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR" ];
                 }
                 else
                 {
                     CustomerIP = HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR" ];
 
                 }
 
                 if  ( string .Compare(CustomerIP,  "unknown" true ) == 0)
                     return  HttpContext.Current.Request.UserHostAddress;
                 return  CustomerIP;
             }
             catch  { }
 
             return  userIP;
         }
         /**/
         /// <summary>
         /// 判断是否是IP地址格式 0.0.0.0
         /// </summary>
         /// <param name="str1">待判断的IP地址</param>
         /// <returns>true or false</returns>
         public  static  bool  IsIPAddress( string  str1)
         {
             if  (str1 ==  null  || str1 ==  string .Empty || str1.Length < 7 || str1.Length > 15)  return  false ;
 
             string  regformat =  @"^/d{1,3}[/.]/d{1,3}[/.]/d{1,3}[/.]/d{1,3}$" ;
 
             Regex regex =  new  Regex(regformat, RegexOptions.IgnoreCase);
             return  regex.IsMatch(str1);
         }
         /// <summary>
         /// 时间转换时间戳
         /// </summary>
         /// <param name="time"></param>
         /// <returns></returns>
         public  static  string  ConvertDateTimeInt( string  time)
         {
             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime( new  DateTime(1970, 1, 1));
             DateTime dtNow = DateTime.Parse(time);
             TimeSpan toNow = dtNow.Subtract(dtStart);
             string  timeStamp = toNow.Ticks.ToString();
             timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
             return  timeStamp;
         }
         /// <summary>
         /// 时间戳转换时间
         /// </summary>
         /// <param name="datestr"></param>
         /// <returns></returns>
         public  static  DateTime ConvertDate( string  datestr)
         {
             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime( new  DateTime(1970, 1, 1));
             long  lTime =  long .Parse(datestr +  "0000000" );
             TimeSpan toNow =  new  TimeSpan(lTime);
             DateTime dtResult = dtStart.Add(toNow);
             return  dtResult;
         }
         /// <summary>
         /// 转换时间
         /// </summary>
         /// <param name="time"></param>
         /// <returns></returns>
         public  static  string  ConvertDateTimeInt_flot( string  time)
         {
             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime( new  DateTime(1970, 1, 1));
             DateTime dtNow = DateTime.Parse(time);
             TimeSpan toNow = dtNow.Subtract(dtStart);
             string  timeStamp = toNow.Ticks.ToString();
             timeStamp = timeStamp.Substring(0, timeStamp.Length - 4);
             return  timeStamp;
         }
         /// <summary>
         /// 上传
         /// </summary>
         /// <param name="_rootPath"></param>
         /// <param name="_file"></param>
         /// <param name="_filename"></param>
         /// <param name="type_s"></param>
         /// <returns></returns>
         public  static  string  FileUploader( string  _rootPath, HttpPostedFileBase _file,  string  _filename =  null string  type_s =  "" )
         {
             string  sFileName = _filename;
             if  (_file !=  null )
             {
                 string  _filePath = _file.FileName;
                 if  (_filePath !=  string .Empty)
                 {
                     string  _fileType = _filePath.Substring(_filePath.LastIndexOf( "." ));
                     string  sFileRoot = _rootPath;
                     if  (!System.IO.Directory.Exists(sFileRoot))
                         System.IO.Directory.CreateDirectory(sFileRoot);
                     if  (sFileName ==  null )
                     {
                         if  (type_s !=  "" )
                         {
                             sFileName = DateTime.Now.ToString( "yyyyMMddHHmmssms" ) + type_s;
                         }
                         else
                         {
                             sFileName = DateTime.Now.ToString( "yyyyMMddHHmmssms" ) + _fileType;
                         }
                     }
                     else
                     {
                         if  (type_s !=  "" )
                         {
                             sFileName = sFileName + type_s;
                         }
                         else
                         {
                             sFileName = sFileName + _fileType;
                         }
                     }
                     string  sFilePath = sFileRoot +  "\\"  + sFileName;
                     _file.SaveAs(sFilePath);
                 }
             }
             return  sFileName;
         }
         /// <summary>
         /// 根据路径把文件转换成数据流
         /// </summary>
         /// <param name="strpath"></param>
         /// <returns></returns>
         public  static  byte [] Returnbyte( string  strpath)
         {
             // 以二进制方式读文件
             FileStream fsMyfile =  new  FileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
             // 创建一个二进制数据流读入器,和打开的文件关联
             BinaryReader brMyfile =  new  BinaryReader(fsMyfile);
             // 把文件指针重新定位到文件的开始
             brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
             byte [] bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
             // 关闭以上new的各个对象
             brMyfile.Close();
             return  bytes;
         }
         public  static  void  DeleteFile( string  filepatch)
         {
             FileInfo file =  new  FileInfo(filepatch); //指定文件路径
             if  (file.Exists) //判断文件是否存在
             {
                 file.Attributes = FileAttributes.Normal; //将文件属性设置为普通,比方说只读文件设置为普通
                 file.Delete(); //删除文件
             }
         }
         /// 取得某月的第一天
         /// </summary>
         /// <param name="datetime">要取得月份第一天的时间</param>
         /// <returns></returns>
         private  DateTime FirstDayOfMonth(DateTime datetime)
         {
             return  datetime.AddDays(1 - datetime.Day);
         }
         /// <summary>
         /// 取得某月的最后一天
         /// </summary>
         /// <param name="datetime">要取得月份最后一天的时间</param>
         /// <returns></returns>
         private  DateTime LastDayOfMonth(DateTime datetime)
         {
             return  datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
         }
 
         /// <summary>
         /// 取得上个月第一天
         /// </summary>
         /// <param name="datetime">要取得上个月第一天的当前时间</param>
         /// <returns></returns>
         public  DateTime FirstDayOfPreviousMonth(DateTime datetime)
         {
             return  datetime.AddDays(1 - datetime.Day).AddMonths(-1);
         }
 
         /// <summary>
         /// 取得上个月的最后一天
         /// </summary>
         /// <param name="datetime">要取得上个月最后一天的当前时间</param>
         /// <returns></returns>
         public  DateTime LastDayOfPrdviousMonth(DateTime datetime)
         {
             return  datetime.AddDays(1 - datetime.Day).AddDays(-1);
         }
 
         /// <summary>
         /// 取得上周的第一天
         /// </summary>
         /// <param name="datetime">要取得上周最后一天的当前时间</param>
         /// <returns></returns>
         public  static  DateTime FirstDayOfPrdviousWeek(DateTime datetime)
         {
             //星期一为第一天 
             int  weeknow = Convert.ToInt32(datetime.DayOfWeek);
  
             //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。 
             weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
             int  daydiff = (-1) * weeknow;
  
             //本周第一天 
             string  FirstDay = datetime.AddDays(daydiff).ToString( "yyyy-MM-dd" );
             return  Convert.ToDateTime(FirstDay);
         }
 
         /// <summary>
         /// 取得上周的最后一天
         /// </summary>
         /// <param name="datetime">要取得上周最后一天的当前时间</param>
         /// <returns></returns>
         public  static  DateTime LastDayOfPrdviousWeek(DateTime datetime)
         {
             //星期天为最后一天 
             int  weeknow = Convert.ToInt32(datetime.DayOfWeek);
             weeknow = (weeknow == 0 ? 7 : weeknow);
             int  daydiff = (7 - weeknow);
 
             //本周最后一天 
             string  LastDay = datetime.AddDays(daydiff).ToString( "yyyy-MM-dd" );
             return  Convert.ToDateTime(LastDay);
         }
 
         /// <summary>
         /// 判断字符串是否为正整数
         /// </summary>
         /// <param name="str">要判断的字符串对象</param>
         /// <returns></returns>
         public  static  bool  IsInt( string  str)
         {
             bool  isInt =  false ;
             if  (! string .IsNullOrEmpty(str))
             {
                 isInt = Regex.IsMatch(str,  @"^(0|([1-9]\d*))$" );
             }
             return  isInt;
         }
 
         /// <summary>
         /// 判断是否为DateTime
         /// </summary>
         /// <param name="strDate"></param>
         /// <returns></returns>
         public  static  bool  IsDateTime( string  strDate)
         {
             try
             {
                 DateTime.Parse(strDate);
                 return  true ;
             }
             catch
             {
                 return  false ;
             }
         }
 
         /// <summary>
         /// 生成单号
         /// </summary>
         /// <param name="channel"></param>
         /// <returns></returns>
         public  static  string  GetOrderNo()
         {
             if  (seed ==  int .MaxValue)
             {
                 seed = 1;
             }
             seed++;
             string  tbout_trade_no =  "" ;
             string  guid = Guid.NewGuid().ToString();
             string  last = guid.Replace( "-" "" );
             char [] cc = last.ToCharArray();
             StringBuilder sb =  new  StringBuilder(4);
             Random rd =  new  Random(( unchecked (( int )DateTime.Now.Ticks + seed)));
             for  ( int  i = 0; i < 6; i++)
             {
                 sb.Append(cc[rd.Next(cc.Length)]);
             }
 
             tbout_trade_no = sb +  "-"  + DateTime.Now.ToString( "yyyyMMddHHmmssff" );
             return  tbout_trade_no;
         }
         /// <summary>
         /// 生成密匙
         /// </summary>
         /// <param name="mch_id"></param>
         /// <returns></returns>
         public  static  string  GetGGAPIKey( string  num_id)
         {
             if  (key_seed ==  int .MaxValue)
             {
                 key_seed = 1;
             }
             key_seed++;
             string  key =  "" ;
             char [] constant = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' ,
                                'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' ,
                                'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' };
             StringBuilder sb =  new  StringBuilder(4);
             for  ( int  i = 0; i < 5; i++)
             {
                 Random rd =  new  Random(( unchecked (( int )DateTime.Now.Ticks + i)));
                 sb.Append(constant[rd.Next(62)]);
             }
             key = MD5.Md5UTF8(num_id + sb).ToLower();
             return  key;
         }
         /// <summary>
         /// PostUTF8格式的JSON
         /// </summary>
         /// <param name="json"></param>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  string  PostUtf8Json( string  json,  string  url,  int  timeout = 1000000)
         {
             byte [] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
             HttpHelper helper =  new  HttpHelper();
             HttpItem item =  new  HttpItem();
             item.URL = url;
             item.Timeout = timeout;
             item.Method =  "POST" ;
             item.PostdataByte = encodebytes;
             item.PostEncoding = Encoding.UTF8;
             item.PostDataType = PostDataType.Byte;
             HttpResult result = helper.GetHtml(item);
             string  msg =  "" ;
             if  (( int )result.StatusCode < 400)
             {
                 msg = result.Html;
                 if  (msg ==  "操作超时" )
                 {
                     //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
                     msg =  "" ;
                 }
             }
             else
             {
                 //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
             }
             return  msg;
         }
         /// <summary>
         /// PostUTF8格式的Form
         /// </summary>
         /// <param name="json"></param>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  string  PostUtf8Form( string  json,  string  url,  int  timeout = 1000000)
         {
             byte [] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
             HttpHelper helper =  new  HttpHelper();
             HttpItem item =  new  HttpItem();
             item.URL = url;
             item.Timeout = timeout;
             item.Method =  "POST" ;
             item.Allowautoredirect =  true ;
             item.ContentType =  "application/x-www-form-urlencoded" ;
             item.PostdataByte = encodebytes;
             item.PostEncoding = Encoding.UTF8;
             item.PostDataType = PostDataType.Byte;
             HttpResult result = helper.GetHtml(item);
             string  msg =  "" ;
             if  (( int )result.StatusCode < 400)
             {
                 msg = result.Html;
                 if  (msg ==  "操作超时" )
                 {
                     //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
                     msg =  "" ;
                 }
             }
             else
             {
                 //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
             }
             return  msg;
         }
         /// <summary>
         /// PostGB2312格式的表单
         /// </summary>
         /// <param name="json"></param>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  string  PostGB2312Form( string  json,  string  url,  int  timeout = 5000)
         {
             byte [] encodebytes = System.Text.Encoding.GetEncoding( "GB2312" ).GetBytes(json);
             HttpHelper helper =  new  HttpHelper();
             HttpItem item =  new  HttpItem();
             item.URL = url;
             item.Timeout = timeout;
             item.Method =  "POST" ;
             item.Allowautoredirect =  true ;
             item.ContentType =  "application/x-www-form-urlencoded" ;
             item.PostdataByte = encodebytes;
             item.PostEncoding = Encoding.GetEncoding( "GB2312" );
             item.PostDataType = PostDataType.Byte;
             HttpResult result = helper.GetHtml(item);
             string  msg =  "" ;
             if  (( int )result.StatusCode < 400)
             {
                 msg = result.Html;
                 if  (msg ==  "操作超时" )
                 {
                     //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
                     msg =  "" ;
                 }
             }
             else
             {
                 //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
             }
             return  msg;
         }
         /// <summary>
         /// PostUTF8格式的JSON
         /// </summary>
         /// <param name="json"></param>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  string  PostUtf8File( byte [] encodebytes,  string  url,  int  timeout = 1000000)
         {
             //byte[] encodebytes = System.Text.Encoding.UTF8.GetBytes(json);
             HttpHelper helper =  new  HttpHelper();
             HttpItem item =  new  HttpItem();
             item.URL = url;
             item.Timeout = timeout;
             item.Method =  "POST" ;
             item.ContentType =  "multipart/form-data" ;
             item.PostdataByte = encodebytes;
             item.PostEncoding = Encoding.UTF8;
             item.PostDataType = PostDataType.Byte;
             HttpResult result = helper.GetHtml(item);
             string  msg =  "" ;
             if  (( int )result.StatusCode < 400)
             {
                 msg = result.Html;
                 if  (msg ==  "操作超时" )
                 {
                     //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
                     msg =  "" ;
                 }
             }
             else
             {
                 //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
             }
             return  msg;
         }
         /// <summary>
         /// Get格式
         /// </summary>
         /// <param name="json"></param>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  string  GetUrl( string  url,  int  timeout = 1000000)
         {
             HttpHelper helper =  new  HttpHelper();
             HttpItem item =  new  HttpItem();
             item.Timeout = timeout;
             item.URL = url;
             HttpResult result = helper.GetHtml(item);
             string  msg =  "" ;
             if  (( int )result.StatusCode < 400)
             {
                 msg = result.Html;
                 if  (msg ==  "操作超时" )
                 {
                     //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
                     msg =  "" ;
                 }
             }
             else
             {
                 //LoggerFactory.Current.Create().LogError("请求错误,状态码为" + (int)result.StatusCode + ",url为" + url);
             }
             return  msg;
         }
         /// <summary>
         /// 生成随机字符串
         /// </summary>
         /// <returns></returns>
         public  static  string  get_noce_str()
         {
             if  (noseed ==  int .MaxValue)
             {
                 noseed = 1;
             }
             noseed++;
             char [] constant = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' ,
                                'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' ,
                                'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' };
             StringBuilder sb =  new  StringBuilder(16);
             Random rd =  new  Random(( unchecked (( int )DateTime.Now.Ticks + noseed)));
             for  ( int  i = 0; i < 16; i++)
             {
                 sb.Append(constant[rd.Next(62)]);
             }
             return  sb.ToString();
         }
         /// <summary>
         /// 生成6位邀请码
         /// </summary>
         /// <returns></returns>
         public  static  string  get_generate_str()
         {
             if  (geseed ==  int .MaxValue)
             {
                 geseed = 1;
             }
             geseed++;
             char [] constant = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' ,
                                'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' ,
                                'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' };
             StringBuilder sb =  new  StringBuilder(6);
             Random rd =  new  Random(( unchecked (( int )DateTime.Now.Ticks + geseed)));
             for  ( int  i = 0; i < 6; i++)
             {
                 sb.Append(constant[rd.Next(62)]);
             }
             return  sb.ToString();
         }
         /// <summary>
         /// 生成6位订单号
         /// </summary>
         /// <returns></returns>
         public  static  string  Nrandom()
         {
             if  (domseed ==  int .MaxValue)
             {
                 domseed = 1;
             }
             domseed++;
             string  rm =  "" ;
             Random rd =  new  Random(( unchecked (( int )DateTime.Now.Ticks + domseed)));
             for  ( int  i = 0; i < 6; i++)
             {
                 rm += rd.Next(0, 9).ToString();
             }
             return  rm;
         }
         /// <summary>
         /// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
         /// </summary>
         /// <param name="sArray">需要拼接的数组</param>
         /// <param name="code">字符编码</param>
         /// <returns>拼接完成以后的字符串</returns>
         public  static  string  CreateLinkStringA(SortedDictionary< string string > dicArray)
         {
             StringBuilder prestr =  new  StringBuilder();
             foreach  (KeyValuePair< string string > temp  in  dicArray)
             {
                 prestr.Append(temp.Key +  "="  + temp.Value +  "&" );
             }
 
             //去掉最後一個&字符
             int  nLen = prestr.Length;
             prestr.Remove(nLen - 1, 1);
 
             return  prestr.ToString();
         }
         /// <summary>
         /// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
         /// </summary>
         /// <param name="sArray">需要拼接的数组</param>
         /// <param name="code">字符编码</param>
         /// <returns>拼接完成以后的字符串</returns>
         public  static  string  CreateLinkStringB(Dictionary< string string > dicArray)
         {
             StringBuilder prestr =  new  StringBuilder();
             foreach  (KeyValuePair< string string > temp  in  dicArray)
             {
                 prestr.Append(temp.Key +  "="  + temp.Value +  "&" );
             }
 
             //去掉最後一個&字符
             int  nLen = prestr.Length;
             prestr.Remove(nLen - 1, 1);
 
             return  prestr.ToString();
         }
         /// <summary>
         /// 把数组所有元素,按照“参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode
         /// </summary>
         /// <param name="sArray">需要拼接的数组</param>
         /// <param name="code">字符编码</param>
         /// <returns>拼接完成以后的字符串</returns>
         public  static  string  CreateLinkStringC(Dictionary< string string > dicArray)
         {
             StringBuilder prestr =  new  StringBuilder();
             foreach  (KeyValuePair< string string > temp  in  dicArray)
             {
                 prestr.Append(temp.Value);
             }
             return  prestr.ToString();
         }
         /// <summary>
         /// 多余字段用指定字符串代替
         /// </summary>
         /// <param name="MaxLength">字符串最大长度</param>
         /// <param name="ReplaceRemark">超出时代替的符号</param>
         /// <param name="value">要转换的字符串</param>
         /// <returns></returns>
         public  static  string  Overflow( int  MaxLength,  string  ReplaceRemark,  string  value)
         {
             if  (value.Length > MaxLength)
             {
                 return  value = value.Remove(MaxLength) + ReplaceRemark;
             }
             return  value;
         }
 
         /// <summary> 
         /// 每隔n个字符插入n个字符 
         /// </summary> 
         /// <param name="input">源字符串</param> 
         /// <param name="interval">间隔字符数</param> 
         /// <param name="value">待插入值</param> 
         /// <returns>返回新生成字符串</returns> 
         public  static  string  InsertFormat( string  input,  int  interval,  string  value)
         {
             for  ( int  i = interval; i < input.Length; i += interval + value.Length)
                 input = input.Insert(i, value);
             return  input;
         }
 
         /// <summary>
         /// 手机号码隐藏中间4位
         /// </summary>
         /// <param name="phone"></param>
         /// <returns></returns>
         public  static  string  HidePhone( string  phone)
         {
             return  Regex.Replace(phone,  "(\\d{3})\\d{4}(\\d{4})" "$1****$2" );
         }
         /// <summary>
         /// 判断是否带http,flase=有,ture=没有
         /// </summary>
         /// <param name="url"></param>
         /// <returns></returns>
         public  static  bool  IsHttp( string  url)
         {
             string  reg =  @"^(http(s)?:\/\/)?(www\.)?[\w-]+(\.\w{2,4})?\.\w{2,4}?(\/)?$" ;
             Regex r =  new  Regex(reg);
             //给网址去所有空格
             string  urlStr = url.Trim();
             Match m = r.Match(urlStr);
 
             //判断是否带http://
             if  (!m.Success)
                 return  false ;
             return  true ;
         }
         #region 得到一周的周一和周日的日期
         /// <summary>
         /// 计算本周的周一日期
         /// </summary>
         /// <returns></returns>
         public  static  DateTime GetMondayDate()
         {
             return  GetMondayDate(DateTime.Now);
         }
         /// <summary>
         /// 计算本周周日的日期
         /// </summary>
         /// <returns></returns>
         public  static  DateTime GetSundayDate()
         {
             return  GetSundayDate(DateTime.Now);
         }
         /// <summary>
         /// 计算某日起始日期(礼拜一的日期)
         /// </summary>
         /// <param name="someDate">该周中任意一天</param>
         /// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
         public  static  DateTime GetMondayDate(DateTime someDate)
         {
             int  i = someDate.DayOfWeek - DayOfWeek.Monday;
             if  (i == -1) i = 6; // i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
             TimeSpan ts =  new  TimeSpan(i, 0, 0, 0);
             return  someDate.Subtract(ts);
         }
         /// <summary>
         /// 计算某日结束日期(礼拜日的日期)
         /// </summary>
         /// <param name="someDate">该周中任意一天</param>
         /// <returns>返回礼拜日日期,后面的具体时、分、秒和传入值相等</returns>
         public  static  DateTime GetSundayDate(DateTime someDate)
         {
             int  i = someDate.DayOfWeek - DayOfWeek.Sunday;
             if  (i != 0) i = 7 - i; // 因为枚举原因,Sunday排在最前,相减间隔要被7减。
             TimeSpan ts =  new  TimeSpan(i, 0, 0, 0);
             return  someDate.Add(ts);
         }
         #endregion
     }
     public  class  ValidateCode
     {
         public  ValidateCode()
         {
         }
         /// <summary>
         /// 验证码的最大长度
         /// </summary>
         public  int  MaxLength
         {
             get  return  10; }
         }
         /// <summary>
         /// 验证码的最小长度
         /// </summary>
         public  int  MinLength
         {
             get  return  1; }
         }
         /// <summary>
         /// 生成验证码
         /// </summary>
         /// <param name="length">指定验证码的长度</param>
         /// <returns></returns>
         public  string  CreateValidateCode( int  length)
         {
             int [] randMembers =  new  int [length];
             int [] validateNums =  new  int [length];
             string  validateNumberStr =  "" ;
             //生成起始序列值
             int  seekSeek =  unchecked (( int )DateTime.Now.Ticks);
             Random seekRand =  new  Random(seekSeek);
             int  beginSeek = ( int )seekRand.Next(0, Int32.MaxValue - length * 10000);
             int [] seeks =  new  int [length];
             for  ( int  i = 0; i < length; i++)
             {
                 beginSeek += 10000;
                 seeks[i] = beginSeek;
             }
             //生成随机数字
             for  ( int  i = 0; i < length; i++)
             {
                 Random rand =  new  Random(seeks[i]);
                 int  pownum = 1 * ( int )Math.Pow(10, length);
                 randMembers[i] = rand.Next(pownum, Int32.MaxValue);
             }
             //抽取随机数字
             for  ( int  i = 0; i < length; i++)
             {
                 string  numStr = randMembers[i].ToString();
                 int  numLength = numStr.Length;
                 Random rand =  new  Random();
                 int  numPosition = rand.Next(0, numLength - 1);
                 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
             }
             //生成验证码
             for  ( int  i = 0; i < length; i++)
             {
                 validateNumberStr += validateNums[i].ToString();
             }
             return  validateNumberStr;
         }
         /// <summary>
         /// 创建验证码的图片
         /// </summary>
         /// <param name="context">要输出到的page对象</param>
         /// <param name="validateNum">验证码</param>
         public  void  CreateValidateGraphic( string  validateCode, HttpContext context)
         {
             Bitmap image =  new  Bitmap(( int )Math.Ceiling(validateCode.Length * 12.0), 22);
             Graphics g = Graphics.FromImage(image);
             try
             {
                 //生成随机生成器
                 Random random =  new  Random();
                 //清空图片背景色
                 g.Clear(Color.White);
                 //画图片的干扰线
                 for  ( int  i = 0; i < 25; i++)
                 {
                     int  x1 = random.Next(image.Width);
                     int  x2 = random.Next(image.Width);
                     int  y1 = random.Next(image.Height);
                     int  y2 = random.Next(image.Height);
                     g.DrawLine( new  Pen(Color.Silver), x1, y1, x2, y2);
                 }
                 Font font =  new  Font( "Arial" , 12, (FontStyle.Bold | FontStyle.Italic));
                 LinearGradientBrush brush =  new  LinearGradientBrush( new  Rectangle(0, 0, image.Width, image.Height),
                  Color.Blue, Color.DarkRed, 1.2f,  true );
                 g.DrawString(validateCode, font, brush, 3, 2);
                 //画图片的前景干扰点
                 for  ( int  i = 0; i < 100; i++)
                 {
                     int  x = random.Next(image.Width);
                     int  y = random.Next(image.Height);
                     image.SetPixel(x, y, Color.FromArgb(random.Next()));
                 }
                 //画图片的边框线
                 g.DrawRectangle( new  Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                 //保存图片数据
                 MemoryStream stream =  new  MemoryStream();
                 image.Save(stream, ImageFormat.Jpeg);
                 //输出图片流
                 context.Response.Clear();
                 context.Response.ContentType =  "image/jpeg" ;
                 context.Response.BinaryWrite(stream.ToArray());
             }
             finally
             {
                 g.Dispose();
                 image.Dispose();
             }
         }
         /// <summary>
         /// 得到验证码图片的长度
         /// </summary>
         /// <param name="validateNumLength">验证码的长度</param>
         /// <returns></returns>
         public  static  int  GetImageWidth( int  validateNumLength)
         {
             return  ( int )(validateNumLength * 12.0);
         }
         /// <summary>
         /// 得到验证码的高度
         /// </summary>
         /// <returns></returns>
         public  static  double  GetImageHeight()
         {
             return  22.5;
         }
 
 
 
         //C# MVC 升级版
         /// <summary>
         /// 创建验证码的图片
         /// </summary>
         /// <param name="containsPage">要输出到的page对象</param>
         /// <param name="validateNum">验证码</param>
         public  byte [] CreateValidateGraphic( string  validateCode)
         {
             Bitmap image =  new  Bitmap(( int )Math.Ceiling(validateCode.Length * 12.0), 22);
             Graphics g = Graphics.FromImage(image);
             try
             {
                 //生成随机生成器
                 Random random =  new  Random();
                 //清空图片背景色
                 g.Clear(Color.White);
                 //画图片的干扰线
                 for  ( int  i = 0; i < 25; i++)
                 {
                     int  x1 = random.Next(image.Width);
                     int  x2 = random.Next(image.Width);
                     int  y1 = random.Next(image.Height);
                     int  y2 = random.Next(image.Height);
                     g.DrawLine( new  Pen(Color.Silver), x1, y1, x2, y2);
                 }
                 Font font =  new  Font( "Arial" , 12, (FontStyle.Bold | FontStyle.Italic));
                 LinearGradientBrush brush =  new  LinearGradientBrush( new  Rectangle(0, 0, image.Width, image.Height),
                  Color.Blue, Color.DarkRed, 1.2f,  true );
                 g.DrawString(validateCode, font, brush, 3, 2);
                 //画图片的前景干扰点
                 for  ( int  i = 0; i < 100; i++)
                 {
                     int  x = random.Next(image.Width);
                     int  y = random.Next(image.Height);
                     image.SetPixel(x, y, Color.FromArgb(random.Next()));
                 }
                 //画图片的边框线
                 g.DrawRectangle( new  Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                 //保存图片数据
                 MemoryStream stream =  new  MemoryStream();
                 image.Save(stream, ImageFormat.Jpeg);
                 //输出图片流
                 return  stream.ToArray();
             }
             finally
             {
                 g.Dispose();
                 image.Dispose();
             }
         }
     }
}

转载于:https://www.cnblogs.com/cjm123/p/9222244.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值