<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>arash karami</title>
	<atom:link href="http://arash.im/feed/" rel="self" type="application/rss+xml" />
	<link>http://arash.im</link>
	<description>.NET and Open source are better together</description>
	<lastBuildDate>Sat, 17 Dec 2011 18:28:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>I used n-layer architecture for my MVC projects</title>
		<link>http://arash.im/2011/12/i-used-the-n-layer-architecture-for-my-mvc-projects/</link>
		<comments>http://arash.im/2011/12/i-used-the-n-layer-architecture-for-my-mvc-projects/#comments</comments>
		<pubDate>Tue, 06 Dec 2011 18:17:54 +0000</pubDate>
		<dc:creator>arash</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity framework]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[nuget]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Entity-framework]]></category>
		<category><![CDATA[MVC3]]></category>
		<category><![CDATA[Pattern]]></category>

		<guid isPermaLink="false">http://www.arash.im/?p=32</guid>
		<description><![CDATA[Really I enjoyed who that thinks about architecture and patterns and some ways for organization own source codes before starting a project. After doing some patterns for organization coding in n-layers applications based on my knowledge I found a best practice for implement n-layers application: My source code for this post: github repository. In two [...]]]></description>
				<content:encoded><![CDATA[<p>Really I enjoyed who that thinks about architecture and patterns and some ways for organization own source codes before starting a project. After doing some patterns for organization coding in n-layers applications based on my knowledge I found a best practice for implement n-layers application:</p>
<div id="attachment_89" class="wp-caption alignright" style="width: 186px"><a href="http://arash.im/wp-content/uploads/2011/12/n-layer-architecture.png"><img class="size-medium wp-image-89" title="n-layer-architecture schema" src="http://arash.im/wp-content/uploads/2011/12/n-layer-architecture-176x300.png" alt="N-layer architecture schema" width="176" height="300" /></a><p class="wp-caption-text">N-layer architecture schema</p></div>
<blockquote>
<ul>
<li><strong>My source code for this post: <a title="github repository" href="https://github.com/arashkarami/nlayeredMVC/downloads" target="_blank">github repository</a>.</strong></li>
</ul>
</blockquote>
<p>In two recent posts I took about entity framework 4.1/2 features and then create a domain layer for using their layers in UI layer.<br />
In this post I will talk about an independent UI (web) layer. So, for this independency in web layer I used a dependency injection tool for using direct service interfaces in all controllers. According to this link with some benchmarks seems structuremap is better than other dependency injection third-parties tools. So I used structuremap.<br />
Also, you can create a utility project and import all common your extension classes and your general html helpers for using to this project or other projects (may be as a template project).for do this, you should add system.web and system.web.mvc references to utility project.<br />
<a href="http://arash.im/wp-content/uploads/2011/12/Utility-project.png"><img class="alignleft size-full wp-image-76" title="Utility-project" src="http://arash.im/wp-content/uploads/2011/12/Utility-project.png" alt="" width="256" height="291" /></a><br />
Note: Maybe you want using utility library to all your enterprise applications, for this case you can make a local nuget package from this utility project, and then add utility package to all projects very fast. I’ll talk about “How to organized local nuget packages” in the next posts, but now you can see <a title="Hanselman post" href="http://www.hanselman.com/blog/NuGetForTheEnterpriseNuGetInAContinuousIntegrationAutomatedBuildSystem.aspx" target="_blank">hanselman post</a> about ‘how to create nuget packages’ or some docs in <a title="official nuget site" href="http://nuget.org/" target="_blank">official nuget site.</a> or visit this <a title="weblog" href="http://www.marcusoft.net/2011/09/creating-local-nuget-repository-with.html" target="_blank">weblog</a><br />
Anyway, come back to our target! I want create a sample for using domain layer in MVC project, so I choose membership subject for my sample. I wrote a customized membership. For do that, we should dirty some Domain codes.<br />
<a href="http://arash.im/wp-content/uploads/2011/12/Site-layer-for-authentication.png"><img class="alignright size-medium wp-image-77" title="Site-layer-for-authentication" src="http://arash.im/wp-content/uploads/2011/12/Site-layer-for-authentication-187x300.png" alt="" width="187" height="300" /></a><br />
You can assume I want create a form-Authentication based on .NET and using native classes for authentication with cookies in .NET but In this sample I want show to you that how to using native .net framework for making session based authentication.<br />
In above figure you see some new classes under “Site” namespace. Please for more information about project check out project from Github.<br />
There is a Controller class in Site namespace that I called <em>AuthenticationController</em>.<br />
This base class for all controllers can do authentication and authorization for all users with difference roles.</p>
<pre class="brush: csharp">using System.Threading;
using System.Web.Mvc;

namespace Arash.Membership.Site
{
    public class AuthenticationController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (SessionPersister.SitePrincipal != null)
            {
                Thread.CurrentPrincipal = SessionPersister.SitePrincipal;
                filterContext.HttpContext.User = SessionPersister.SitePrincipal;
            }

            base.OnAuthorization(filterContext);
        }
    }
}</pre>
<p>Other classes such as SiteIndentity or SitePrincipal are only an implement of some native .NET interfaces.<br />
And Now Web layer:<br />
- Install structuremap:<br />
I added this third-party with execute command in packet manager:</p>
<p><a href="http://nuget.org/packages/structuremap"> PM&gt; Install-Package structuremap</a></p>
<p>For using authentication you can create a derived controller form Authentication controller.<br />
Conclusions:<br />
After recent three posts we could create a new organized model for creating n-layer applications. And then implement a session based authentication model for sample, I hope you use this model and say me disadvantages or advantages.</p>
<p>You can download this sample form <a title="github repository" href="https://github.com/arashkarami/nlayeredMVC/downloads" target="_blank">github repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://arash.im/2011/12/i-used-the-n-layer-architecture-for-my-mvc-projects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Entity framework features Part 2</title>
		<link>http://arash.im/2011/11/useing-entity-framework-features-part2/</link>
		<comments>http://arash.im/2011/11/useing-entity-framework-features-part2/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 16:12:00 +0000</pubDate>
		<dc:creator>arash</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Entity framework]]></category>
		<category><![CDATA[Data-Access-architecture]]></category>
		<category><![CDATA[Entity-framework]]></category>

		<guid isPermaLink="false">http://www.arash.im/?p=25</guid>
		<description><![CDATA[In the previous post, I talked about the advantages of using code first method and EF4.1/2 , created a sample model in a domain project, then added DataAccess project for direct use in an MVC project. Now I want to use data access in my service layer. How? Recently i heard about repository pattern! So I&#8217;m [...]]]></description>
				<content:encoded><![CDATA[<p>In the previous <a title="post" href="http://arash.im/2011/11/why-don%e2%80%99t-used-entity-framework-features-part-1/" target="_blank">post</a>, I talked about the advantages of using code first method and EF4.1/2 , created a sample model in a domain project, then added DataAccess project for direct use in an MVC project. Now I want to use data access in my service layer. How?</p>
<p>Recently i heard about repository pattern! So I&#8217;m implementing this in a new project and then i&#8217;ll complete the domain layer:</p>
<p>&nbsp;</p>
<p>Before implementing the repository pattern i need an interface to access the DataAccess layer, So i create IDbContext interface in the Infrastructure library project:</p>
<p><span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">public interface IDbContext</span></p>
<pre class="brush: csharp">    {
        IDbSet Set() where T : class;

        Database Db { get; }

        int SaveChanges();
    }</pre>
<p>Now i add a <a title="Repository pattern" href="http://msdn.microsoft.com/en-us/library/ff649690.aspx" target="_blank">Repository pattern</a> to the project:</p>
<p>First i use an interface repository in Infrastructure project:</p>
<pre class="brush: csharp">public interface IRepository where T : class
{
        ///
<summary> /// Create New Instance /// </summary>

 T NewEntityInstance(); ///
<summary> /// Inserts an item /// </summary>

 void Add(T item); ///
<summary> /// Deletes an item /// </summary>

 void Remove(T item); ///
<summary> /// Get an item matching to prediate /// </summary>

 T Get(Funcpredicate); ///
<summary> /// Get Count of items matching to predicate /// </summary>

 int GetCount(Funcpredicate); ///
<summary> /// Get IEnumerable object matching to predicate /// </summary>

 IEnumerableGetAll(Funcpredicate); ///
<summary> /// Get IEnumerable object matching to predicate,start index and count /// </summary>

 IEnumerableGetAll(Funcpredicate, int start, int count); ///
<summary> /// Saves the pending changes back into the DataContext. /// </summary>

 void Save();
}</pre>
<p>And then put it in DataAccess project:</p>
<pre class="brush: csharp">    public class Repository : IRepository where T : class
    {
        protected IDbContext _Context;
        protected IDbSet _DbSet;

        public Repository(IDbContext context)
        {
            _Context = context;
            _DbSet = _Context.Set();
        }

        public T NewEntityInstance()
        {
            return _DbSet.Create();
        }

        public void Add(T entity)
        {
            _DbSet.Add(entity);
        }

        public virtual IQueryable GetAll()
        {
            return _DbSet.AsQueryable();
        }

        public void Remove(T entity)
        {
            _DbSet.Remove(entity);
        }

        public T Get(Func predicate)
        {
            return _DbSet.FirstOrDefault(predicate);
        }

        public int GetCount(Func predicate)
        {
            return _DbSet.Count(predicate);
        }

        public IEnumerable GetAll(Func predicate)
        {
            return _DbSet.Where(predicate);
        }

        public IEnumerable GetAll(Func predicate, int start, int count)
        {
            return _DbSet.Where(predicate).Skip(start).Take(count);
        }

        public void Save()
        {
            try
            {
                _Context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                var s = e.EntityValidationErrors.ToList();
                throw;
            }
        }

        public IEnumerable GetQuery(string queryString, Func predicate = null) where K : class
        {
            if (predicate != null)
                return _Context.Db.SqlQuery(queryString).Where(predicate);
            return _Context.Db.SqlQuery(queryString);

        }
    }</pre>
<p>Good, Service classes are ready to be used in Controllers and action methods.</p>
<p>How to create a service:</p>
<p>for example i wrote a simple service named MemberManager:</p>
<pre class="brush: csharp">using System;
using System.Collections.Generic;
using Arash.Membership.Model;

namespace Arash.Core
{
    public interface IMemberManager
    {
        Member MakeInstance();

        void Add(Member entity);

        void Edit(Member entity);

        void Remove(Member entity);

        int GetCount(Func predicate = null);

        Member Get(Func predicate = null);

        IEnumerable GetAll(Func predicate = null, int start = 0, int count = 6);

        Member Authenticate(string username, string password);
    }
}</pre>
<p>implemented Member service class:</p>
<pre class="brush: csharp">using System;
using System.Collections.Generic;
using Arash.Membership.Model;
using Arash.Utility.Common;
using Paradiso.Infrastructure.Data;
using Arash.Infrastructure.Data;

namespace Arash.Core.Manager
{
    public class MemberManager : IMemberManager
    {
        private IRepository _repository;

        public MemberManager(IRepository repository)
        {
            _repository = repository;
        }

        public Member MakeInstance()
        {
            return _repository.NewEntityInstance();
        }

        public void Add(Member entity)
        {
            _repository.Add(entity);
            _repository.Save();
        }

        public void Edit(Member entity)
        {
            _repository.Save();
        }

        public void Remove(Member entity)
        {
            _repository.Remove(entity);
            _repository.Save();
        }

        public int GetCount(Func predicate = null)
        {
            return predicate == null
                ? _repository.GetCount(p =&gt; true)
                : _repository.GetCount(predicate);
        }

        public Member Get(Func predicate = null)
        {
            return predicate == null
                ? _repository.Get(p =&gt; true)
                : _repository.Get(predicate);
        }

        public IEnumerable GetAll(Func predicate = null, int start = 0, int count = 6)
        {
            return predicate == null
                 ? _repository.GetAll(p =&gt; true)
                 : start == 0
                     ? _repository.GetAll(predicate)
                     : _repository.GetAll(predicate, start, count);
        }

        public Member Authenticate(string username, string password)
        {
            var entity = _repository.Get(p =&gt; p.Username == username);

            if (entity == null)
                return null;

            var passwordHash = PasswordGenerator.GetHashPassword(password);

            if (!string.Equals(passwordHash, password))
                return null;

            return entity;
        }
    }
}</pre>
<p>Conclusion:</p>
<p>We learned how to implement some layers in n-layer architecture. Ofcourse you can download source codes of posts part1 and 2 from <a href="https://github.com/arashkarami/EF4XSample/downloads" title="my github account">github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://arash.im/2011/11/useing-entity-framework-features-part2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Entity framework features Part 1</title>
		<link>http://arash.im/2011/11/using-entity-framework-features-part-1/</link>
		<comments>http://arash.im/2011/11/using-entity-framework-features-part-1/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 13:20:12 +0000</pubDate>
		<dc:creator>arash</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity framework]]></category>
		<category><![CDATA[code-first]]></category>
		<category><![CDATA[Data-Access-architecture]]></category>
		<category><![CDATA[Entity-framework]]></category>

		<guid isPermaLink="false">http://www.arash.im/?p=19</guid>
		<description><![CDATA[About two year ago I wrote many storeprocedures and many string queries and views for data access layer projects. But after some months my life is better: come up Linq to SQL and then advent Entity framework 4.0. We added a .edmx file to project and map all table entities to project and use modelEntities [...]]]></description>
				<content:encoded><![CDATA[<p style="text-align: left;">About two year ago I wrote many storeprocedures and many string queries and views for data access layer projects. But after some months my life is better: come up Linq to SQL and then advent Entity framework 4.0. We added a .edmx file to project and map all table entities to project and use modelEntities context for using hot LINQ queries. I was very happy when used this technology and then come up many other templates (T4 templates) for change tracking, making POCO classes, … . Entity framework had two concepts: model first and Database first, I guess you known about them, until come up Entity framework 4.1.</p>
<p>So today I want speak about entity framework 4.1/2.</p>
<p>In the EF 4.1/2 we can design a project with code first approach and make a dynamic SQL database.</p>
<p>Why don’t used Entity framework features?</p>
<ul>
<li>Without create a database project and writing dummy query and insert data to DB for test we could create a DbContextInitializer class for create dummy objects for creating Database and insert all objects to Database.</li>
</ul>
<ul>
<li>We could separate all entities form each others.In many project we don’t need come all entities populate in one library or I want make modular projects. See my sample project models:<span style="font-size: 13.0pt; line-height: 115%; font-family: 'Calibri','sans-serif'; mso-ascii-theme-font: minor-latin; mso-fareast-font-family: Calibri; mso-fareast-theme-font: minor-latin; mso-hansi-theme-font: minor-latin; mso-bidi-font-family: Arial; mso-bidi-theme-font: minor-bidi; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA; mso-no-proof: yes;"><!--[if gte vml 1]><v:shapetype  id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t"  path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"><br />
<v:stroke joinstyle="miter"/><br />
<v:formulas><br />
<v:f eqn="if lineDrawn pixelLineWidth 0"/><br />
<v:f eqn="sum @0 1 0"/><br />
<v:f eqn="sum 0 0 @1"/><br />
<v:f eqn="prod @2 1 2"/><br />
<v:f eqn="prod @3 21600 pixelWidth"/><br />
<v:f eqn="prod @3 21600 pixelHeight"/><br />
<v:f eqn="sum @0 0 1"/><br />
<v:f eqn="prod @6 1 2"/><br />
<v:f eqn="prod @7 21600 pixelWidth"/><br />
<v:f eqn="sum @8 21600 0"/><br />
<v:f eqn="prod @7 21600 pixelHeight"/><br />
<v:f eqn="sum @10 21600 0"/><br />
</v:formulas><br />
<v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/><br />
<o:lock v:ext="edit" aspectratio="t"/><br />
</v:shapetype><v:shape id="Picture_x0020_1" o:spid="_x0000_i1025" type="#_x0000_t75"  style='width:206.25pt;height:324.75pt;visibility:visible;mso-wrap-style:square'><br />
<v:imagedata src="file:///C:\Users\ARASHK~1\AppData\Local\Temp\msohtmlclip1\01\clip_image001.png"   o:title=""/><br />
</v:shape><![endif]--><br />
<a style="text-align: left;" href="http://www.arash.im/wp-content/uploads/2011/11/1.png"><img class="size-medium wp-image-20 aligncenter" title="Domain model projects" src="http://www.arash.im/wp-content/uploads/2011/11/1-191x300.png" alt="Domain model projects" width="191" height="300" /></a></span></li>
</ul>
<div style="text-align: left;">
<pre class="brush: csharp">using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Arash.Core.Model
{
    [Table("EntityBase")]
    public abstract class EntityBase
    {
        // primitive
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EntityId
        {
            get;
            set;
        }

        [ForeignKey("EntityType")]
        public int EntityTypeId { get; set; }

        // navigation

        [ForeignKey("EntityTypeId")]
        public EntityType EntityType
        {
            get;
            set;
        }

        public EntityTypes EntityTypes
        {
            get
            {
                return (EntityTypes)EntityType.Id;
            }
            set
            {
                EntityTypeId = (int)EntityTypes;
            }
        }

        public virtual IEnumerable Tages { get; set; }
    }
}
}</pre>
<p>in sample project we have a three projects in Domain layer project: <strong>Core,  Membership, Restaurant. </strong>in each project we have a Model as a sub namespace that populate our models. These model folders have many entity classes. This entity classes are same object tables!Really?</p>
<p>After complete all models, we should create a DataAccess project and all model references to it:</p>
<p><a href="http://www.arash.im/wp-content/uploads/2011/11/2.png"><img class="aligncenter size-medium wp-image-21" title="Implement data access layer" src="http://www.arash.im/wp-content/uploads/2011/11/2-201x300.png" alt="Implement data access layer" width="201" height="300" /></a><br />
There is two concept for develop code first POCO classes in EF 4.1/2: develop a partial class and bind properties to field names in SQL table or put code first attributes top of mapped properties of a POCO class.I use attribute model without add any .edmx file to project</p>
<pre class="brush: csharp">using System.Data.Entity;
using Arash.Core.Model;
using Arash.Membership.Model;
using Arash.Restaurant.Model;
using Paradiso.Infrastructure.Data;

namespace Arash.DataAccess
{
    public class ArashDbContext : DbContext, IDbContext
    {
        public ArashDbContext() : base("arashConnectionString") { }

        public DbSet Members { get; set; }
        public DbSet Roles { get; set; }
        public DbSet Users { get; set; }
        public DbSet Jobs { get; set; }
        public DbSet EntityBases { get; set; }
        public DbSet EntityType { get; set; }
        public DbSet Tages { get; set; }
        public DbSet TagEntities { get; set; }
        public DbSet Coffeeshops { get; set; }

        public new IDbSet Set() where T : class
        {
            return base.Set();
        }

        public Database Query
        {
            get { return this.Database; }
        }

        public IDbSet GetDbSet() where T : class
        {
            return null;
        }

        public Database Db
        {
            get { return this.Database; }
        }
    }
}</pre>
<p>So We making a new structure of model for domain layer and  data access layer. We could add a class as data initialize object to Db. For this:</p>
<pre class="brush: csharp">sing System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using Arash.Core.Model;
using Arash.DataAccess;

namespace Arash.DataAccess
{
    public class ArashDbContextInitializer : DropCreateDatabaseAlways
    {
        protected override void Seed(ArashDbContext context)
        {
            #region entity type
            new List
            {
                new EntityType {
                    Name = "Coffeeshop"
                },
                new EntityType {
                    Name = "bar"
                }
            }.ForEach(m =&gt; context.EntityType.Add(m));
            #endregion

            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                var ex = e.EntityValidationErrors.ToList();
            }

            base.Seed(context);
        }
    }
}</pre>
<p><strong>Concludion:</strong></p>
<p>We used EF 4.1/2 with code first concept for separating model projects. With these approach we can add a new models without change old assemblies or old domain projects</p>
<p>Please read Part 2 for using these approach for using in Service(Bussiness) layer <img src='http://arash.im/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://arash.im/2011/11/using-entity-framework-features-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hello world!</title>
		<link>http://arash.im/2011/10/hello-world/</link>
		<comments>http://arash.im/2011/10/hello-world/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 13:10:56 +0000</pubDate>
		<dc:creator>arash</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.arash.im/?p=1</guid>
		<description><![CDATA[First post! This is a test code, for all coders void main(){ printf("hello world."); }]]></description>
				<content:encoded><![CDATA[<p>First post! This is a test code, for all coders <img src='http://arash.im/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="prettyprint cs linenums:1">
void main(){
printf("hello world.");
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://arash.im/2011/10/hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
