Context is King

No pain, no gain.

  • Google API for .NET architecture (Part 1)

    Today, I have just released a OSS with named is Gapi4net library at codeplex. This is a wrapper some of API's Google for search Web, Local, Video, Blog, News, Book, Image, Patent and language translation. In the past, I also saw some wrapper for Google API, specially are a google-api-for-dotnet, gapidotnet. But as I realized that they are hard to using and when you used them, you must remember many input parameters. For example, if you use the google-api-for-dotnet, you must input as:

  • Unit testing for a project that some classes inside it is marked with internal keyword

    Have you ever written a component that used for a other solution? This is meaning you write a component (for example, a third party, a extensions,...). So we usually use the "internal" keyword inside all classes in your component. Is it right?  And as you know if you use the "internal" keyword, you will not access from outside. Now I assume that you have a testing project out side the component project. How can you access to the internal classes inside your component project? If you try access to this component project, you will get one error "Cannot access internal class <ClassName> here"
    This post only a tips and tricks, so you can use it to access to the component that mark with the "internal" keyword. It is just simple is you must tell to the component project to assign enough permission to a assembly that want to access to your component.
    In order to make this, you are only need open the AssemblyInfo.cs file, and append one line to the end of this file. And this line is:
    [assembly: InternalsVisibleTo("<Namespace of the assembly that you want to access to this assembly>")]
    For example, I have the component project with namespace is Cik.Domain and the Unit Testing project is Cik.Domain.Testing. So I must open the AssemblyInfo.cs file inside the Cik.Domain project and add one line at the end of this file as: [assembly: InternalsVisibleToCik.Domain.Testing")]
    Now compile all projects, and all things will work well. You shall have enough visible to use some classes inside your component and do unit testing for it. I hope this tips and tricks will be useful for you.

  • The short example about EF4 CTP4 using DataAnnotation configuration

    In the last post at here, here and here, I wrote about EF4 (Entity Framework 4) with code-first approaching. In 3 parts, I used the configuration class for mapping with database (this feature is like Fluent NHibernate). But in the CTP4, we also use the DataAnnotation (new feature in .NET 4) for mapping with database. If we use the DataAnnotation, we shall be easy to mapping with much Convention over Configuration rules. You can go to this link for read all convention’s EF4 CTP. As Andrew suggest me, the example for mapping of my last post is very simple and did not have complex. So I downloaded the Northwind database from Microsoft and implemented in this post. Why do we use the DataAnnotation? As you know, Microsoft integrated it into .NET 4, and now they used it in all new technology, such as Silverlight, WPF, ASP.NET MVC… And in the future I think it will become popularly. And we shall be familiar with it, use it easily. In this post, I will explorer about mapping use the DataAnnotation, and some convention in relationship for ORM mapping.

  • Integrated StructureMap container for the MvcServiceLocator in ASP.NET MVC 3

    ASP.NET MVC 3 just released a few days ago. In this release, Microsoft team published some features very cool. I really love that, because we shall code easier. See release note for more information. And in this post, I would like to explore about MvcServiceLocator, one of features very interesting in this release. So why I want to know about that? Because in the past project in codeplex http://nma.codeplex.com, I used to CommonServiceLocator from Microsoft, and I must to customize it for integrated with StructureMap. Now, I don’t need making like that, because ASP.NET MVC team has already integrated it into core of ASP.NET MVC 3. That enough to talking, I only care about coding because I don’t want to talk more but not practice.

  • The short example about Entity Framework 4 CTP4 - Part 3

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4

    • Come with Entity Framework extensions

    Go to http://code.msdn.microsoft.com/EFExtensions/Release/ProjectReleases.aspx?ReleaseId=3624. And getting a source code of Entity Framework extensions, you must build it and get the dll with named EFExtensions.dll

    • Talk about Materializer and DbCommand

    We need a Materializer for build a static function that mapping a model contract with the result return from the store procedure. And we need the DbCommand for executing a store procedure. That is all things I knew about it. For more information, go to http://blogs.msdn.com/b/meek/archive/2008/03/26/ado-entity-framework-stored-procedure-customization.aspx. I think a expert at here will explain easily understanding than me. The theory is enough; I should focus on my work.

    • Build Contract Model for storing result that return from Store-Proc

    I must build the Contract Model for mapping result that invoke the store procedure

    public class SumarizeCategoriesAndNews
        {
            /// <summary>
            /// Gets or sets the category id.
            /// </summary>
            /// <value>The category id.</value>
            public int CategoryId { getset; }

            /// <summary>
            /// Gets or sets the name of the category.
            /// </summary>
            /// <value>The name of the category.</value>
            public string CategoryName { getset; }

            /// <summary>
            /// Gets or sets the category created date.
            /// </summary>
            /// <value>The category created date.</value>
            public DateTime CategoryCreatedDate { getset; }

            /// <summary>
            /// Gets or sets a value indicating whether [category is delete].
            /// </summary>
            /// <value><c>true</c> if [category is delete]; otherwise, <c>false</c>.</value>
            public bool CategoryIsDelete { getset; }

            /// <summary>
            /// Gets or sets the new id.
            /// </summary>
            /// <value>The new id.</value>
            public int NewId { getset; }

            /// <summary>
            /// Gets or sets the news title.
            /// </summary>
            /// <value>The news title.</value>
            public string NewsTitle { getset; }

            /// <summary>
            /// Gets or sets the content of the news.
            /// </summary>
            /// <value>The content of the news.</value>
            public string NewsContent { getset; }

            /// <summary>
            /// Gets or sets the news created date.
            /// </summary>
            /// <value>The news created date.</value>
            public DateTime NewsCreatedDate { getset; }

            /// <summary>
            /// Gets or sets a value indicating whether [news is delete].
            /// </summary>
            /// <value><c>true</c> if [news is delete]; otherwise, <c>false</c>.</value>
            public bool NewsIsDelete { getset; }
        }
    • Re-code the DbContext for mapping store procedure

    Next, I built the CSPDbContext partial class with named CSPDbContext.StoreProc and its code here:

        public partial class CSPDbContext
        {        
            private static readonly Materializer<SumarizeCategoriesAndNews> s_sumarizeCatAndNewsMaterializer = new Materializer<SumarizeCategoriesAndNews>(r =>
                new SumarizeCategoriesAndNews
                {
                    CategoryId = r.Field<int>("CategoryId"),
                    CategoryName = r.Field<string>("CategoryName"),
                    CategoryCreatedDate = r.Field<DateTime>("CategoryCreatedDate"),
                    CategoryIsDelete = r.Field<bool>("CategoryIsDelete"),
                    NewId = r.Field<int>("NewId"),
                    NewsTitle = r.Field<string>("NewsTitle"),
                    NewsContent = r.Field<string>("NewsContent"),
                    NewsCreatedDate = r.Field<DateTime>("NewsCreatedDate"),
                    NewsIsDelete = r.Field<bool>("NewsIsDelete"),
                });

            /// <summary>
            /// Gets the sumarize category and news.
            /// </summary>
            /// <returns></returns>
            public SumarizeCategoriesAndNews GetSumarizeCategoryAndNews()
            {
                // The CreateStoreCommand utility method simplified creation
                DbCommand command = this.ObjectContext.CreateStoreCommand(
                    "SumarizeCategoryAndNews",
                    CommandType.StoredProcedure,
                    null);
                SumarizeCategoriesAndNews catAndNews = s_sumarizeCatAndNewsMaterializer
                    .Materialize(command)   // Returns typed results given a DB command.
                    .SingleOrDefault();     // We expect at most a single match for this stored procedure.

                return catAndNews;
            }
        }

    As you see, I invoked the store-proc with named [SumarizeCategoryAndNews]. I think it is clear with anyone that read this code.

    And the Repository, we only need called it as:

            public SumarizeCategoriesAndNews GetSumarizeCategoriesAndNews()
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                return temp.GetSumarizeCategoryAndNews();
            }

     

    Finally I do unit testing for this function:

             [TestMethod()]
            public void GetSumarizeCategoriesAndNewsTesting()
            {
                var result = CategoryRepository.GetSumarizeCategoriesAndNews();

                Assert.IsNotNull(result);
                Assert.AreEqual(result.CategoryName, "test");
                Assert.AreEqual(result.CategoryIsDelete, false);
            }
    Notes:
    • You must run the Databasescript.sql to created the store-proc after you created successful the database schema
    • You must set the command 
      Database.SetInitializer<CSPDbContext>(newRecreateDatabaseIfModelChanges<CSPDbContext>());
      //Database.SetInitializer<CSPDbContext>(new DontTouchMyDatabase<CSPDbContext>());
      at Testing base class for created new database schema
    More developing:
    • Intergrated with IoC container (Unity 2.0, Structure Map, MEF,..) 
    • Do more Unit Testing
    Read further:
    • Data Annotation on EF4 CTP4
    • WCF ADO.NET Data Service based on EF4 CTP4 

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    Part 2: Repository and Unit of Work on Entity Framework 4

  • The short example about Entity Framework 4 CTP4 - Part 2

    Part 2: Repository and Unit of Work on Entity Framework 4

    • Create the repository for persistence ignorance

    Up to now, I very love the Persistence Ignorance. So what is it? I remembered that I usually built the Data Access Layer for access Database in the past. That is make your layer is coupling with the Database. So it is not good if you change database, change something else. So what do you think if we don’t need to know about it? Just tell the class that “I want to make something, and don’t care what happen in the behind scene.” It’s really good, and that is a place where Repository pattern jumps into. For more information, go to http://martinfowler.com/eaaCatalog/repository.html. I don’t want to speak more about it. Now we shall continue on my example. The first thing, we must to build is a IRepository interface for making a contract.

        public interface IRepository<T> where T : IEntity
        {
        }

    IRepository is constraint on T generic type and must be an IEntity. Now I want to separate with 2 Repositories that do specific jobs. At here, I divided 2 Repositories with 2 contracts are: ICommandRepository and IQueryRepository. ICommandRepository contains all actions about CRUD, and IQueryRepository contains all actions about query data. That is it.

        public interface ICommandRepository<T> : IRepository<T> where T : IEntity
        {
            /// <summary>
            /// Gets the by id.
            /// </summary>
            /// <param name="id">The id.</param>
            /// <returns></returns>
            T GetById(int id);

            /// <summary>
            /// Adds the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            /// <returns></returns>
            T Add(T entity);

            /// <summary>
            /// Updates the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            void Update(T entity);

            /// <summary>
            /// Deletes the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            void Delete(T entity);

            /// <summary>
            /// Deletes the specified id.
            /// </summary>
            /// <param name="id">The id.</param>
            void Delete(int id);

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            IUnitOfWork UnitOfWork();
        }

    And,

        public interface IQueryRepository<T> : IRepository<T> where T : IEntity
        {
            /// <summary>
            /// Gets all.
            /// </summary>
            /// <returns></returns>
            IEnumerable<T> GetAll();

            /// <summary>
            /// Gets the specified where.
            /// </summary>
            /// <param name="where">The where.</param>
            /// <returns></returns>
            IEnumerable<T> Get(Func<T, bool> where);
        }

    I also have a base Repository for re-use all things that you think it can shared for all Repository used.

        public abstract class BaseRepository<T> : IDisposable
        {
            private DbContext _dbContext;

            /// <summary>
            /// Initializes a new instance of the <see cref="BaseRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public BaseRepository(IDatabaseFactory databaseFactory)
            {
                Contract.Assert(databaseFactory != null"DatabaseFactory is null");

                DatabaseFactory = databaseFactory;
            }

            /// <summary>
            /// Gets or sets the database factory.
            /// </summary>
            /// <value>The database factory.</value>
            protected IDatabaseFactory DatabaseFactory
            {
                get;
                private set;
            }

            /// <summary>
            /// Gets the db context.
            /// </summary>
            /// <value>The db context.</value>
            protected DbContext DbContext
            {
                [DebuggerStepThrough]
                get
                {
                    return _dbContext ?? (_dbContext = DatabaseFactory.Get());
                }
            }

            /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            public void Dispose()
            {
                if (DbContext != null)
                    GC.SuppressFinalize(DbContext);

                if (DatabaseFactory != null)
                    GC.SuppressFinalize(DatabaseFactory);
            }
        }
    Now we can implement the CategoryRepository as below:
        public interface ICategoryRepository : ICommandRepository<Category>, IQueryRepository<Category>
        {
        }
        public class CategoryRepository : BaseRepository<Category>, ICategoryRepository
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CategoryRepository"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public CategoryRepository(IDatabaseFactory databaseFactory)
                : base(databaseFactory)
            {
            }

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            public IUnitOfWork UnitOfWork()
            {
                return DbContext as CSPDbContext;
            }

            /// <summary>
            /// Gets the by id.
            /// </summary>
            /// <param name="id">The id.</param>
            /// <returns></returns>
            public Category GetById(int id)
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                return (temp).Categories.Where<Category>(x => x.Id == id).FirstOrDefault<Category>();
            }

            /// <summary>
            /// Adds the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            /// <returns></returns>
            public Category Add(Category entity)
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                temp.Categories.Add(entity);

                return entity;
            }

            ...


        }
    • Unit of Work on EF4 

    This is a hard pattern in EF4, so I will don’t explain about it. I just gave you a reference to read it, and I also implemented according to this link

    http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

    This is my code:

        public interface IUnitOfWork
        {
            /// <summary>
            /// Saves this instance.
            /// </summary>
            void Save();
        }
     
        public partial class CSPDbContext : DbContextIUnitOfWork
        {
            ...
            /// <summary>
            /// Saves this instance.
            /// </summary>
            public void Save()
            {
                SaveChanges();
            }
        }

    I gave the CSPDbContext implementing the IUnitOfWork contract, and

    public class CategoryRepository : BaseRepository<Category>, ICategoryRepository
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CategoryRepository"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public CategoryRepository(IDatabaseFactory databaseFactory)
                : base(databaseFactory)
            {
            }

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            public IUnitOfWork UnitOfWork()
            {
                return DbContext as CSPDbContext;
            }
            ...
        }

    Now I do unit testing for CategoryRepository as:

            [TestMethod()]
            public void GetAllTesting()
            {
                var result = CategoryRepository.GetAll();
                Assert.IsNotNull(result);
            }
            [TestMethod()]
          public void AddCategoryTesting()
            {
                var entity = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test"
                });

                Assert.IsNotNull(entity);
                Assert.AreEqual(entity.Name, "test");
                Assert.AreEqual(entity.IsDelete, false);
            }

    Unit testing for UnitOfWork:

            [TestMethod()]
            public void UnitOfWorkTesting()
            {
                var uow = CategoryRepository.UnitOfWork();

                var entity1 = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test3",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test3"
                });

                var entity2 = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test4",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test4"
                });

                uow.Save();
            }
     

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4