NetInverse Developers Blog

May 3, 2010
Category: .Net — Tags: — admin @ 11:24 pm

A sample of LINQ provider.

using System;
using System.Collections;

namespace LINQSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var myNumberServer = new MyNumberServer(323, 2);
            var query = from a in myNumberServer
                        where a != 3
                        select a;

            foreach(var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }

    public class MyNumberServer
    {
        private readonly int _numberToServer;
        private readonly int _length;

        public MyNumberServer(int init, int length)
        {
            _numberToServer = init;
            _length = length;
        }

        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < _length; i++)
            {
                yield return _numberToServer;
            }
        }
    }

    public static class Extensions
    {
        public static IEnumerable Where(this MyNumberServer source, Func<int, bool> predicate)
        {
            foreach (int item in source)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }

        public static IEnumerable Select(this MyNumberServer source, Func<object, object> selector)
        {
            foreach (var item in source)
            {
                yield return selector(item);
            }
        }

        public static IEnumerable Cast(this MyNumberServer source)
        {
            foreach (var item in source)
            {
                yield return (int)(item);
            }
        }
    }
 }

Note: This is a sample from the book “Essential LINQ”.

Category: .Net — Tags: — admin @ 10:12 pm

IQueryable<T> is the type used in LINQ to SQL queries. IQueryable<T> differs from IEnumerable<T> in that it includes an expression tree. In particular, the type takes the following shape:

public interface IQueryable<T> : IEnumerable<T>, IQueryable, IEnumerable
{
}

The important interface in this declaration is IQueryable:

public interface IQueryable: IEnumerable
{
   Type ElementType {get;}
   Expression Expression {get;}
   IQueryProvider Provider {get;}
}

The key property  here is the middle one - Expression. IQueryable<T> implements IEnumerable<T>.

February 8, 2010
Category: .Net — Tags: , — admin @ 10:32 pm

Dynamic reflection is the classic .Net reflection. Now there is a new pattern called “Static Reflection” which is very popular in some open source code like nHibernate. Static Reflection’s main
benefit is “refactoring” friendly. For example, in the following code snippet, if you use the static relfection and change the property name, it won’t break. If you use the string to locate the property, it will break easily.

    //Classic Reflection
    var entity = new SampleEntity();
    entity.SetValue(entity, "Id", 100); //dynamic binding
    entity.SetValue(entity, "Name", "Sample");

    //Static Relection
    var entity1 = new SampleEntity();
    entity1.SetValue(e => e.Id, 100); //early binding
    entity1.SetValue(e => e.Name, "Sample");
// Static reflections.cs

using System;
using System.Linq.Expressions;
using System.Reflection;

namespace LinqExpressionSample
{
    public class SampleEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public void SetValue<T>(T entity, string propertyName, object value)
        {
            PropertyInfo propertyInfo = typeof (T).GetProperty(propertyName);
            propertyInfo.SetValue(entity, value, null);
        }

    }

    public static class Extension
    {
        public static void SetValue<T>(this T entity, Expression<Func<T, object>> expression, object value)
        {
            MemberExpression memberExpression = GetMemberExpression(expression);
            var propertyInfo = memberExpression.Member as PropertyInfo;
            propertyInfo.SetValue(entity, value, null);
        }

        private static MemberExpression GetMemberExpression<T, TValue>(Expression<Func<T, TValue>> expression)
        {
            if (expression == null)
            {
                return null;
            }
            if (expression.Body is MemberExpression)
            {
                return (MemberExpression)expression.Body;
            }
            if (expression.Body is UnaryExpression)
            {
                var operand = ((UnaryExpression)expression.Body).Operand;
                if (operand is MemberExpression)
                {
                    return (MemberExpression)operand;
                }
                if (operand is MethodCallExpression)
                {
                    return ((MethodCallExpression)operand).Object as MemberExpression;
                }
            }
            return null;
        }
    }
}
January 5, 2010
Category: .Net — Tags: , , , , , — admin @ 9:59 pm

If you use WCF to create web services, you need to define your data contracts by using DataContract/DataMember attributes.
Actually you can use them directly for serialization/deserialization in your code. Following is a sample of how to use DataContract/DataMember attributes for fast object Xml serialization and deserialization.

using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace DataContractSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student()
            {
                Age = 12,
                Name = "David"
            };

            DataContractSerializer dcs = new DataContractSerializer(typeof(Student));
            StringBuilder sb = new StringBuilder();

            using(XmlWriter writer = XmlWriter.Create(sb))
            {
                dcs.WriteObject(writer, student);
            }
            string xml = sb.ToString();

            using (XmlTextReader reader = new XmlTextReader(new StringReader(xml)))
            {
                Student newStudent = (Student) dcs.ReadObject(reader, true);
            }
        }
    }

    [DataContract(Namespace="http://www.netinverse.com")]
    public class Student
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
}
November 14, 2009
Category: .Net — Tags: , , , — admin @ 11:42 pm

There are two types of heap corruptions: 1) NT Heap Corruption 2) GC Heap Corruption.

