显示标签为“c#”的博文。显示所有博文
显示标签为“c#”的博文。显示所有博文

2009年3月17日星期二

March 17th:C#,Debug,HTML

C#
    This post touches on four major expression subjects:
    1) String Comparison - does a string contain a particular sub-string?
    a. finding valid HTML tags- RegEx.Matches return MactchCollection
    valid html tags: Regex HTMLTag = new Regex(@"(<\/?[^>]+>)");
    2) Splitting a string into segments(分割,部分)- we will take an IPv4 address and retrieve its dotted components
    a. splitting decimal Tcp/IP address looks like xxx.xxx.xxx.xxx with x being a decimal number
    Regex tcpIp = new Regex(@"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})");
    3) String Replacement
    4) Substitution Patterns
    5) Stricter input validation- how to harden your expressions
    1) The ? conditional evaluation operator
    example:int max = (x > y) ? x : y;
    2) Null-Coalesce(合并,联合) operator(??)
    example:obejct e = ( c != null ) ? c : d; => object e = c ?? d;
    3) Object Initializers
    Customer c = new Customer{ Name="James",Address="204 Lime Street"};(c# 3.0)
    4) The using statement
    5) Aliases(别名) for long winded namespaces and types
    example: using Word = Microsoft.Office.Interop.Word;
                     Word.Application = new Word.Application(){ Visible = true};
    6) Nullable objects
    example: Nullable x = null;
     int? x =  null;
    7) Automatic Properties(c# 3.0)
    8) Type inference(c#3.0 var)
    note: There is no performance impact results form using type inference.The compiler does all the work figuring out the data type at compile time.
    9) Lambda Expressions
    10) string.IsNullOrEmpty
    Optional and named parameters in C# 4.0
    Example:app.Document.open(ref filename,ref missing.......);
    app.Documents.open(@"c:\Document.docx",Readonly:true);
    1) what is an anonymous type?
      One important motivation(动机)for this was to make code written with LINQ easier to read.Anonymous types simply mean that you don't specify the type- but let the complier do it instead.
    2) what is the beneficial for Anonymous type?
    a. simple definitions,simplified
    b. using anonymous types for creating arrays
    c. Saving time and code with anonymous types
    d. Combining Lambda expressions with Queries
    3) other questions?
    a. Is var typesafe? yes
    b. Is there a performance penalty(处罚,征罚) for using "var"? no
    c. On using anonymous definitions in large projects

Debugger
    1) Install the Visual Studio 2008 QFE( Quick-Fix-Engineering)
    2) Start Visual Studio 2008 and bring up Tools > Options > Debugging > General
      Turn OFF the "Enable Just My Code" setting
      Turn ON the "Enable Source Server Support" setting
    3) Next,bring up the "Symbols" page and set the symbols download URL and a cache location.
      Set the symbol file location to be:http://referencesource.microsoft.com/symbols

Sliverlight

Other

2009年3月10日星期二

March 10th-13th Links:C#,Struct,Word,Javascript

C#
    1. What The Defference Between Const and Readonly in .NET?
    1) The readonly keywork differs from the const keyword.A const field can only be initialized at the declaration of the field.A readonly field can be initialized either at the declaration or in a constructor.
    2) A const field is a compile-time constant,the readonly field can be used for run-time constants,as in this line: public static readonly unit l = (uint)DateTime.Now.Ticks;
    3) When using const,the value has to be set before compiling,and can not be changed. Once u make your assembly,the value of the const is baked in there.if u want to change the value of the const,u must go back into your code,change the value,then recompile.if another assemly(Assembly B) wants to use the const in the first assembly(Assembly A),the const is also baked in there as well.So,if u change the value of the const,not only will you have to rebuild your first Assembly A,you will also have to build all other assembly(e.g.:assembly B,C,D...).
    4) Another difference between const and readonly,is that const are static by default,where with readonly,you must define it as static(if you wnat it to be).
    c# 2.0(which shipped with VS2005) introduced the concept of anonymous methods,which allow code blocks to be wrritten "in-line" where delegate values are expected.
    Lambda Expressions provide a more concise(简明的),functional syntax for writing anonymous methods.Since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.
    syntax: params => expression
    One of the things that make Lambda expressions particularly(adv尤其) powerful from a framework developer's perspective(看法) is that they can be compiled as either a code delegate(int the form of IL based method) or as a expression tree object which can be used at runtime to analyze,transform or optimize the expression.
    1) Lambda Expressions to Code Delegates
    2) Lambda Expressions to Expression Trees

