failed: Rhino.Mocks.Exceptions.ExpectationViolationException : IBandwidthDataService.GetDataForCustom(100, 2010/1/11 14:35:31, 2010/2/11 14:35:31, 1.00:00:00); Expected #0, Actual #1.
模拟的方法加上.IgnoreArguments()
failed: Rhino.Mocks.Exceptions.ExpectationViolationException : IBandwidthDataService.GetDataForCustom(100, 2010/1/11 14:35:31, 2010/2/11 14:35:31, 1.00:00:00); Expected #0, Actual #1.
模拟的方法加上.IgnoreArguments()
写一个sorter
public class CourseSorter:IComparer
{
#region IComparer Members
public int Compare(CourseDto x, CourseDto y)
{
return x.Title.CompareTo(y.Title);
}
#endregion
}
用的时候list.sort(new Sorter());
即可
public IList<ShopDownloadAmountEntity> GetDayByShopBetween(int shopID, DateTime startTime, DateTime endTime)
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT sum(sizeamount) as SizeAmount,[ShopID],");
sb.Append("dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime) as DownloadTime ");
sb.Append("FROM ShopDownloadAmount ");
sb.Append("WHERE downloadtime between ‘" + startTime + "’ and ‘" + endTime + "’");
sb.Append(" GROUP BY shopid, dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime) ");
sb.Append(" order by dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime)");//sql string
ISQLQuery sql = NHibernateSession.CreateSQLQuery(sb.ToString());
sql.AddScalar("SizeAmount", NHibernateUtil.Int32);//set type of data
sql.AddScalar("ShopID", NHibernateUtil.Int32);
sql.AddScalar("DownloadTime", NHibernateUtil.DateTime);
sql.SetResultTransformer(Transformers.AliasToBean(typeof(ShopDownloadAmountEntity)));//make the result set to entity
return sql.List<ShopDownloadAmountEntity>();
}
ShopDownloadAmountEntity???????à??SizeAmount??ShopID??DownloadTime??setter
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
criteria.CreateAlias("Enduser", "enduser");
criteria.Add(Expression.Eq("enduser.EnduserID",enduserID));
criteria.Add(Expression.Between("DownloadTime", day, day.AddDays(1)));
criteria.SetProjection(Projections.Sum("FileSize"));
return (int)criteria.UniqueResult();
c#(或vb.net)程序改进
1、使用值类型的ToString方法
在连接字符串时,经常使用"+"号直接将数字添加到字符串中。这种方法虽然简单,也可以得到正确结果,但是由于涉及到不同的数据类型,数字需要通过装 箱操作转化为引用类型才可以添加到字符串中。但是装箱操作对性能影响较大,因为在进行这类处理时,将在托管堆中分配一个新的对象,原有的值复制到新创建的 对象中。
使用值类型的ToString方法可以避免装箱操作,从而提高应用程序性能。
int num=1;
string str="go"+num.ToString();
2、运用StringBuilder类
String类对象是不可改变的,对于String对象的重新赋值在本质上是重新创建了一个String对象并将新值赋予该对象,其方法ToString对性能的提高并非很显著。
在处理字符串时,最好使用StringBuilder类,其.NET 命名空间是System.Text。该类并非创建新的对象,而是通过Append,Remove,Insert等方法直接对字符串进行操作,通过ToString方法返回操作结果。
其定义及操作语句如下所示:
int num;
System.Text.StringBuilder str = new System.Text.StringBuilder(); //创建字符串
str.Append(num.ToString()); //添加数值num
Response.Write(str.ToString); //显示操作结果
3、使用 HttpServerUtility.Transfer 方法在同一应用程序的页面间重定向
采用 Server.Transfer 语法,在页面中使用该方法可避免不必要的客户端重定向(Response.Redirect)。
4、避免使用ArrayList。
因为任何对象添加到ArrayList都要封箱为System.Object类型,从ArrayList取出数据时,要拆箱回实际的类型。建议使用自定义 的集合类型代替ArrayList。asp.net 2.0提供了一个新的类型,叫泛型,这是一个强类型,使用泛型集合就可以避免了封箱和拆箱的发生,提高了性能。
5、使用HashTale代替其他字典集合类型
(如StringDictionary,NameValueCollection,HybridCollection),存放少量数据的时候可以使用HashTable.
6、为字符串容器声明常量,不要直接把字符封装在双引号" "里面。
//避免
MyObject obj = new MyObject();
obj.Status = "ACTIVE";
//推荐
const string C_STATUS = "ACTIVE";
MyObject obj = new MyObject();
obj.Status = C_STATUS;
7、不要用ToUpper(),ToLower()转换字符串进行比较,用String.Compare代替,它可以忽略大小写进行比较.
例:
const string C_VALUE = "COMPARE";
if (String.Compare(sVariable, C_VALUE, true) == 0)
{
Console.Write( "相同");
}
也可以用str == String.Empty或者str.Length == 0判断是否为空。(注意判断输入数据的长度,可防止sql注入式攻击)
将String对象的Length属性与0比较是最快的方法,避免不必要的调用 ToUpper 或 ToLower 方法。
8、类型转化Int32.TryParse()优于Int32.Parse()优于Convert.ToInt32()。
建议.NET1.1下用Int32.Parse();.NET2.0用Int32.TryParse()。
因为:
Convert.ToInt32 会把最终的解析工作代理给 Int32.Parse;
Int32.Parse 会把最终的解析工作代理给Number.ParseInt32;
Int32.TryParse 会把最终的解析工作代理给Number.TryParseInt32。
9、如果只是从XML对象读取数据,用只读的XPathDocument代替XMLDocument,可以提高性能
//避免
XmlDocument xmld = new XmlDocument();
xmld.LoadXml(sXML);
txtName.Text = xmld.SelectSingleNode( "/packet/child").InnerText;
//推荐
XPathDocument xmldContext = new XPathDocument(new StringReader(oContext.Value));
XPathNavigator xnav = xmldContext.CreateNavigator();
XPathNodeIterator xpNodeIter = xnav.Select( "packet/child");
iCount = xpNodeIter.Count;
xpNodeIter = xnav.SelectDescendants(XPathNodeType.Element, false);
while(xpNodeIter.MoveNext())
{
sCurrValues += xpNodeIter.Current.Value+ ",";
}
10、避免在循环体里声明变量,应该在循环体外声明变量,在循环体里初始化。
C#程序开发要遵循的一个基本原则就是避免不必要的对象创建
//避免
for(int i=0; i <10; i++)
{
SomeClass objSC = new SomeClass();
}
//推荐
SomeClass objSC = null;
for(int i=0; i <10; i++)
{
objSC = new SomeClass();
}
11、捕获指定的异常,不要使用通用的System.Exception.
//避免
try
{
<some logic>
}
catch(Exception exc)
{
<Error handling>
}
//推荐
try
{
<some logic>
}
catch(System.NullReferenceException exc)
{
<Error handling>
}
catch(System.ArgumentOutOfRangeException exc)
{
<Error handling>
}
catch(System.InvalidCastException exc)
{
<Error handling>
}
12、使用Try…catch…finally时, 要在finally里释放占用的资源如连接,文件流等
不然在Catch到错误后占用的资源不能释放。
try
{}
catch
{}
finally
{
conntion.close();
}
13、不要用Exception控制程序流程
有些程序员可能会使用异常来实现一些流程控制。例如:
try{
result=100/num;
}
Catch(Exception e)
{
result=0;
}
但实际上,Exception是非常消耗系统性能的。除非必要,不应当使用异常控制来实现程序流程。上面的代码应当写为:
if(num!=0)
result=100/num;
else
result=0;
14、避免使用递归调用和嵌套循环,使用他们会严重影响性能,在不得不用的时候才使用。
15、禁用VB.net和Jscript动态数据类型
应当始终显示地申明变量数据类型,这能够节约程序的执行时间。以往,开发人员喜欢使用 Visual Basic、VBScript 和 JScript 的原因之一就是它们所谓“无类型”的性质。变量不需要显式类型声明,并能够简单地通过使用来创建它们。当从一个类型到另一个类型进行分配时,转换将自动执 行。不过,这种便利会大大损害应用程序的性能。
如:
为了获得最佳的性能,当声明 JScript .NET 变量时,请为其分配一个类型。例如,var A : String;
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Entity.CustomerEntity, Entity" table="Customer" lazy="false" >
<id name="CustomerID" column="CustomerID" type="Int32">
<generator class="identity" />
</id>
<property name="CustomerName" column="CustomerName" type="String" length="10" />
<bag name="Files" table="File" cascade="all">
<key column="FileID" foreign-key="FileID"></key>
<one-to-many class="Entity.FileEntity, Entity"/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Entity.FileEntity, Entity" table="File1" lazy="false">
<id name="FileID" column="FileID" type="Int32">
<generator class="identity" />
</id>
<property name="FileSize" column="FileSize" type="Int32" length="4" />
<property name="CustomerID" column="CustomerID" type="Int32" length="4" />
<many-to-one name="Customer" column="CustomerID" class="Entity.CustomerEntity, Entity" insert="false"/>
<bag name="DownloadLogs" table="DownloadLog" cascade="all">
<key column="FileID"/>
<one-to-many class="Entity.DownloadLogEntity, Entity" />
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Entity.DownloadLogEntity, Entity" table="DownloadLog" lazy="false" >
<id name="DownloadLogID" column="DownloadLogID" type="Int32">
<generator class="identity" />
</id>
<property name="FileID" column="FileID" type="Int32" length="4" />
<property name="Times" column="Times" type="Int32" length="4" />
<many-to-one name="File" column="FileID" class="Entity.FileEntity, Entity" insert="false"/>
</class>
</hibernate-mapping>
从配置文件上可以看出
每个customer对应多个file,每个file对应多个downloadlog
如果使用icriteria查询customer对应的downloadlog
可以这样写:
public IList<DownloadLogEntity> GetByCustomerID(int customerID)
{
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
criteria.CreateAlias("File", "file");
criteria.CreateAlias("file.Customer", "customer");
criteria.Add(Expression.Eq("customer.CustomerID",customerID));
return criteria.List<DownloadLogEntity>();
}
Error:The type ‘IManagers.IDataManager’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘IManagers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’.
添加引用即可
Page Method 方式
如果不想独立创建Web Service,而只是希望能够调用页面上的一些方法,那么可以采用Page Method的的方法。同样的我们添加一个页面PageMethodDemo.aspx,增加一些JavaScript和一个后台方法,注意这个方法必须 是静态方法,代码如下:
<script type="text/javascript">
function PageMethodCall()
{
var testString = "PageMethodCall";
PageMethods.Test($get('txtName').value, OnSucceeded);
}
// 页面方法调用完成的回调函数.
function OnSucceeded(result)
{
// 显示调用结果
var RsltElem = document.getElementById("Results");
RsltElem.innerHTML = result;
}
</script>
<form id="form1">
<h2>Page Method</h2>
<input id="txtName" type="text" />
<button id="Button1">调用Page Method</button>
</form>
代码页PageMethodDemo.aspx.cs
[System.Web.Services.WebMethod]
public static string Test(string name)
{
return "Hello " + name + "!";
}
映射文件hbm.xml里要
<sql-query name="Filter_CheckAssignTime">
<return class="FilterService.Entities.Filter_Course_MediaEntity, FilterService.Entities">
</return>
exec Filter_CheckAssignTime
</sql-query>
dao里调用
NHibernateSession.GetNamedQuery("Filter_CheckAssignTime").List();
alert(‘<asp:Localize ID="EmailFomatInvalid" runat="server" meta:resourcekey="EmailFomatInvalid" />’, ‘lbl_email’);
在资源文件中定义各种语言的文本内容即可