Friday, September 23, 2011

What’s New in .NET Framework 4.0(C# .Net 4.0 Nutshell)

Framework 4.0 adds the following new features:

• New core types: BigInteger (for arbitrarily large numbers), Complex (complex
numbers), and tuples (Chapter 6)
• A new SortedSet collection (Chapter 7)
• Code contracts, for enabling methods to interact more reliably through mutual
obligations and responsibilities (Chapter 13)
• Direct support for memory-mapped files (Chapter 14)
• Lazy file- and directory-I/O methods that return IEnumerable instead of
arrays (Chapter 14)
• The Dynamic Language Runtime (DLR), which is now part of the .NET
Framework (Chapter 19)
• Security transparency, which makes it easier to secure libraries in partially
trusted environments (Chapter 20)
• New threading constructs, including a more robust Monitor.Enter overload,
Thread.Yield, new signaling classes (Barrier and CountdownEvent), and lazy
initialization primitives (Chapter 21)
• Parallel programming APIs for leveraging multicore processors, including
Parallel LINQ (PLINQ), imperative data and task parallelism constructs,
concurrent collections, and low-latency synchronization and spinning primitives
(Chapter 22)
• Methods for application domain resource monitoring (Chapter 24)
Framework 4.0 also includes enhancements to ASP.NET, including the MVC
framework and Dynamic Data, and enhancements to Entity Framework, WPF,
WCF, and Workflow. In addition, it includes the new Managed Extensibility
Framework library, to assist with runtime composition, discovery, and dependency
injection.

Tuesday, September 13, 2011

Member Leak in Managed Component

From C# .Net 4.0 Netshell

--Event Handler
--Database Connection
--Timers


Managed Memory Leaks
In unmanaged languages such as C++, you must remember to manually deallocate
memory when an object is no longer required; otherwise, a memory leak will result.
In the managed world, this kind of error is impossible due to the CLR’s automatic
garbage collection system.
Nonetheless, large and complex .NET applications can exhibit a milder form of the
same syndrome with the same end result: the application consumes more and more
memory over its lifetime, until it eventually has to be restarted. The good news is
that managed memory leaks are usually easier to diagnose and prevent.
Managed memory leaks are caused by unused objects remaining alive by virtue of
unused or forgotten references. A common candidate is event handlers—these hold
a reference to the target object (unless the target is a static method). For instance, consider the following classes:

class Host
{
public event EventHandler Click;
}

class Client
{
Host _host;
public Client (Host host)
{
_host = host;
_host.Click += HostClicked;
}
void HostClicked (object sender, EventArgs e) { ... }
}
The following test class contains a method that instantiates 1,000 clients:
class Test
{
static Host _host = new Host();
public static void CreateClients()
{
Client[] clients = Enumerable.Range (0, 1000)
.Select (i => new Client (_host))
.ToArray();
// Do something with clients ...
}
}

You might expect that after CreateClients finishes executing, the 1,000 Client objects
will become eligible for collection. Unfortunately, each client has another referee:
the _host object whose Click event now references each Client instance. This
may go unnoticed if the Click event doesn’t fire—or if the HostClicked method
doesn’t do anything to attract attention.
One way to solve this is to make Client implement IDisposable, and in the
Dispose method, unhook the event handler:

public void Dispose() { _host.Click -= HostClicked; }

Consumers of Client then dispose of the instances when they’re done with them:

Array.ForEach (clients, c => c.Dispose());

--Timer

Timers (System.Timers)
Forgotten timers can also cause memory leaks (we discuss timers in Chapter 21).
There are two distinct scenarios, depending on the kind of timer. Let’s first look at
the timer in the System.Timers namespace. In the following example, the Foo class
(when instantiated) calls the tmr_Elapsed method once every second:
using System.Timers;
class Foo
{
Timer _timer;
Foo()
{
_timer = new System.Timers.Timer { Interval = 1000 };
_timer.Elapsed += tmr_Elapsed;
_timer.Start();
}


The timer in the System.Threading namespace, however, is special. The .NET Framework
doesn’t hold references to active threading timers; it instead references the
callback delegates directly. This means that if you forget to dispose of a threading
timer, a finalizer can (and will) fire—and this will automatically stop and dispose
the timer. This can create a different problem, however, which we can illustrate as
follows:
static void Main()
{
var tmr = new System.Threading.Timer (TimerTick, null, 1000, 1000);
GC.Collect();
System.Threading.Thread.Sleep (10000); // Wait 10 seconds
}
static void TimerTick (object notUsed) { Console.WriteLine ("tick"); }
If this example is compiled in “release” mode (debugging disabled and optimizations
enabled), the timer will be collected and finalized before it has a chance to fire even
once! Again, we can fix this by disposing of the timer when we’re done with it:

using (var tmr = new System.Threading.Timer (TimerTick, null, 1000, 1000))
{
GC.Collect();
System.Threading.Thread.Sleep (10000); // Wait 10 seconds
}


The implicit call to tmr.Dispose at the end of the using block ensures that the tmr
variable is “used” and so not considered dead by the GC until the end of the block.
Ironically, this call to Dispose actually keeps the object alive longer!


void tmr_Elapsed (object sender, ElapsedEventArgs e) { ... }
}
Unfortunately, instances of Foo can never be garbage-collected! The problem is
the .NET Framework itself holds references to active timers so that it can fire their
Elapsed events. Hence:
• The .NET Framework will keep _timer alive.
• _timer will keep the Foo instance alive, via the tmr_Elapsed event handler.
The solution is obvious when you realize that Timer implements IDisposable. Disposing
of the timer stops it and ensures that the .NET Framework no longer references
the object:
class Foo : IDisposable
{
...
public void Dispose() { _timer.Dispose(); }
}

Monday, September 12, 2011

Closure Example (C#)

1.

IEnumerable<char> query = "Not what you might expect";
    query = query
               .Where(c => c != 'a')
               .Where(c => c != 'e')
               .Where(c => c != 'i')
               .Where(c => c != 'o')
               .Where(c => c != 'u');

 

result

// Nt wht y mght xpct

2.

 

IEnumerable<char> query = "Not what you might expect";
foreach (char vowel in "aeiou")
                  query = query.Where (c => c != vowel);
foreach (char c in query) Console.Write (c);

 

Result :

// Not what yo might expect

(only u is skipped, because vowel is updated on foreach step, when later enumberate the query, all lambda expression reference same charter value which is “u” , and executed five same times).

 

3. Workout solution

IEnumerable<char> query = "Not what you might expect";
foreach (char vowel in "aeiou")
{               

char kk=vowel;

  query = query.Where (c => c != kk);
}

foreach (char c in query) Console.Write (c);

 

Result:

// Nt wht y mght xpct

Linq: Fluent Syntax VS Query Syntax

Fluent Syntax:

names.Where (n => n.Contains ("a")) // Privately scoped n
.OrderBy (n => n.Length) // Privately scoped n
.Select (n => n.ToUpper()) // Privately scoped n

Query Syntax :

from n in names // n is our range variable
where n.Contains ("a") // n = directly from the array
orderby n.Length // n = subsequent to being filtered
select n.ToUpper() // n = subsequent to being sorted

--Large personal choice

1. Fluent Syntax has more operators than that of Query Syntax
2. When using join , better with QuerySyntax

Sunday, September 11, 2011

Covariance In .Net(ZT)

Problem:
我们可能会遇到这样的事情,就是在一些使用了泛型的接口或者数组中,即使只有泛型参数的类型不同,这些类型也不能像普通类一样互相转换

Eg.

class Animal {}
class Bear : Animal {}
class Camel : Animal {}
...
Stack<Bear> bears = new Stack<Bear>();
Stack<Animal> animals = bears;    // Compile error
Bear b=new Animal(); // no compile error
.....

什么是 Covariance

Covariance 用于数组、泛型接口和泛型委托中,如果存在泛型接口 I<T> 的两个实例 I<A> 和 I<B>,而 A 和 B 之间有继承关系(A is base, B is superclass),且 A > B。如果允许 I<B> 隐式转换为 I<A>,则成 I<T> 支持 Covariance。

C#数组的协变(Array Covariance) s supported from .net Framework 1.0

Eg.

object[] array=new string[10];// no compile error

but it is not type safe

array[0]=1; // will get run-time error


From .Net 4
如果存在类 A 和 B,A 是 B 的基类(A > B),那么 I<T> 是一个泛型接口,T 约束为 A(where T : A),那么从类型 I<B> 可以转换为类型 I<A>。

对于委托,如果存在类 A 和 B,A 是 B 的基类(A > B),那么 D<T>() 是一个泛型委托,T 约束为 A(where T : A),那么从委托 D<B> 可以转换为委托 D<A>。

如何声明一个接口或者委托支持 Covariance

C# 4.0 现在提供一个新的约束性语法,在声明返型接口或委托时,可以在泛型参数前面加上 in 或者 out 来表示该接口或委托支持 Contra-variance 或 Covariance。这篇文章只涉及到 Covariance,因此我们需要一个 out 约束。

某一些 CLR 系统内置的类,如 IEnumerable<T>,已经被声明成了 IEnumerable<out T>。我们通过 Metadata 看到的 System.Collections.Generic.IEnumerable<T> 如下。

image

这就意味着 .NET Framework 4.0 中的 IEnumerable<T> 支持 Covariance。于是,下面的代码是可以工作的 。

image

我们也可以自己实现 Covariance。如下面的例子,类 A  和 类 B 具备继承关系,下面的转换都是合法的。因为 object > A > B,因此 B –> A,B –> object 以及 A –> object 均有效。

image
Covariance 的约束条件

按照惯例,不是所有具备泛型参数的接口和委托都可以用来支持 Covariance。如果类型 I<T> 或委托 D<T> 的类型参数 T 具备 out 约束,那么:

    T 是类、结构或者枚举类型。
    T 是非泛型接口或者委托类型。
    T 是元素类型支持 Variance 的数组。
    T 是一个没有被定义为 out 约束的类型参数类型。

另外,支持 Covariance (有 out 约束)的泛型接口或委托存在以下限制:

    他们不能包含一个具备类型参数表的事件(但自定义事件或者使用委托声明的事件除外)。
    他们不能包含内部类(Nested Class)、结构或枚举类型。

其他需要注意的地方

作为最佳实践,泛型接口的类型参数 T 一般为 out 约束(Covariance),泛型委托的类型参数如果是作为参数列表的,则一般为 in 约束(Contra-variance),而类型参数作为返回值的,一般为 out 约束(Covariance)。关于这一点请参照 IEnumerable<out T> 和 Func<in T, out TResult>。

Friday, September 09, 2011

Closure Example

Example 1:
static Func Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
static void Main()
{
Func natural = Natural();
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 1
}


Example 2:


static Func Natural()
{
return() => { int seed = 0; return seed++; };
}


static void Main()
{
Func natural = Natural();
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 0
}

Capturing is internally implemented by “hoisting” the captured
variables into fields of a private class. When the method is
called, the class is instantiated and lifetime-bound to the delegate
instance.

Thursday, September 08, 2011

实例化顺序C#(ZT)

From

Summary:
child static field>child static contructor>child instance filed>base static field>base static constructor>base instance field>base instance contructor>child instance constructor>child new methods>base virtual methods(if child methods is not aviable, if availab, it won't be executed,so a5 will not be executed at all).





  最近找工作,面试了几家公司,其中有一家公司的面试题给我印象很深,不久前在博客园看过类似的题目,但这次的更复杂,题目如下:

public class BaseA
{
public static MyTest a1 = new MyTest("a1");
public MyTest a2 = new MyTest("a2");
static BaseA()
{
MyTest a3 = new MyTest("a3");
}
public BaseA()
{
MyTest a4 = new MyTest("a4");
}
public virtual void MyFun()
{
MyTest a5 = new MyTest("a5");
}
}
public class BaseB : BaseA
{
public static MyTest b1 = new MyTest("b1");
public MyTest b2 = new MyTest("b2");
static BaseB()
{
MyTest b3 = new MyTest("b3");
}
public BaseB()
{
MyTest b4 = new MyTest("b4");
}
public new void MyFun()
{
MyTest b5 = new MyTest("b5");
}
}
static class Program
{
static void Main()
{
BaseB baseb = new BaseB();
baseb.MyFun();
}
}
public class MyTest
{
public MyTest(string info)
{
Console.WriteLine(info);
}
}

  最后的问题是:请写出Main()方法中,a1-a5,b1-b5这十个类实例化的顺序。(MyTest类是我自己添的,方便查看结果,原题是是实例化一个object类。)

  不知道园子里有多少人能胸有成竹的写出正确答案,反正我是答错了,正确答案是:

  b1
  b3
  b2
  a1
  a3
  a2
  a4
  b4
  b5
  题目中涉及到的知识点

  虽然题目没做对了,但要知道自己为什么会做错,这样才会有所提高,趁着端午的假期,我把这个面试题涉及到的知识点都梳理了一遍,要点如下:

内联(inline)方式初始化字段。
类型构造器(静态构造函数)的执行时间。
C#中基类和子类实例化的顺序。
new修饰符的作用。

  内联方式初始化字段

  这个知识点在《CLR via C#》书中有讲到,所谓内联方式,就是初始化字段的一种简化语法。来看示例代码:

public class SomeType
{
public int m_x = 5;
}

  这种在类中声明变量时进行赋值的方式就叫做内联,大致等效于下面的代码:

public class SomeType
{
public int m_x;
public SomeType()
{
m_x = 5;
}
}

  之所以说大致等效,因为两者的执行顺序上略有差异,编译器会首先生成内联方式的代码,然后再调用构造函数。

  比如,下面的代码,最后m_x的结果就为10。

public class SomeType
{
//先执行
public int m_x=5;
public SomeType()
{
//后执行
m_x = 10;
}
}

  类型构造器的执行

  所谓类型构造器也就是我们熟知的静态构造方法,在我们编写的类中,都会有一个默认的静态无参构造方法,跟无参实例构造方法一样是默认存在的。

  每当我们对一个类创建第一个实例或访问静态字段前,JIT编译器就会调用该类的静态构造方法。当然,静态变量也可以使用上面说的内联方法进行赋值。

  这里可以看出,当第一次实例化某个类时,会首先调用该类的静态构造方法。
  C#中基类和子类实例化的顺序

  这个知识点比较简单,那就是在调用子类实例构造方法之前会调用基类的实例构造方法。从面试题的结果可以看出,基类的构造方法又比子类的静态构造函数晚一些,此处因个人能力有限,我也没办法从更底层的角度去分析原理,只能暂且记住吧。
  new修饰符的作用

  我看过不少关于new以修饰符的形式用在方法声明中的题目,关于new的用法在MSDN上也都查的到,官方说法是显式隐藏从基类继承的成员。

  我个人的理解比较简单:当子类中,一个方法的签名(指参数,方法名,返回值)与基类的一个方法相同,通过加入new修饰符,可以让子类不做更改的去使用该方法。

  说到底,new修饰符就是让两个不相关的同名方法同时存在而已。(这里同名指相同的方法签名)
  最后

  回头想想,其实在我日常的项目开发中,多多少少都有涉及到这几个问题,只是平时不注意,没有深究吃透,写此文也是勉励自己以后要重视基础,不再浮躁。

Wednesday, September 07, 2011

.Net Smarteam Component Deployment

The production server might not get .Net SDK or VS installed. So need to create a setup package.

Updated Steps:
(1) Add new setup project .
(2) Add project output
(3) Right-click File System on Target Machine, click Add Special Folder, and then click Global Assembly Cache Folder
(4) Add project output again to Global Assembly Cache Folder

Tuesday, September 06, 2011

SSIS 2005 Running in 64Bit of Window Server 2008

Got the following error:

Error: Script could not be recompiled or run: Retrieving the COM class factory for component with CLSID {A138CF39-2CAE-42C2-ADB3-022658D79F2F} failed due to the following error: 80040154.. For more information, see the Microsoft Knowledge Base article, KB931846 (http://go.microsoft.com/fwlink/?LinkId=81885).

Solution:

go into project properties -- debugging -- debug options -- and set Run64bitRuntime to false.

Friday, September 02, 2011

Linq To Sharepoint (ZT)

 

From http://blog.csdn.net/xylinzai_xy/article/details/6442484

 

linq to sharepoint和linq to sql是不完全一样的,其中就包括linq to sharepoint 不支持query多个list. MSDN中表明 join() 操作是一种效率低下的查找操作,为了避免低效率的linq query in sharepoint ,我们可以用linq to sharepoint provider 和linq to objects provider.这两种providers来解决低效率的linq query

接下来是实例讲解如何在sharepoint 中用linq 的join操作来连接查询

假设在我们的站点中有2个list,结构如下:

ProjectList {ProjectID , ProjectManger,ProjectPeriod}

ProjectDetail {ProjectID, ProjectName}

这两个list是随便建立的它们之前通过ProjectID关联,最终我们要的结果是包含四个字段的一个集合

Object {ProjectID,ProjectName,ProjectManger,ProjectPeriod}

一、使用spmetal.exe 生成我们需要的linq to sharepoint 代理类

语法:spmetal /web:http://ip:port /namespace:tess /code:linqHelper.cs

二、 将生成的linqHelper.cs添加到项目中,并且添加引用Microsoft.SharePoint.Linq;

三、 编码

var dc = new LinqHelperDataContext(SPContext.Current.Web.Url);

var Projects = dc.GetList<Project>("ProjectList");

var Pnames = dc.GetList<ProjectDetailItem>("ProjectDetail");

接下来我们或许会这么写:

Var queryResult=from c in Projects join d in Pnames on c.ProjectID equals d. ProjectID

Select new {

c.ProjectID,

c.ProjectManagerName,

d.ProjectName,

c.ProjectPeriod

}

编译程序不会报错,但是当我们部署后,运行则报错!
linq to sharepoint 不支持多个list的连接查询

正确的做法:

把其中一个EntityList转变成generic list

假设我现在要把Pnames转换成 genericlist

1、 New一个实体类,该实体类的属性和ProjectDetail中的column对应

Public class TempProject

{

Public int32 ProjectID{get;set;}

Public string ProjectName{get;set;}

}

2、 接着上面的写:

var dc = new LinqHelperDataContext(SPContext.Current.Web.Url);

var Projects = dc.GetList<Project>("ProjectList");

var Pnames = dc.GetList<ProjectDetailItem>("ProjectDetail");

var details=from d in Pnames select d;

var p_details=new list<TempProject>();

foreach(var I in details)

{

p_details.Add(new TempProject (d.ProjectID, d.ProjectName));

}

var queryResult = from c in Projects

join cd in p_details

on c.ProjectID equals cd.ProjectID

select new

{

c.ProjectID,

c.ProjectManagerImnName,

cd.ProjectName,

c.ProjectPeriod

};

3、 绑定数据到spgridview

this.SPGridView1.DataSource = queryResult;

this.SPGridView1.DataBind();

注:我们也可以把2个Entitylist都转换成generic list,然后进行join 操作

---------------------------------------------------------

Another example

 

http://www.eggheadcafe.com/tutorials/aspnet/b0c1cd0d-fe82-444e-a16e-7d3fb7d38eca/join-lists-with-linq--sharepoint-2010.aspx

 

Good example

Thursday, September 01, 2011

SSIS Deplyment Tip 09-01-2011

 

--Using variable in package to store sensitive information like db connection string). In db connection property , select expression and put connectionstring=@User::variablename


-- if a package will execute another package ( need to set second package protectlevel from default to dosavesentive)