Saturday, July 31, 2010

Translate<T> method in ObjectContext in Entity Framework 4

In Entity Framework 4, ObjectContext has a nice Translate<T> method. This method will materialize the result type. It takes your DbDataReader and materializes the data back into entities, the T can be a primitive type, an entity type, or any custom type you like, That type does not have to be defined in the Entity Framework conceptual model.

LINQ Join in Entity Framework 4

I want to explain a simple linq join in entity framework 4.

Thursday, July 29, 2010

How to install the latest Flex SDK into Flex builder 3

Installing the latest flex SDK into flex builder 3 is pretty simple. after you download the new version of SDK from Adobe website, then unzip that zip file and copy the content to a new folder created on a location
like C:\Program Files\Adobe\Flex Builder 3\sdks or any location you like, But I prefer that location.
From the main menu, select Window > Preferences > Flex > Installed SDKs and click Add to add a your new sdk and you can select the default SDK you want Flex builder to use to compile your program.
Cheers!

Wednesday, July 28, 2010

How to get only date part in T-sql DateTime

SELECT DATEADD(D, 0, DATEDIFF(D, 0, GETDATE()))

OR

SELECT CONVERT(DATETIME, FLOOR( CONVERT(FLOAT, GETDATE())))

Thursday, June 3, 2010

What is System.Lazy<T>

there is a new class in .Net framework 4.0 Called Lazy<T> that provides lazy initialization. Lazy initialization occurs the first time the Lazy<T>.Value property is accessed or the Lazy<T>.ToString method is called and the return value will be cached, it means the second time you access its value, the expression or function does not get executed.

Friday, April 23, 2010

URL with port number in Firefox

Firefox will block url containing port number for security reasons.
we can configure firefox to access url with port numbers.
we can override the blocked ports as follow:
Solution:
first type "about:config" into the address bar and press Enter.
then right click anywhere on the page and choose choose New -> String.
then type "network.security.ports.banned.override" in the textbox and click OK.
and in the value textbox we can enter port numbers seperated by comma., like 86,87,88
and then click OK.

How to decouple your application from IoC container implementation

As we all know, DI(Dependency Injection) is a form of IoC(Inversion of Control). when I use IoC Containers like Unity or Autofac to implement dependency injection, my application will be dependent on that framework, so if i decide to go for another IoC Container, I need to change a lot of things.what I want to achieve is how to make this change easier and how to decouple my application from any specific container. what i did is creating an interface to work with.


I need to add a reference to Microsoft.Practices.ServiceLocation.dll
and I make use of IServiseLocator interface in that assembly.
//IoCContainer.cs
//-----------------------------------------------------
using Microsoft.Practices.ServiceLocation;

public abstract class IocContainer
{
   public static IServiceLocator Locator;

   protected IocContainer()
   {
      Locator = CreateServiceLocator();
   }

  protected abstract IServiceLocator CreateServiceLocator();
}

public class IocContainerInitialization
{
  private static IocContainer _iocContainer;


  public static void Initialize(IocContainer iocContainer)
  {
    _iocContainer = iocContainer;
  }

  public static IocContainer IocContainer
  {
    get { return _iocContainer; }
  }
}
//-------------------------------------------------------------

//then for every IoC Container I want to use, I need to create a container //inheriting from that base IoCContainer class.

//for example, for using Autofac


//AutofacIocContainer.cs
//----------------------------------------------------------
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using AutofacContrib.CommonServiceLocator;
using Microsoft.Practices.ServiceLocation;

public class AutofacIocContainer : IocContainer
{
  protected override IServiceLocator CreateServiceLocator()
  {
    var containerBuilder = new ContainerBuilder();

    //For MVC-------------
  containerBuilder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
    //------------------------------------------------
    RegisterTypes(containerBuilder);

    ContainerProvider containerProvider = new ContainerProvider(containerBuilder.Build());

    //For MVC-------------------------------
    System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new  AutofacControllerFactory(containerProvider));
    //---------------------------------------------------

    return new AutofacServiceLocator(containerProvider.ApplicationContainer);
}

  private static void RegisterTypes(ContainerBuilder container)
  {
    //Cache per request
    container.Register(c => new DbHelper("MyConnectionString")).As().InstancePerLifetimeScope();

    container.Register(c => new DbMapper(c.Resolve())).As();
    container.Register(c => new TagRepository()).As();
    container.Register(c => new UserRepository()).As();
  }
}
//--------------------------------------------------------------

//Then, in your Global.asax file we need to initialize our Container.


void Application_Start(object sender, EventArgs e)
{
  IocContainerInitialization.Initialize(new AutofacIocContainer());
  RegisterRoutes(RouteTable.Routes);
}

Now, if you want to switch to another IoC Container, you only need to change one line and initialize another container.

cheers!

Thursday, April 22, 2010

ASP.NET ReportViewer problems on IIS 7

today we were trying to move our asp.net application to IIS 7, and there were some pages using ReportViewer in local mode. we had some problems to make it working.
The first thing to consider is that IIS7 need a new web.config structure. you have to register your httpModules and httpHandlers under system.webServer element instead of system.web

1- register the handler in the web.config file under system.webServer element

<system.webServer>
<add name="ReportViewerWebControl" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</system.webServer>

2- make sure on the aspx page using ReportViewer control you have registered the correct version. it must be like this:

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>


Cheers!

Friday, April 16, 2010

URL Routing in ASP.NET 3.5 Webform

URL Routing decouples the URL from a physical file on the disk, we can define routing rules to specify what URL maps to what physical files. ASP.NET Routing is not only for MVC and is independent library so ASP.NET Routing can be used in a traditional ASP.NET web forms.

First, add a reference to System.Web.Routing and make sure that web.config has UrlRoutingModule HTTP Module registered in httpModules section.

then, we create this class,

CustomRouteHandler.cs
//------------------------------------------------------
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}

public string VirtualPath { get; private set; }

public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
foreach (var paramUrl in requestContext.RouteData.Values)
{
requestContext.HttpContext.Items[paramUrl.Key] = paramUrl.Value;
}
var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
//--------------------------------------------------
Then in Global.asax file and in Application_Start event, I will define my routing rules.

Global.asax
//----------------------------------------------
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}


private void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.Clear();

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");

routes.Add("IndexPage", new Route("index/{page-num}", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("Index", new Route("index", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("ContactUs", new Route("contactus", new CustomRouteHandler("~/Home/contactus.aspx")));

}

The Route Data will be stored in HttpContext.Item (cache per request)
You can get the Route Data from HttpContext.Current.Items["name"] on the page.

Cheers!

Wednesday, April 14, 2010

Some Useful Design Principles

I am a big fan of design patterns and like these principles much, they can really help us decide better when facing design issues, even they can help in normal life when you don't program.


DRY : (Don't Repeat Yourself)
SOC : (Separation of Concerns)
KISS: (Keep it Simple and Stupid)
YAGNI : (You ain't gonna need it)
CQS : (Command-Query Separation)

SOLID Principles:
SRP:(single responsibility principle)
OCP:(Open Close Principle)
LSP: (Liskov substitution principle - Design By Contract)
ISP:(Interface-segregation principle)
DIP:(Dependency inversion principle)

Inheritance --> A is a kind of B
Composition --> A is a part of B
Aggregation --> A has a B

Cheers!