Design Patterns
    If u want to do something that requires interacting with multiple subsystems you can create a facade that same only a few methods that handle all the interaction with the subsystem.

JAVASCRIPT

Silverlight
    I have been wording extensively with both WPF and Silverlight over the past many months.Not too long ago,my workstation started having trouble - specifically Visual Studio 2008 was crashing when tring to open XAML files.Not just crashing either.maybe u should need this patch:  download this patch

English
    1. Unethical
    2. Survey: 调查,民意调查
    3. reusable: 重复使用
    4. fetch: 取得
    5. paragraphs:段
    6. Enumerable: IEnumerable
    7. concise
    8. syntax
    9. subsequent: 后续的
    10. evaluation: 付值,评估,评价
    11. perspective: 看法,透视

2009年3月1日星期日

March 1th Links:ASP.NET MVC,

ASP.NET MVC

C#  
    1) The Action delegate
     encapsulate a method which dosen't reutn a value,and which holds a variable number of parameters.
     a. public delegate void Action()- if the method is parameterless,use it.
     b. public delegate void Action(T arg1).
     c. public delegate void Action(T1 arg1,T2 arg2).
     d. public delegate void Action(T1 arg1,T2 arg2,T3 arg3).
     e. public delegate void Action(T1 arg1,T2 arg2,T3 arg3,T4 arg4).
    e.g: Foreach
    2) The Comparison delegate
    sorting elements within a collection
    e.g: Sort
    3) The Converter
    convert an object from on type to another type
    e.g: List toysNames = toys.ConvertAll(toy => toy.Name);
    4) The Predicate delegate
    defines a set of criteria and determines whether the specified object meets those criteria.
    e.g: Exists,Find,FindAll,FindIndex,etc..
    4. Infinite Lists With C# Yield- Justin Etheredge

CodePlex

JAVASCRIPT
    1. Time to grok Closures- Sergio Pereira
    This happens when the returned(or inner) function has a reference to anything defined in the parent(or outer) function,i.e.(换言之),the parent local scope.When this happens,we way that a closure has been created.

SQL SERVER
    1) Unidirectional(单向的) synchronization
    2) Bidirectional(双向的) synchronization

English
    1. Comfortable: 舒适的
    2. encapsulate: 装入内部,封装(encapsulate method)
    3. intention: 意图
    4. Infinite: 无限的,无穷的,极大的
    5. Closure: 闭合

2009年2月25日星期三

February 26th-27th Links:SQL SERVER,ASP.NET PERFORMANCE

C#
    1. Creating SOLID Code: Sigle Responsibility Principle- Episode-Codebetter.com 

ASP.NET

IIS

SQL SERVER
    The query statement is related Table : sys.foreign_keys,sys.foreign_key_columns,sys.objects
    Third Normal Form(3NF) is most preferable normal form in RDBMS.Nomalization is the process of designing a data model to efficiently store data in database.The rules of 3NF are mentioned here:
    1) Make a sperate table for each set of related attributes, and give each table a privary key.
    2) If an attribute deponds on only part of a muil-valued key. remove it to a separate table.
    3) If an attribute don't contribute(有助) to a description of the key, remove it to a separate table.
    Normalization is very close to concept of Object Oriented schema's and it stores one data at only one place by removing all the redundant(多余的) data. Normalization comes at cost of performance.
    PS: 1NF: 数据库表中的字段都是单一属性,不可再分.
           attribute1   attribute2  attribute3(attribute3.1,attribute3.2...)
           2NF: 数据库表中不存在非键字段对任一候选关键字段的部分函数依赖.
           (studentId, courseName)->(studentName,age,grade,credits(学分))
           but
           (courseName)->(credits)
           (studentId)->(studentName,age)
           3NF: 数据表中不存在非关键字段对任一候选关键字段的传递函数依赖。
          (studentId)->(name,age,college,colleagePhone,colleageLocation)
   but
          (studentId)->(colleage)->(colleagePhone,colleageLocation)

2009年2月24日星期二

February 24th Links:ASP.NET,SEO,C#

ASP.NET

C#

NUint
 
LINQ-XML

SQL SERVER

WEB
    the short answer is ALWAYS! But let's rewind(绕回) a bit and provide some context...............In Summary,the compatibility(兼容) UA-X meta tag is the perfect way to ensure that your customers will enjoy your pages the way they were intended
e.g. meta equiv="x-UA-Compatible" content="IE-EmulateIE7"

CodePlex
    1. Fluent DateTime
    A set of(Ruby inspired灵感) C# Extension Methods for easier and more natural DateTime handing and operations in .NET.