GCSTRESS is a checked or debugging build with some registry keys set used to debug the GC Heap Corruption. It forces the garbage collection to occur very oftern to shake out a bug.

June 20, 2009
Category: .Net, Agile — Tags: , , — admin @ 12:11 am

Pragmatic programmers use feedback to drive their development and personal processes. The most valuable feedback you can get while coding comes from unit testing. Now in it’s second edition, Pragmatic Unit Testing in C# with NUnit, 2nd Ed. will show you how to do software unit testing, of course, but more importantly will show you what to test.

About this book

New for the Second Edition:

  • Updated for NUnit 2.4 (C#, .NET 2.0, Visual Studio 2005, and Mono)
  • More NUnit assert methods
  • New String and Collection assertion support
  • Better support for multiple-platform development (Mono and .NET)
  • Higher-level setup and teardown fixtures
  • …and more!

Without good tests in place, coding can become a frustrating game of “whack-a-mole.” That’s the carnival game where the player strikes at a mechanical mole; it retreats and another mole pops up on the opposite side of the field. The moles pop up and down so fast that you end up flailing your mallet helplessly as the moles continue to pop up where you least expect them. You need automated testing and regression testing to keep the moles from popping up.

You don’t test a bridge by driving a single car over it right down the middle lane on a clear, calm day. Yet many programmers approach testing that same way—one pass right down the middle and they call it “tested.” Pragmatic programmers can do better than that!

With this book, you will:

  • Write better code, faster
  • Discover the best hiding places where C# bugs breed
  • Learn how to think of all the things that could go wrong
  • Test pieces of code without using the whole .NET project
  • Use NUnit to simplify your C# test code
  • Test effectively with the whole team

Real software unit testing will make your life easier. It will make your software design and architecture better and drastically reduce the amount of time you spend debugging you .NET code.

June 18, 2009
Category: .Net — Tags: , — admin @ 11:21 pm

Igor Ostrovsky’s LINQ Tips:

Check out Igor’s site.

May 30, 2009
Category: .Net — Tags: , — admin @ 11:23 pm

Microsoft just released Beta 1 versions of Visual Studio 2010 and .NET 4.0, which contain its new support for parallel programming. The v1 of Parallel Extensions for .Net is part of .Net 4.0.

Parallel Extensions includes task and data parallelism, and tools for building concurrent and parallel applications. This is a sine qua non feature considering the increasing occurrence of multiple core processors, because the chips aren’t getting faster, they’re just adding more cores.

April 23, 2009
Category: .Net, CLR, Debugging — Tags: , — admin @ 10:53 pm

CLR Internal - ObjHeader

Every Object is preceded by an object header -ObjHeader (at a negative offset). ObjHeader is a DWORD and has a combination of different bit masks (defined in Syncblk.h) like hash code, AppDomain index, flags to facility string operations, thin lock bit and etc.

When the DWORD is not large enough, CLR will create a SyncBlock for the object and set the SyncBlock index in object header.

Category: .Net, CLR, Debugging — Tags: , , — admin @ 10:14 pm

CLR Internal: SyncBlock

CLR Object Internal - from Shared Source CLI Essentials

CLR Object Internal - from Shared Source CLI Essentials

Every Object is preceded by an ObjHeader (at a negative offset). The ObjHeader has an index to a SyncBlock. This index is 0 for the bulk of all instances, which indicates that the object shares a dummy SyncBlock with most other objects. All SyncBlocks are stored in SyncTable as an array and managed by SyncBlockCache.

The SyncBlock is primarily responsible for object synchronization. However, it is also a “kitchen sink” of sparsely allocated instance data. For instance, the default implementation of Hash() is based on the existence of a SyncTableEntry. And objects exposed to or from COM, or through context boundaries, can store sparse data here.

SyncTableEntries and SyncBlocks are allocated in non-GC memory. A weak pointer from the SyncTableEntry to the instance is used to ensure that the SyncBlock and SyncTableEntry are reclaimed (recycled) when the instance dies.

The organization of the SyncBlocks isn’t intuitive (at least to me). Here’s the explanation:

Before each Object is an ObjHeader. If the object has a SyncBlock, the ObjHeader contains a non-0 index to it.

The index is looked up in the g_pSyncTable of SyncTableEntries. This means the table is consecutive for all outstanding indices. Whenever it needs to grow, it doubles in size and copies all the original entries. The old table is kept until GC time, when it can be safely discarded.

Each SyncTableEntry has a backpointer to the object and a forward pointer to the actual SyncBlock. The SyncBlock is allocated out of a SyncBlockArray which is essentially just a block of SyncBlocks.

The SyncBlockArrays are managed by a SyncBlockCache that handles the actual allocations and frees of the blocks.

Each allocation and release has to handle free lists in the table of entries and the table of blocks.

We burn an extra 4 bytes for the pointer from the SyncTableEntry to the SyncBlock.

The reason for this is that many objects have a SyncTableEntry but no SyncBlock. That’s because someone (e.g. HashTable) called Hash() on them.

- syncblk.h

Older Posts »

©2009 NetInverse. All rights reserved. Powered by WordPress