Thursday, April 18, 2013

Learn CSS

Blocking element div is the standard block-level element. A block-level element starts on a new line and stretches out to the left and right as far as it can. Other common block-level elements are p and form, and new in HTML5 are header, footer, section, and more.

Thursday, November 03, 2011

SQL Server : Adding RowId to Previous Result

Example:

Select row_number () over ( order by b.FieldName) , b.* from
(
select .....

)b



Real Code:
select row_number()over(order by b.DateResult) ,*
from(

SElect t.ECI,min(t.From_Date) as DateResult from @Table2 t group by ECI


)b

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.