English
    1. Global Summit:全球峰会
    2. Seattle and Redmond
    3. Canonical : 标准的,权威的
    4. Inspired:灵感的
    5. Campaign:战役,活动,运动

2009年2月17日星期二

February 18th Links: ASP.NET,JQuery

ASP.NET
1. Download the files by using Asp.net
JQuery
--Bill Beckelman
    note: this post include some good url regExp

REST,C#

WCF

2008年10月10日星期五

XmlDocument与xelement性能(XMLDOCUMENT VS XELEMENT PERFORMANCE)

我已经使用XElement有一段时间了,下面我做了一些性能的测试,并指出在xmlDocuemnt和xelement之间的不同。
首先,XElement是.NET Framework3.5的一部分,它被使用在xml to linq,并且位于System.xml.linq命名空间下。这个class在linq方面得到了很好的使用。xElement.Nodes和xElement.Attribues返回了一个IEnumerable,这个接口很容易的被使用于nodes的访问。当然你也可以使用Lambda expressions操作它们。更多的信息请参考http//msdn.microsoft.com/en-us/library/bb487098.aspx
在下面的例子中,我创建了两个static方法,一个使用xmlDocument,一个使用xElement去生成一个XML,通过循环system assembly exported type构建一个巨大的xml ,并将其保存到Stream中去,下面是两段代码:
   1://Generates XML using XmlDocument
   2: internal static void GenerateXmlUsingXmlDocument() 
   3: {
   4:     MemoryStream ms =new MemoryStream();
   5:     XmlDocument xmlDoc = new XmlDocument();
   6:     xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no"));
   7:     XmlElement assembliesNode = xmlDoc.CreateElement("Assemblies");
   8:     foreach (Type t in Assembly.GetAssembly(typeof(Object)).GetExportedTypes())
   9:     {
  10:         XmlElement assemblyNode = xmlDoc.CreateElement("Assembly");
  11:         XmlAttribute fullTypeName = xmlDoc.CreateAttribute("FullTypeName");
  12:         fullTypeName.Value = t.ToString();
  13:         XmlAttribute isInterfaceName = xmlDoc.CreateAttribute("IsInterface");
  14:         isInterfaceName.Value = t.IsInterface.ToString();
  15:         assemblyNode.Attributes.Append(fullTypeName);
  16:         assemblyNode.Attributes.Append(isInterfaceName);
  17:         assembliesNode.AppendChild(assemblyNode);
  18:     }
  19:     xmlDoc.AppendChild(assembliesNode);
  20:     xmlDoc.WriteContentTo(new XmlTextWriter(ms,System.Text.ASCIIEncoding.ASCII));
  21: }
  22:  
  23: //Generates XML using XElement
  24: internal static void GenerateXmlUsingXElement()
  25: {
  26:     MemoryStream ms = new MemoryStream();
  27:     XElement assembliesNode = new XElement("Assemblies",
  28:             from Type t in Assembly.GetAssembly(typeof(Object)).GetExportedTypes()
  29:             select new XElement("Assembly",
  30:                 new XAttribute("FullTypeName", t.ToString()),
  31:                 new XAttribute("IsInterface", t.IsInterface.ToString())));
  32:     
  33:     assembliesNode.Save(new XmlTextWriter(ms, System.Text.ASCIIEncoding.ASCII));
  34: }
