C# UnitTest在VS 2010后有自带框架,但2008和2005最好的选择是NUnit。
具体操作是
1.新建一个library project
2.下载最新版本,然后添加相应版本(.Net 2.0, 3.0)的DLL到项目
3.写测试代码
4.右击项目run tests即可
代码的attribute:
TestFixture for test class
Setup for initialization, not for test cases
Test for each test case
TearDown for clean up after tests like delete test records in database
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Thursday, April 14, 2016
C#之泛型编程generic programing
Sunday, March 6, 2016
C#之OOD
http://blog.csdn.net/hliq5399/article/details/6305335
http://www.cnblogs.com/max007super/archive/2009/02/09/1386980.html
http://www.cnblogs.com/weihai2003/archive/2008/10/24/1319003.html
http://stackoverflow.com/questions/1327544/what-is-the-equivalent-of-javas-final-in-c/1327549#1327549
http://www.cnblogs.com/chenssy/p/3388487.html
http://www.cnblogs.com/max007super/archive/2009/02/09/1386980.html
http://www.cnblogs.com/weihai2003/archive/2008/10/24/1319003.html
http://stackoverflow.com/questions/1327544/what-is-the-equivalent-of-javas-final-in-c/1327549#1327549
http://www.cnblogs.com/chenssy/p/3388487.html
Tuesday, July 21, 2015
Gmail API for C#
安装:
根据这个Quick start:https://developers.google.com/gmail/api/quickstart/dotnet
根据这个Quick start:https://developers.google.com/gmail/api/quickstart/dotnet
权限问题:
static string[] Scopes = { GmailService.Scope.GmailReadonly };
这句代码说明了权限只局限于Read email only,每次运行代码都会先检查权限文件C:\Users\KK\Documents\.credentials(自动生成,如果存在就会Cache)
如果要修改权限,比如改成
tatic string[] Scopes = { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailModify, GmailService.Scope.GmailLabels};
运行代码前先要删除权限文件,因为默认下,它被cached了。
Tuesday, May 19, 2015
Android加密算法: java变成jar然后到dll
Android用定制的BouncyCastle (轻量级加密算法)并且去除key长度限制
1. Java AES encrypt example:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encryptor {
public static String encrypt(String key1, String key2, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:"
+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key1, String key2, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key1 = "Bar12345Bar12345"; // 128 bit key
String key2 = "ThisIsASecretKet";
System.out.println(decrypt(key1, key2,
encrypt(key1, key2, "Hello World")));
}
}
2. JCE Unlimited Strength installation (java JCE download):
http://stackoverflow.com/ questions/6363801/ invalidkeyexception-illegal- key-size-java-code-throwing- exception-for-encryp
将local_policy.jar & US_export_policy.jar覆盖JRE security文件夹中的原始jar
3. How to export jar file in Eclipse (non-runnable jar):
if your code refers other libs, you need to copy the lib's source code in the src folder and compile together and can't use it as a jar reference.
Ref:
http://stackoverflow.com/ questions/15554296/simple- java-aes-encrypt-decrypt- example
1. Java AES encrypt example:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encryptor {
public static String encrypt(String key1, String key2, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:"
+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key1, String key2, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(key2.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key1.getBytes("UTF-8"),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key1 = "Bar12345Bar12345"; // 128 bit key
String key2 = "ThisIsASecretKet";
System.out.println(decrypt(key1, key2,
encrypt(key1, key2, "Hello World")));
}
}
2. JCE Unlimited Strength installation (java JCE download):
http://stackoverflow.com/
将local_policy.jar & US_export_policy.jar覆盖JRE security文件夹中的原始jar
3. How to export jar file in Eclipse (non-runnable jar):
if your code refers other libs, you need to copy the lib's source code in the src folder and compile together and can't use it as a jar reference.
4. convert jar to dll/exe for .Net by ikvm:
Ref:
http://stackoverflow.com/
Monday, February 2, 2015
Selenium in C# - Browser Automation
OpenQA.Selenium:
Start: http://docs.seleniumhq.org/docs/03_webdriver.jsp
SetPreference: http://seleniumeasy.com/selenium-tutorials/firefox-profile-preferences-using-selenium-webdriver
FindElement(By): http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/By.html?_sm_au_=iVVsMF35HZfF7QWj
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.http", "1234");
FirefoxDriver browser = new FirefoxDriver(profile);
browser.PageSource.Contains("abcd");
IWebElement total = browser.FindElement(By.ClassName("ddd"));//css class
String totalStr = total.Text;
ReadOnlyCollection<IWebElement> children = total.FindElements(By.ClassName("eee")).FindElement(By.ClassName("fff"));
foreach (IWebElement product in children){}
String innerHtml = total.GetAttribute("innerHTML");
total.Click();
//selelium's approach: scroll an element into view
browser.ExecuteJavaScript("arguments[0].scrollIntoView(true);", total);
xpath
("//div[@class='abc']")[1]
("//div[contains(@class, 'abc']")//h4[contains(text(), 'bb')]
Start: http://docs.seleniumhq.org/docs/03_webdriver.jsp
SetPreference: http://seleniumeasy.com/selenium-tutorials/firefox-profile-preferences-using-selenium-webdriver
FindElement(By): http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/By.html?_sm_au_=iVVsMF35HZfF7QWj
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.http", "1234");
FirefoxDriver browser = new FirefoxDriver(profile);
browser.PageSource.Contains("abcd");
IWebElement total = browser.FindElement(By.ClassName("ddd"));//css class
String totalStr = total.Text;
ReadOnlyCollection<IWebElement> children = total.FindElements(By.ClassName("eee")).FindElement(By.ClassName("fff"));
foreach (IWebElement product in children){}
String innerHtml = total.GetAttribute("innerHTML");
total.Click();
//selelium's approach: scroll an element into view
browser.ExecuteJavaScript("arguments[0].scrollIntoView(true);", total);
xpath
("//div[@class='abc']")[1]
("//div[contains(@class, 'abc']")//h4[contains(text(), 'bb')]
KB: C#
AppSettingsReader:
Read app.config file
XmlDocument & XmlNode (Read XML file):
XmlDocument configDoc = new XmlDocument();
configDoc.Load(fileName);
XmlNode oneNode = configDoc.SelectSingleNode("//config/");
String abc = botNode.Attributes["proxy"];
Attribute & CustomAttributeData:
FieldInfo[] fs = obj.GetType().GetFields();
foreach (FieldInfo f in fs)
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(f);
foreach (CustomAttributeData attribute in attributes)
{
//check if the field was marked as [ConfigValue]
if (attribute.Constructor.DeclaringType.Equals(typeof(ConfigValue)))
{}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class ConfigValue : Attribute
{
private String prameName;
public ConfigValue(String name)
{
prameName = name;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RegexFile : Attribute
{
private String fileName;
public RegexFile(String name)
{
fileName = name;
}
}
Use:
[ConfigValue]
String proxy;
[RegexFile("rabc.regex")]
private Regex rabc;
Read app.config file
XmlDocument & XmlNode (Read XML file):
XmlDocument configDoc = new XmlDocument();
configDoc.Load(fileName);
XmlNode oneNode = configDoc.SelectSingleNode("//config/");
String abc = botNode.Attributes["proxy"];
Attribute & CustomAttributeData:
FieldInfo[] fs = obj.GetType().GetFields();
foreach (FieldInfo f in fs)
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(f);
foreach (CustomAttributeData attribute in attributes)
{
//check if the field was marked as [ConfigValue]
if (attribute.Constructor.DeclaringType.Equals(typeof(ConfigValue)))
{}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class ConfigValue : Attribute
{
private String prameName;
public ConfigValue(String name)
{
prameName = name;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RegexFile : Attribute
{
private String fileName;
public RegexFile(String name)
{
fileName = name;
}
}
Use:
[ConfigValue]
String proxy;
[RegexFile("rabc.regex")]
private Regex rabc;
Wednesday, April 23, 2014
KB: c#之反射
有时为了使相似度较高的代码智能化,我们会使用到反射。
这是Reflexion的命名空间using System.Reflection;
前面的blog说到C#之Entity framework,提到这段代码:
这是Reflexion的命名空间using System.Reflection;
前面的blog说到C#之Entity framework,提到这段代码:
using (ModelEntities context = new ModelEntities())
{
context.stocks_EF.Add(new stocks_EF() { Symbol = "CAT", Price = 98.42, PricePct = 2.5, Volume = 29389, AvgVolume = 39392, MktCap = "56.5B", Yield = 2.2, PE = 10.2, TradeDate = Convert.ToDateTime("2013-06-17 00:00:00.000") });
context.SaveChanges();
}
public partial class ModelEntities : DbContext
{
public DbSet<stocks_EF> stocks_EF { get; set; }
}
下面我说说怎么用反射写这段代码。
1.已知道类型的Type:Type contextType = typeof(ModelEntities);如果是某instance的type是
obj.GetType()
2. 创建某类型的Instance:object context = Activator.CreateInstance(contextType);
3. 获得某Instance的某属性的值:
object dbSetInstance = contextType.GetProperty(propName).GetValue(context);
4. 获得某Instance的某属性的类型:
Type dbSetType = contextType.GetProperty(propName).PropertyType;
5.获得某类型的某方法:MethodInfo objAddMethod = dbSetType.GetMethod("Add");
6.Call某方法: objAddMethod.Invoke(dbSetInstance, new object[]{obj});
(eg2)7.获得泛型的参数类型
1.已知道类型的Type:Type contextType = typeof(ModelEntities);如果是某instance的type是
obj.GetType()
2. 创建某类型的Instance:object context = Activator.CreateInstance(contextType);
3. 获得某Instance的某属性的值:
object dbSetInstance = contextType.GetProperty(propName).GetValue(context);
4. 获得某Instance的某属性的类型:
Type dbSetType = contextType.GetProperty(propName).PropertyType;
5.获得某类型的某方法:MethodInfo objAddMethod = dbSetType.GetMethod("Add");
6.Call某方法: objAddMethod.Invoke(dbSetInstance, new object[]{obj});
(eg2)7.获得泛型的参数类型
if (propType.IsGenericType)
{
Type[] paraList = propType.GetGenericArguments();
propertyName = paraList[0].Name;
}
8.设置某属性的值:t.GetProperty(name).SetValue(obj, "abd")
Type contextType = typeof(ModelEntities);
object context = Activator.CreateInstance(contextType);
Type objType = obj.GetType();
var propNames = from p in contextType.GetProperties() select p.Name;
foreach (var propName in propNames)
{
if (objType.ToString() == contextType.Namespace+"."+propName)
{
object dbSetInstance =
contextType.GetProperty(propName).GetValue(context);
Type dbSetType =
contextType.GetProperty(propName).PropertyType;
MethodInfo objAddMethod =
dbSetType.GetMethod("Add");
objAddMethod.Invoke(dbSetInstance, new object[] { obj });
MethodInfo objSaveMethod =
contextType.GetMethod("SaveChanges");
objSaveMethod.Invoke(context, null);
}
}
再训练一个:
code如下:
再训练一个:
public partial class stocks_EF
{
public int ID { get; set; }
public string Symbol { get; set; }
public Nullable<double> Price { get; set; }
public Nullable<double> PricePct { get; set; }
public Nullable<int> Volume { get; set; }
public Nullable<int> AvgVolume { get; set; }
public string MktCap { get; set; }
public Nullable<double> Yield { get; set; }
public Nullable<double> PE { get; set; }
public Nullable<System.DateTime> TradeDate { get; set; }
public Nullable<System.DateTime> InsertTime { get; set; }
}
code如下:
public static void Fill(string[] words, object obj)
{
Type t = obj.GetType();
var propNames = from p in t.GetProperties() select p.Name;
int i=0;
foreach (var name in propNames)
{
Type propType = t.GetProperty(name).PropertyType;
string propertyName = propType.Name;
if (propType.IsGenericType)
{
Type[] paraList = propType.GetGenericArguments();
propertyName = paraList[0].Name;
}
if (propertyName == "DateTime")
t.GetProperty(name).SetValue(obj, Convert.ToDateTime(words[i]));
else if (propertyName == "Int32")
t.GetProperty(name).SetValue(obj, Convert.ToInt32(words[i]));
else if (propertyName == "Double")
t.GetProperty(name).SetValue(obj, Convert.ToDouble(words[i]));
else t.GetProperty(name).SetValue(obj, words[i]);
i++;
}
}
main函数:
string[] words = { "1", "CAT", "98.43", "2.5", "29389", "39392", "56.5B", "2.2", "10.2", "2013-06-17
00:00:00.000", "2014-04-23 00:00:00.000" };
stocks_EF s = new stocks_EF();
Fill(words, s);
Monday, April 21, 2014
C#之Entity framework
Entity Framework用于简历数据库与逻辑对象的映射
假设我们有表:
Visual studio 2012的设置:
连接数据库:
add sql server connection
选择数据库:
到这里,我们已经把数据库内置到了visual studio 2012中了。
下面我们加入entity framework:
加入.edm,这个可以数据库命名
选择Generate from database,然后选择要创建model的database表:
完成后,我们看到生成的代码结构如下:
双击ModelDB.edmx,会看到一个图形化表,如果以txt打开它,会看到它的内在代码:分为三部分:StorageModels (db table), ConceptualModels (C# class),Mappings。
运行如下C#代码:
会得到如下错误:
Unable to update the EntitySet 'stocks_EF' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
如果表有primary key,不用手动修改edmx文件,否则就要做改动:
这是因为该表没有primary key,有两个解决方案:
1. 写SP
2. 手动改.edmx的代码:
去掉store:Schema中的store,还去掉definingQuery部分即可
<DefiningQuery>SELECT
[stocks_EF].[ID] AS [ID],
[stocks_EF].[Symbol] AS [Symbol],
[stocks_EF].[Price] AS [Price],
[stocks_EF].[PricePct] AS [PricePct],
[stocks_EF].[Volume] AS [Volume],
[stocks_EF].[AvgVolume] AS [AvgVolume],
[stocks_EF].[MktCap] AS [MktCap],
[stocks_EF].[Yield] AS [Yield],
[stocks_EF].[PE] AS [PE],
[stocks_EF].[TradeDate] AS [TradeDate],
[stocks_EF].[InsertTime] AS [InsertTime]
FROM [dbo].[stocks_EF] AS [stocks_EF]</DefiningQuery>
运行代码后,发现insertTime没有输入,显然是DEFAULT contraint没有设置好:
只要加入黄色部分代码StoreGeneratedPattern即可.。
Refer to http://blogs.msdn.com/b/alexj/archive/2009/09/01/tip-34-how-to-work-with-updatable-views.aspx
假设我们有表:
CREATE TABLE [dbo].[stocks_EF](
[ID] int identity(1,1),
[Symbol] [varchar](10) NOT NULL,
[Price] [float] NULL,
[PricePct] [float] NULL,
[Volume] [int] NULL,
[AvgVolume] [int] NULL,
[MktCap] [varchar](20) NULL,
[Yield] [float] NULL,
[PE] [float] NULL,
[TradeDate] [datetime]
NULL,
[InsertTime] [datetime]
default(getdate())
)
Visual studio 2012的设置:
连接数据库:
add sql server connection
选择数据库:
到这里,我们已经把数据库内置到了visual studio 2012中了。
下面我们加入entity framework:
加入.edm,这个可以数据库命名
选择Generate from database,然后选择要创建model的database表:
完成后,我们看到生成的代码结构如下:
双击ModelDB.edmx,会看到一个图形化表,如果以txt打开它,会看到它的内在代码:分为三部分:StorageModels (db table), ConceptualModels (C# class),Mappings。
运行如下C#代码:
static void Main(string[] args)
{
using (ModelEntities context
= new ModelEntities())
{
context.stocks_EF.Add(new stocks_EF() { Symbol = "CAT", Price = 98.42, PricePct = 2.5, Volume = 29389, AvgVolume = 39392, MktCap = "56.5B", Yield = 2.2, PE = 10.2, TradeDate = Convert.ToDateTime("2013-06-17 00:00:00.000") });
context.SaveChanges();
}
}
Unable to update the EntitySet 'stocks_EF' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
如果表有primary key,不用手动修改edmx文件,否则就要做改动:
这是因为该表没有primary key,有两个解决方案:
1. 写SP
2. 手动改.edmx的代码:
去掉store:Schema中的store,还去掉definingQuery部分即可
<edmx:StorageModels>
<Schema Namespace="modelModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityContainer Name="modelModelStoreContainer">
<EntitySet Name="stocks_EF" EntityType="modelModel.Store.stocks_EF" store:Type="Tables" store:Schema="dbo" store:Name="stocks_EF">
</EntitySet>
</EntityContainer>
<!--Errors
Found During Generation:
warning 6002: The table/view
'model.dbo.stocks_EF' does not have a primary key defined. The key has been
inferred and the definition was created as a read-only table/view.
-->
<EntityType Name="stocks_EF">
<Key>
<PropertyRef Name="ID" />
<PropertyRef Name="Symbol" />
</Key>
<Property Name="ID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="Symbol" Type="varchar" Nullable="false" MaxLength="10" />
<Property Name="Price" Type="float" />
<Property Name="PricePct" Type="float" />
<Property Name="Volume" Type="int" />
<Property Name="AvgVolume" Type="int" />
<Property Name="MktCap" Type="varchar" MaxLength="20" />
<Property Name="Yield" Type="float" />
<Property Name="PE" Type="float" />
<Property Name="TradeDate" Type="datetime" />
<Property Name="InsertTime" Type="datetime" StoreGeneratedPattern="Computed"/>
</EntityType>
</Schema>
</edmx:StorageModels>
运行代码后,发现insertTime没有输入,显然是DEFAULT contraint没有设置好:
只要加入黄色部分代码StoreGeneratedPattern即可.。
Refer to http://blogs.msdn.com/b/alexj/archive/2009/09/01/tip-34-how-to-work-with-updatable-views.aspx
Subscribe to:
Posts (Atom)