September 26, 2012
@ 03:29 PM
I found this piece of code from stackflow, and I think it was very useful when you want to use a enum to a MVC dropdown.

    public static class EnumUtility
    {
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { Id = e, Name = e.ToString() };

            return new SelectList(values, "Id", "Name", enumObj);
        }
    }


 
Categories: C# | MVC

Custom Project Template with Wizard, create the new class with the name of custom value.
 
Categories: Asp.net | C# | Visual studio 10/up | VS 2008

  public static class UnityIOC
    {
        public static IUnityContainer Container;
        private static bool _isInited ;
        
        //Make it not dependends the application_start, 
        //this make the Controller can be tested in UnitTest tools
        static UnityIOC()
        {
            Initialise();
        }

        //call by global.asax application start for MVC
        public static void Initialise()
        {
            if (!_isInited)
            {
                _isInited = true;
                Container = BuildUnityContainer();
                DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
                //to use this container in mvc
                // DependencyResolver.Current.GetService(Type)  just resolve in ioc containner
            }
        }

        private static IUnityContainer BuildUnityContainer()
        {
            Container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<ITestService, TestService>();            
          //  Container.RegisterType<Widgets.WsunTest.Common.ILoggingService, Widgets.WsunTest.Common.WsunLoggingService>();

            //load web.config ref:http://msdn.microsoft.com/en-us/library/ff660935%28v=pandp.20%29.aspx
             Container.LoadConfiguration();

            Container.RegisterType
                <WsunTest.ViewModel.IWidgetModelFactory<WsunTest.Models.IWsunRequest, WsunTest.Models.WsunResponse>,
                    WsunTest.ViewModel.WsunTestModelFactory>()
                .RegisterType<WsunTest.Models.IWsunRequest, WsunTest.Models.WsunRequest>();
            
            return Container;
        }
    }


the Config in Web.Config
<configuration>
  
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity>">
    <containers>
      <!-- <alias alias="ILoggingService" type="Widgets.WsunTest.Common.ILoggingService" />
     <namespace name="Widgets.WsunTest.Common" />
      <assembly name="Widgets.WsunTest" /> -->
      <container>        
          <register  type="Widgets.WsunTest.Common.ILoggingService,Widgets.WsunTest"
                mapTo="Widgets.WsunTest.Common.WsunLoggingService, Widgets.WsunTest" />   
       
      </container>
    </containers>
  </unity>
Reference:
http://msdn.microsoft.com/en-us/library/ff660935%28v=pandp.20%29.aspx


 
Categories: C# | IoC | MVC

September 18, 2012
@ 07:49 PM
Just Implement a Controller Error Handler call "LogError":
  public class LogError : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            
           ILoggingService logService = DependencyResolver.Current.GetService<ILoggingService>();
          
           logService.Logging(filterContext.Exception.Message,1);

            //redirect to customer error page
            filterContext.Result =
               new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "WsunTest" },
                                                 { "action", "Error" },
                                                 {"message",filterContext.Exception.Message},
                                                 { "returnUrl",    filterContext.HttpContext.Request.RawUrl }
                                                });
            filterContext.ExceptionHandled = true;

        }
    }

And below is the controller, I put the filter on the top of Controller:
 [LogError]
    public class WsunTestController : Controller
    {
       
       public ActionResult Index()
       {
                throw  new Exception("test exception message");

            return View();
          
       }   
      

        public ActionResult Error(string message="unknow")
        {
            ViewBag.message=message;
            return View();
        }

}

There is another way is override the parent controller:
 protected override void OnException(ExceptionContext filterContext)
        {

            // Don't interfere if the exception is already handled
            if (filterContext.ExceptionHandled)
                return;
            //do something to handele the exception
            filterContext.ExceptionHandled = true;
}
Easy to understand..buy I think Filter or actionFilter is more flexible easy to use.


 
Categories: C# | MVC

September 16, 2012
@ 02:47 AM
I have some thoughts for making better code. I call it 3 rulers plus 2 sub rulers.

1 Readable : small function, single responsibility, straightforward name convention.
2. Re-useable: clear and simple responsibility, DRY
3. Testable : can be tested by UnitTest tools. Also I like write code that I can easily put a break point there.

+

4. flexible :  Prepare for future change,  configurable, lower coupling. using IoC.
5. performance: improve code for better performance or user experience, Threading, Cache, Ajax, Parallel LinQ,


4 and 5 have lower priority than 123.   You should know why ;)


 
Categories: C# | OODesign