你可以发现上面两个方法中的不同了吧,xElement使用 LINQ expressions生成xml,它代码简单明了。通过下面的代码,我重复的测试在每个方法中执行时间
1: Stopwatch sw = new Stopwatch();
   2: for (int index = 0; index <>
   3: {
   4:     sw.Reset(); sw.Start();
   5:     Program.GenerateXmlUsingXmlDocument();
   6:     sw.Stop();
   7:     Console.Write("Generation time using XmlDocument " +
   8:         "and XElement: " + sw.ElapsedMilliseconds);
   9:     sw.Reset(); sw.Start();
  10:     Program.GenerateXmlUsingXElement();
  11:     sw.Stop();
  12:     Console.WriteLine(" : " + sw.ElapsedMilliseconds);
  13:     //Forcing the Garbage Collector to run to make sure,
  14:     //We dispose of all the types we created on the
  15:     //Managed heap.
  16:     GC.Collect();
  17: }
  18: Console.ReadKey();间
从上面的代码中,你可以发现我循环50次去测试每一个方法,另外,在每个测试后,我都显视的调用了GC回收器去清理通过两个方法创建的对象。下面我显示测试的结果:
XmlDocumentXElement
在上面,你可以清楚的发现,在两个方法中create xml的不同。它们之间的执行时间相差了6到10倍。在ASP.NET applications 和Web Services 中以每毫秒计算犹为重要。还有一件事情提醒一下,xElement是 .NET 3.5中Ssytem.xml.linq.dll的一部分,但是它仍桀犬吠尧是以.NET 2.0 CLR运行的,因此,如果你还没有使用.NET 3.5,你可以 copy System.Xml.Linq.dll在你的应用程序下。但是,你会错过许用来自于.NET team的好的更新。
英文地址(引用):XMLDOCUMENT VS CELEMENT PERFORMANCE



异常的性能及抛出(Exception Throwing)

1. 抛出异常(Exception Throwing)
抛出异常在这篇文章里被定义为是对执行失败时给出的定义。执行失败在任何时候都引出了一个被设计好的程序不去做它应该做的事情。例如,如果打开一个文件的方法不能返回一个打开文件的操作给调用者,则它应该被设计成一个执行失败。
许多开发者可能已经很自然的去使用exceptions处理例如像除以0,以及为对象为null引用的过程。在framework中,expceptions被使用在复杂错误和逻辑错误中。首先,它很难去报告所有功能失败的手段,但是它被设计成对framework中所有公共方法通过抛出一个异常去报告方法的失败。
其实有各种各样的方法可以不使用异常处理,但大多数规结了两种,一种是返回一个错误的代码或者错误的模块不去执行并且返回一个错误的代码。性能的考虑在下面一节中讨论。作为一个API的设计者,我们不应该去猜测使用我们代码的开发者对我们的程序很熟悉,下面是异常的一些使用方法与规则:
1)不要返回一个错误代码。exceptions是在框架中报告错误的主要方法。
2)通过抛出异常报告执行失败。
3)  考虑终止进程。当你的程序遇到下一步执行不安全的时候,通过调用System.Environment.FailFast(.NET Framework 2.0 feature)代替抛出异常。
4) 不要在正常的控制流程中使用异常。除了系统错误,一般写代码的时候避免抛出异常。例如,在调用一个成员之前,你可以提供一个方式去检查。
ICollection collection = ...
if( !collection.IsReadOnly ){
collection.Add(additionalNumber);
}
被设计成执行其它成员的先决条件的成员被称为tester,实际工作的成员被称为doer.(在下性能的章节中有更多关于Tester-Doer Pattern的信息)。
5.  考虑性能的影响(在下面介绍)
6.  不用使用一公共的成员,它们为一个返回的值或out parameter返回异常。
7.  考虑使用异常bulder methods.它是在不同地方抛出一样异常的方法去避免代码的冗余。
class File{
string fileName;
public byte[] Read(int bytest){
if( !ReadFile(handle,bytes)){
throw NewFileIOException(...);
}
}
FileExceiption NewFileExction(...){
string description = //build localized string
return new FileExceipton(desciption);
}
}
1.2 异常和性能
在异常发生时候时候,它的性能会变慢。但是它也有可能获得好的性能当中止执行错误代码的时候。在下面我就介绍一下这两个情况:
1) 不要使用错误代码,因为异常引起了性能过慢
Tester-Doer模式
有时候,抛出异常的性能的成员能通过将其自身折成两个来提高性能,让我们来看看下面的例子:
Dictionary table = new Dictionary();
...
int value = table["key"];
如果the key不存在,则这个索引器将引出一个异常而引起一些性能问题。我们将其改成
Dictionary talbe = new Dictionary();
...
if( table.Contains("key") ){
int value = table["key"];
}
table成员使用了测试条件,在我们的例子中是Contains方法,这个被称作为'tester',下面一个用于操作的方法的成员就叫做Doer。这就是Tester-Doer 模式。考虑使用Tester-Doer模式去避免与异常有关的性能问题。
TryParse模式
对于极高性能要求的API,则一个更快的模式应该被使用。例如,DateTime有一个方法Parse方法去将日期转换为string,还定义了别外一个TryParse方法也是做同样的事情,但是两者的区别在于,前者失败的话会抛出一个异常,而后者失败的情况下返回一个false.
本人观点:
上面的观点来自于krzysztof cwalina的ExceptionThrowing,可能大家看的有得迷糊,翻译得不是很理想。望大家见谅。就我的理解,文章中提到几个重要的地方那就是,如果要使用抛出异常,尽量使用系统自带的。如果在程序中,尽量在可能出现异常的地方使用Tester-doea和Tryxxx方法去控制异常,毕竟程序性能是第一.
英文地址(引用):Exception Throwing
  参考地址:The Cost of Exceptions