WPF / Silverlight中的 Timer 与 DispatcherTimer 有什么区别呢? 这里我给大家简单介绍一下他们在使用和实现上的区别。 在一个应用程序中,Timer会重复生成time事件,而DispatcherTimer是一个集成到了Dispatcher队列中的时钟,这可以使它被按照指定的时间间隔以指定的priority定期执行。 对于一个Timer时钟事件,系统并不能保证在时间间隔到达后被立即执行,但是能够确保在时间间隔到达之前不被执行。这是因为DispatcherTimer像其他操作一样被放置在了Dispatcher队列中。何时执行DispatcherTimer事件依赖于队列中的其他任务以及他们的优先级. 如果一个WPF应用程序使用了Timer时钟,那么它的事件必须在一个单独的时钟线程中运行,而不是在UI线程中,这对于WPF应用程序毫无用处——你没法在UI线程之外直接访问UI元素,而只能通过Invoke或者BeginInvoke将操作发送给Dispatcher 对象,委托Dispatcher去执行UI操作。 看到这里,你大概知道了为什么我们在WPF中应该用DispatcherTimer而不是Timer了:DispatcherTimer与Dispatcher运行于同一个线程中——UI线程,而且具有相同的DispatcherPriority优先级。 所以,在WPF/Silverlight应用中,正确的做法如下所示:
1 2 3 4 |
DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(10); //10秒 timer.Tick += new EventHandler(timer_Tick); timer.Start(); |
1 2 3 4 |
private void timer1_Tick(object sender, EventArgs e) { //(你的定时处理) } |
参考:http://www.roboby.com/the_different_bitween_timer_and_dispatchertimer_in_wpf.html
View Details这年头找个正经能用的东西那是真难,网上一搜索一大堆,正经能用的没几个,得,最后还是得靠自己,正巧遇上需要AES加解密的地方了,而且还是Java和C#间的相互加解密操作,这里做个备忘 这里采用的加解密使用base64转码方法,ECB模式,PKCS5Padding填充,密码必须是16位,否则会报错哈 模式:Java的ECB对应C#的System.Security.Cryptography.CipherMode.ECB 填充方法:Java的PKCS5Padding对应C#System.Security.Cryptography.PaddingMode.PKCS7 Java和C#版的加解密是互通的,也就是能相互加解密,编码明确指定了采用UTF-8,有需要其他编码方法的请自行扩展 Java版
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 |
package nb.tmall.util; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import sun.misc.*; @SuppressWarnings("restriction") public class EncryptUtil { public static String aesEncrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); byte[] bytes = cipher.doFinal(str.getBytes("utf-8")); return new BASE64Encoder().encode(bytes); } public static String aesDecrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); byte[] bytes = new BASE64Decoder().decodeBuffer(str); bytes = cipher.doFinal(bytes); return new String(bytes, "utf-8"); } } |
C#版
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 |
using System; using System.Security.Cryptography; using System.Text; namespace CSharp.Util.Security { /// <summary> /// AES 加密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES 解密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } } } |
from:http://www.cnblogs.com/lzrabbit/p/3639503.html
View Details1. 一个控制台例子,实现动态生成Word。 首先,添加引用:COM->Microsoft Word 11.0 Object Library。
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Microsoft.Office.Interop.Word; using System.Reflection; namespace TestWord { class Program { static void Main(string[] args) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; //endofdoc是预定义的bookmark //创建一个document. Microsoft.Office.Interop.Word._Application oWord; Microsoft.Office.Interop.Word._Document oDoc; oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //在document的开始部分添加一个paragraph. Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt 行间距 oPara1.Range.InsertParagraphAfter(); //在当前document的最后添加一个paragraph Microsoft.Office.Interop.Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //接着添加一个paragraph Microsoft.Office.Interop.Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //添加一个3行5列的表格,填充数据,并且设定第一行的样式 Microsoft.Office.Interop.Word.Table oTable; Microsoft.Office.Interop.Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for (r = 1; r <= 3; r++) for (c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //接着添加一些文字 Microsoft.Office.Interop.Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "And here's another table:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //添加一个5行2列的表,填充数据并且改变列宽 wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for (r = 1; r <= 5; r++) for (c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Columns[1].Width = oWord.InchesToPoints(2); //设置列宽 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Microsoft.Office.Interop.Word.WdInformation.wdVerticalPositionRelativeToPage); } while (dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertBreak(ref oPageBreak); wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); wrdRng.InsertParagraphAfter(); //添加一个chart Microsoft.Office.Interop.Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 4; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); Console.ReadLine(); } } } |
2. 介绍几篇牛人写的关于操作Word的文章 [分享]一段导出到word模版的代码 http://www.cnblogs.com/goody9807/archive/2005/08/25/222526.html 再谈word2003编程 http://www.cnblogs.com/Andmm/archive/2008/06/18/1224422.html 最近一直在做C#操作office方面的工作!总结一下!Word(二) http://www.cnblogs.com/wngwz/archive/2004/08/19/34678.html C#也能动态生成Word文档并填充数据 http://www.cnblogs.com/qyfan82/archive/2007/09/14/893293.html from:http://www.cnblogs.com/tianzhiliang/archive/2011/07/07/2099800.html
View Details引用http://blog.csdn.net/mengyao/archive/2007/09/13/1784079.aspx using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.Office.Interop.Word; namespace WindowsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { CreateWordFile("c:\\dd.doc"); } public string CreateWordFile(string CheckedInfo) { string message = ""; try { Object Nothing = System.Reflection.Missing.Value; Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录 string name = "CNSI_" + DateTime.Now.ToLongDateString()+".doc"; object filename = "C://CNSI//" + name; //文件保存路径 //创建Word文档 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //添加页眉 WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]"); WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距 //移动焦点并换行 object count = 14; object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行; WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 WordApp.Selection.TypeParagraph();//插入段落 //文档中创建表格 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing); //设置表格样式 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap; newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; newTable.Columns[1].Width = 100f; newTable.Columns[2].Width = 220f; newTable.Columns[3].Width = 105f; //填充表格内容 newTable.Cell(1, 1).Range.Text = "产品详细信息表"; newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体 //合并单元格 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3)); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 //填充表格内容 newTable.Cell(2, 1).Range.Text = "产品基本信息"; newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色 //合并单元格 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3)); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //填充表格内容 newTable.Cell(3, 1).Range.Text = "品牌名称:"; newTable.Cell(3, 2).Range.Text = "BrandName"; //纵向合并单元格 newTable.Cell(3, 3).Select();//选中一行 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object moveCount = 5; object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend; WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend); WordApp.Selection.Cells.Merge(); //插入图片 string FileName = @"c:\picture.jpg";//图片所在路径 object LinkToFile = false; object SaveWithDocument = true; object Anchor = WordDoc.Application.Selection.Range; WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度 //将图片设置为四周环绕型 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); […]
View Details一. 二进制转换成图片 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Image img = Image.FromStream(ms); ms.Close(); this.pictureBox1.Image 二. C#中byte[]与string的转换代码 1、System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); byte[] inputBytes =converter.GetBytes(inputString); string inputString = converter.GetString(inputBytes); 2、string inputString = System.Convert.ToBase64String(inputBytes); byte[] inputBytes = System.Convert.FromBase64String(inputString); FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); 三. C# Stream 和 byte[] 之间的转换 /// 将 Stream 转成 byte[] public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// 将 byte[] 转成 Stream public Stream BytesToStream(byte[] bytes) { Stream stream = new […]
View Details1:添加记录后,如何获取新添加的ID的值 比如,一个实体 TestEntity 对应一个表TestEntity(ID主键自增,Name,age),使用linq to ef 添加一条记录后,如何获取新记录的ID值?如下代码:
1 |
var te = new TestEntity () { Name = "名字", Age = 21 }; using (EFDbContext context = new EFDbContext()) { context.TestEntity .Add(te); context.SaveChanges(); return te.ID; } |
调用SaveChanges()之后,ef.ID的值就是数据库中新加记录对应自增标识列的值。Linq to ef智能地判断出ID就是自增主键标识列。 他给我们返回了。 2:列名叫“ID”的列,它不是自增列,linq to ef不让插入的问题 如标题,就是,列名叫“ID”的列,它不是主键,也不是主键,linq to ef不让插入。我已经给ID赋值了 但它一直提示 ID不能为NULL ,打断点,看了,也有值! 代码走到SaveChanges(),就报异常,提示ID不能为空!超蛋疼… 原因:默认情况,linq to ef认为只要实体类中有ID属性,数据库对应的是一定是自增标识列。 解决方式: 1)第一步 因为EFDbContex继承自Context类,所以,我们需要从新对它这个叫OnModelCreating的虚函数进行实现
1 |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TestEntity>().Property(p => p.ID) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); } |
2)第二步 在实体类叫ID的属性上加标记实现(记得添加引用):
1 |
public class TestEntity { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } |
from:http://www.ithao123.cn/content-2766171.html
View Details准备一些测试数据,如下: use Test Create table Student( ID int identity(1,1) primary key, [Name] nvarchar(50) not null ) Create Table Book( ID int identity(1,1) primary key, [Name] nvarchar(50)not null, StudentID int not null ) insert into Student values('张三') insert into Student values('李四') insert into Student values('王五') select * from student --张三借的书 insert into Book values('红楼',1) insert into Book values('大话红楼',1) --李四借的书 insert into Book values('三国',2) --王五没借书 --一本错误的记录 insert into Book values('错误时怎样练成的',111) --左连接 select s.name,b.name from student as s left join Book as b on s.id=b.studentid --右连接 select s.name,b.name from student […]
View Detailsusing System; using System.Data; using System.Configuration; using System.Collections; using System.Drawing; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class study_CheckCode2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string code = CreateVerifyCode(); //取随机码 CreateImageOnPage(code, this.Context); // 输出图片 Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper()));// 使用Cookies取验证码的值 } #region 验证码长度(默认4个验证码的长度) int length = 4; public int Length { get { return length; } set { length = value; } } #endregion […]
View DetailsC#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值 总结: 对应某个类的实例化的对象tc, 遍历获取所有属性(子成员)的方法(采用反射): Type t = tc.GetType();//获得该类的Type //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了 foreach (PropertyInfo pi in t.GetProperties { object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值 string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作 //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数 if(value1.GetType() == typeof(int)) { //进行你想要的操作 } } 注意: 必须要设置了get 和set方法的属性,反射才能获得该属性 public int Pid { get { return pid; } set { pid = value; } } from:http://virgoooos.iteye.com/blog/623561
View Details