NetInverse Developers Blog

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 - the following code was contributed by Jessica L.
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 entity, string propertyName, object value)
        {
            PropertyInfo propertyInfo = typeof (T).GetProperty(propertyName);
            propertyInfo.SetValue(entity, value, null);
        }

    }

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

        private static MemberExpression GetMemberExpression(Expression> 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; }
    }
}
Category: WiX — Tags: , , , — admin @ 8:33 pm

If you have worked with MSI for a while, I bet you have encountered this: You have built and installed an MSI. Later on you change the WiX of it and build the new MSI, when you try to uninstall the old MSI with the new one, the uninstall fails.

In this case, you can

1) Use the utility tool MSIZap to clean up manually.
2) Or, do a force install with the new MSI using msiexec’s Repair Options. After that you can uninstall the MSI and go back to the good state.

msiexec /i /fe your_installer.msi

Repair Options
/f[p|e|c|m|s|o|d|a|u|v]
Repairs a product
p - only if file is missing
o - if file is missing or an older version is installed (default)
e - if file is missing or an equal or older version is installed
d - if file is missing or a different version is installed
c - if file is missing or checksum does not match the calculated value
a - forces all files to be reinstalled
u - all required user-specific registry entries (default)
m - all required computer-specific registry entries (default)
s - all existing shortcuts (default)
v - runs from source and recaches local package

December 8, 2009
Category: WiX — Tags: , , — admin @ 1:38 am

A sample master WiX file has includes:

<Directory Id="BIN" Name="bin">
    <?include ..\include\shared.wxi?>
        <Component Id="Service.SharedFiles" DiskId="1" Guid="72e3b959-9515-40ba-a095-bf788aa3d617">
            <CreateFolder>
                <Permission User="Administrators" GenericAll="yes" />

A sample shared.wxi to be included:

<?xml version="1.0"?>
<Include>
    <Component Id="Component_1" Guid="58345065-0314-41fd-9992-d960f297ba9a" DiskId="1">
        <File Id="File1" Name="Net_~1.dll" LongName="NetInverse.core.dll"
            KeyPath="yes" Compressed="yes" src="$(var.COREDIR)\bin\" />
 
November 14, 2009
Category: Debugging — Tags: , , , — admin @ 11:59 pm

Managed Memory Leak will be reported by an OutOfMemoryException exception thrown by the CLR. There are a few reasons will result in it.

1) Too many objects are alive.
2) Object handle leak. Use !sos.objsize to list handles.
3) Heap fragmentation. Use !sos.dumpheap to get excessive GC Heap fragmentation report.

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.

November 2, 2009
Category: Software Product Lines — Tags: — admin @ 11:19 pm
Software product lines

Software product lines

Software product lines, or software product line development, refers to software engineering methods, tools and techniques for creating a collection of similar software systems from a shared set of software assets using a common means of production. 

  • Software Product Lines Carnegie Mellon Software Engineering Institute Web Site
  • Software Products Lines Community Web Site and Discussion Forums
  • July 20, 2009
    Category: Agile — Tags: , , — admin @ 11:06 pm

    Net Objectives delivers Public Courses in all best practices of effective software development. Delivered in convenient, central locations, our courses are designed to help you and your team maximize the business value returned from your engineering efforts in software development and maintenance.

    Net Objectives Public Courses are delivered throughout the country. Use the below schedule to sort Courses by Course Name, Date, City or State.

    http://www.netobjectives.com/courses/

    July 8, 2009
    Category: SQL — Tags: — admin @ 10:25 pm

    Useful SQL Queries

    Showing the plan hash values:

    SELECT s.execution_count
          ,s.query_hash
          ,s.query_plan_hash
          ,t.text
    FROM   sys.dm_exec_query_stats s
           CROSS APPLY sys.dm_exec_sql_text(s.plan_handle) t

    Showing execution plans in the procedure cache:

    SELECT * FROM sys.dm_exec_cached_plans

    Showing fragmentation:

    SELECT  s.avg_fragmentation_in_percent
           ,s.fragment_count
           ,s.page_count
           ,s.avg_page_space_used_in_percent
           ,s.record_count
           ,avg_record_size_in_bytes
    FROM    sys.dm_db_index_physical_stats(DB_ID('AdventureWorks2008'),
                                           OBJECT_ID(N'dbo.t1'), NULL, NULL,
                                           'Sampled') AS s
    

    Show SQL memory usages:

    CACHESTORE_OBJCP: These are compiled plans for stored procedures, functions and triggers.
    CACHESTORE_SQLCP: These are cached SQL statements or batches that aren’t in stored procedures, functions and triggers. This includes any dynamic SQL or raw SELECT statements sent to the server.

    SELECT * FROM sys.dm_exec_cached_plans
    
    SELECT * FROM sys.dm_os_memory_cache_clock_hands
    WHERE TYPE IN ('CACHESTORE_SQLCP','CACHESTORE_OBJCP')
    ORDER BY removed_all_rounds_count desc 
    
    SELECT TOP 512
    	st.text,
    	cp.cacheobjtype,
    	cp.objtype,
    	cp.refcounts,
    	cp.usecounts,
    	cp.size_in_bytes,
    	cp.bucketid,
    	cp.plan_handle
    FROM sys.dm_exec_cached_plans as cp
    CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) as st
    WHERE cp.cacheobjtype = 'Compiled Plan' AND cp.objtype = 'Prepared'
    ORDER BY cp.usecounts desc
    
    SELECT  TOP 10
    	LEFT([name], 20) as [name],
    	LEFT([type], 20) as [type],
    	[single_pages_kb] + [multi_pages_kb] AS cache_kb,
    	[entries_count]
    FROM sys.dm_os_memory_cache_counters
    ORDER BY single_pages_kb + multi_pages_kb DESC
    
    SELECT TOP 10 type,
    	(sum(single_pages_kb) + sum(multi_pages_kb)) as 'Total Pages(KB)',
    	sum(single_pages_kb) as 'Single Pages(KB)',
    	sum(multi_pages_kb) as 'Multi Pages(KB)',
    	sum(virtual_memory_reserved_kb) as 'VM Reserved(KB)',
    	sum(virtual_memory_committed_kb) as 'VM Committed(KB)',
    	sum(awe_allocated_kb) as 'AWE Allocated(KB)',
    	sum(shared_memory_reserved_kb) as 'Shared Memory Reserved(KB)',
    	sum(shared_memory_committed_kb) as 'Shared Memory Committed(KB)'
    FROM sys.dm_os_memory_clerks
    GROUP BY type
    ORDER BY sum(single_pages_kb) + sum(multi_pages_kb) desc
    

    SQL Performance Tips

    Top SQL Server 2005 Performance Issues for OLTP Applications: http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/oltp-performance-issues.mspx
    Troubleshooting Performance Problems in SQL Server 2005: http://technet.microsoft.com/en-us/library/cc966540.aspx
    Batch Compilation, Recompilation, and Plan Caching Issues in SQL Server 2005: http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx

    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.

    Older Posts »

    ©2009 NetInverse. All rights reserved. Powered by WordPress