Wednesday, June 24, 2015

Web Application Projects versus Web Site Projects in Visual Studio


.NET Framework 4.5
In Visual Studio you can create web application projects or web site projects. You create or open a web application project by choosing New Project or Open Project in the Visual Studio File menu. You create or open a web site project by choosing New Web Site or Open Web Sitein the File menu. It’s best to choose the right type before you create a web project, because it can be time-consuming, difficult, and error-prone to convert from one type to the other.
NoteNote
For new development, we recommend that you choose web application projects. This topic explains that web site projects have some advantages, but many developers who choose web site projects eventually find that the disadvantages outweigh any perceived advantages. In addition, as new ASP.NET features are developed, they won’t always be made available for web site projects. For example, the next Visual Studio release after Visual Studio 2012 will have new tooling for creating web projects, and this new tooling will work only with web application projects. For more information, see Creating an ASP.NET Web Project in Visual Studio 2013.
This topic contains the following sections:

Scenarios

Scenarios in which web application projects are the preferred choice include the following:
  • You want to be able to use the Edit and Continue feature of the Visual Studio debugger.
  • You want to run unit tests on code that is in the class files that are associated with ASP.NET pages.
  • You want to refer to the classes that are associated with pages and user controls from standalone classes.
  • You want to establish project dependencies between multiple web projects.
  • You want the compiler to create a single assembly for the entire site.
  • You want control over the assembly name and version number that is generated for the site.
  • You want to use MSBuild or Team Build to compile the project. For example, you might want to add prebuild and postbuild steps.
  • You want to avoid putting source code on a production server.
Scenarios in which Web site projects are the preferred choice include the following:
  • You want to include both C# and Visual Basic code in a single web project. (By default, a web application is compiled based on language settings in the project file. Exceptions can be made, but it is relatively difficult.)
  • You want to open the production site in Visual Studio and update it in real time by using FTP.
  • You do not want to have to explicitly compile the project in order to deploy it.
  • If you do precompile the site, you want the compiler to create multiple assemblies for the site, which can include one assembly per page or user control, or one or more assemblies per folder.
  • You want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.
  • If you precompile the site, you want to be able to update individual ASP.NET web pages (.aspx files) without having to recompile the entire site.
  • You like to keep your source code on the production server because it can serve as an additional backup copy.

Summary of Differences

The following table summarizes the main differences.
Area
Web application projects
Web site projects
Project file structure
A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.
There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
Compilation
  • You explicitly compile the source code on the computer that is used for development or source control.
  • By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
  • The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.
    You can precompile the site (compile in advance on a development computer or on the server).
  • By default, compilation produces multiple assemblies.
Namespaces
Explicit namespaces are added to pages, controls, and classes by default.
Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.
Deployment
  • You copy the assembly to a server. The assembly is produced by compiling the application.
  • Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
  • You copy the application source files to a computer that has IIS installed on it.
  • If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server.
  • Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.

Project File Structure

Web application projects use Visual Studio project files (.csproj or .vbproj) to keep track of information about the project. This makes it possible to specify which files are included in or excluded from the project, and therefore which files are compiled during a build.
For web site projects, all files in a folder structure are automatically considered to be included in the web site. If you want to exclude something from compilation, you must remove the file from the web site project folder or change its file-name extension to an extension that is not compiled and is not served by IIS.
An advantage of using project files in web application projects is the following:
  • It is easy to temporarily remove files from the site but still make sure that you do not lose track of them, because they remain in the folder structure. For example, if a page is not ready to be deployed, you can temporarily exclude it from the build without deleting it from the folder structure. You can deploy the compiled assembly, and then include the file in the project again. This is especially important if you are working with a source control repository.
An advantage of using folder structure without project files in Web site projects is the following:
  • You do not have to manage the project's structure exclusively in Visual Studio. For example, you can copy files into the project or delete them from the project by using File Explorer.

Compilation

For web application projects, you typically build the project in Visual Studio or by using the ASP.NET batch compiler on a computer that is not the production IIS server. All code-behind class files and standalone class files in the project are compiled into a single assembly, which is then put in the web application project's Bin folder. (The .aspx and .ascx files are compiled dynamically in a manner similar to what is done for web site projects.)
For web site projects, you do not have to manually compile the project. web site projects are typically compiled dynamically by ASP.NET (on both the development computer and the production IIS server). You can choose between batch compilation mode, which typically produces one assembly per folder, and fixed compilation mode, which typically produces one assembly for each page or user control.
Advantages of the compilation model for web application projects include the following:
  • You can use MSBuild to create a custom batch-compilation process.
  • It is easy to specify assembly attributes such as name and version.
  • Compiling in advance makes sure that users do not have to wait while the site compiles on the production server. (If the site is very large, dynamic compilation of a web site project might take a noticeable amount of time. Dynamic compilation occurs when a request for a site resource is received after an update to the site, and the request that triggers compilation might be delayed while the required resources are compiled. If the delay is unacceptable, you can precompile the site. However, then some of the advantages of dynamic compilation are lost.)
  • You have complete control over where you put code files in the project folder structure, and how you how classes in the project refer to each other. (Dynamic compilation requires that the source code for any classes that are used throughout the site must be in the App_Code folder. You cannot refer to a page or user control class from a class in App_Code.)
Advantages of the compilation model for Web site projects include the following:
  • You can test specific pages regardless of the state of other pages. This is because running an individual page does not require that the whole site compile successfully, only the page and any components it depends on, such as code in the App_Code folder or the Global.asax file. (In a web application project, if there are compilation errors anywhere in the site, you cannot create the assembly and therefore cannot test even the pieces of the site that compile.)
  • It is easy to update a Web site in production. You can update individual source code files on the production server without having to explicitly recompile the site. You can update individual files that are ready for deployment even if other files are not ready due to compile errors. You can also open the Web site on the production IIS server directly in Visual Studio and update the Web site in real time.
  • Precompiling to multiple assemblies can have a performance advantage in some scenarios. A typical example is a site that has many pages with lots of code written for them. Most of the pages are rarely requested and only some are used frequently. If you compile a site like this into multiple assemblies, the production server can load only the assemblies that are required for the current requests. If a page is not requested, its corresponding assembly is not loaded.
NoteNote
There is no difference in performance between a web site project and a web application project. The only significant exceptions are the ones that have already been noted, and as a practical matter they apply only to very large sites. The first request to the web site might require the site to be compiled, which can result in a delay. And if the web site is running on an IIS server that is short on memory, including the entire site in a single assembly might use more memory than would be required for multiple assemblies.

Deployment

You typically copy all of your source code to the web server when you deploy a web site project. In a web application project, source code is compiled into an assembly (a .dll file), and that is what has to be on the web server.
An advantage of web application projects is that you can avoid deploying source code to the IIS server. In some scenarios, such as shared hosting environments, you might be concerned about unauthorized access to source code on the IIS server. For a web site project, you can avoid this risk by precompiling on a development computer and deploying the generated assemblies instead of the source code. However, in that case you lose some of the benefits of easy site updates.
An advantage of web site projects is that when you make a small change to a web site, you do not have to redeploy the whole site. Instead, you can copy just the changed file or files to the production IIS server. You can also edit files directly on the production server. Because a web application project's code files are compiled into a single assembly file, you must deploy the whole site even for small changes, unless the only change is to an .aspx or .ascx file.
Deployment often involves other tasks in addition to copying assemblies or code to a server. For example, database scripts might have to run in production, and connection strings in the Web.config file might have to be changed for a production server. Visual Studio provides tools such as one-click publish that work with web application projects to automate many of these tasks. These tools are available for both web application projects and web site projects. For more information, see Web Deployment Overview for Visual Studio and ASP.NET.

Difference between abstract class and interface

About Abstract Class :

Abstract class is a class that contain complete and abstract (incomplete) both type of member and it can not be instantiated, Abstract classes are one of the essential behaviors provided by dotnet.

Interface contains only definition / signature of functionality, and if we have some common functionality as well as common signature then there is a need of abstract class so through abstract class we can provide behavior as well as functionality both in the same time, developer inheriting abstract class can use this functionality and need to fill only in the blank.

About Interface :

Interface is a type which contains only the signatures of methods, delegates or events, it has no implementation, Implementation of the methods is done by the class that which implements the interface.

Interface is a contract that defines the signature of the functionality. So if a class is implementing a interface it says to the outer world, that it provides specific behavior. Example if a class is implementing ‘Idisposable’interface that means it has a functionality to release unmanaged resources.

OOPs interface vs abstract class

InterfaceAbstract class
Interface support multiple inheritanceAbstract class does not support multiple inheritance
Interface does'n Contains Data MemberAbstract class contains Data Member
Interface does'n contains CunstructorsAbstract class contains Cunstructors
An interface Contains only incomplete member (signature of member)An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Member of interface can not be StaticOnly Complete Member of abstract class can be Static

To Know More about Interface and Abstract Class Click Bellow :-

Monday, June 22, 2015

Lambda Expressions Continue............

LAMBDA CONTINUES
LINQ is a cool feature in C# 3.0. Most of the developers are struggling for the syntax and examples. Here I have collected various examples for each operator in LINQ and the equivalent Lambda Expressions. 

Where

IEnumerable<Product> x = products.Where(p => p.UnitPrice >= 10);
IEnumerable<Product> x =
    from p in products
    where p.UnitPrice >= 10
    select p;

Select
IEnumerable<string> productNames = products.Select(p => p.Name);
IEnumerable<string> productNames = from p in products select p.Name;
var namesAndPrices =
    products.
    Where(p => p.UnitPrice >= 10).
    Select(p => new { p.Name, p.UnitPrice }).
    ToList();
IEnumerable<int> indices =
    products.
    Select((product, index) => new { product, index }).
    Where(x => x.product.UnitPrice >= 10).
    Select(x => x.index);

SelectMany

IEnumerable<Order> orders =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders);
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Select(o => new { o.Customer.Name, o.OrderID });
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders, (c,o) => new { c, o }).
    Where(co => co.o.OrderDate.Year == 2005).
    Select(co => new { co.c.Name, co.o.OrderID });
var namesAndOrderIDs =
    from c in customers
    where c.Country == "Denmark"
    from o in c.Orders
    where o.OrderDate.Year == 2005
    select new { c.Name, o.OrderID };

Take

IEnumerable<Product> MostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable<Product> AllButMostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Skip(10);

TakeWhile SkipWhile
s.TakeWhile(p) s.SkipWhile(p)
Join

var custOrders =
    customers.
    Join(orders, c => c.CustomerID, o => o.CustomerID,
        (c, o) => new { c.Name, o.OrderDate, o.Total }
    );
var custOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID
    select new { c.Name, o.OrderDate, o.Total };

GroupJoin

var custTotalOrders =
    customers.
    GroupJoin(orders, c => c.CustomerID, o => o.CustomerID,
        (c, co) => new { c.Name, TotalOrders = co.Sum(o => o.Total) }
    );
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    select new { c.Name, TotalOrders = co.Sum(o => o.Total) };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID
    select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    from o in co
    select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    from o in co.DefaultIfEmpty(emptyOrder)
    select new { c.Name, o.OrderDate, o.Total };
Concat

IEnumerable<string> locations =
    customers.Select(c => c.City).
    Concat(customers.Select(c => c.Region)).
    Concat(customers.Select(c => c.Country)).
    Distinct();
IEnumerable<string> locations =
    new[] {
        customers.Select(c => c.City),
        customers.Select(c => c.Region),
        customers.Select(c => c.Country),
    }.
    SelectMany(s => s).
    Distinct();

OrderBy / ThenBy

IEnumerable<Product> orderedProducts1 =
    products.
    OrderBy(p => p.Category).
    ThenByDescending(p => p.UnitPrice).
    ThenBy(p => p.Name);
IEnumerable<Product> orderedProducts1 =
    from p in products
    orderby p.Category, p.UnitPrice descending, p.Name
    select p;
IEnumerable<Product> orderedProducts2 =
    products.
    Where(p => p.Category == "Beverages").
    OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
IEnumerable<string> orderedProductNames =
    products.
    Where(p => p.Category == "Beverages").
    Select(p => p.Name).
    OrderBy(x => x);

GroupBy

IEnumerable<IGrouping<string, Product>> productsByCategory =
    products.GroupBy(p => p.Category);
IEnumerable<IGrouping<string, string>> productNamesByCategory =
    products.GroupBy(p => p.Category, p => p.Name);

Distinct

IEnumerable<string> productCategories =
    products.Select(p => p.Category).Distinct();

AsEnumerable

Table<Customer> custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));

ToArray

string[] customerCountries =
    customers.Select(c => c.Country).Distinct().ToArray();

ToList

List<Customer> customersWithOrdersIn2005 =
    customers.
    Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
    ToList();

ToDictionary

Dictionary<int,Order> orders =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    ToDictionary(o => o.OrderID);
Dictionary<string,decimal> categoryMaxPrice =
    products.
    GroupBy(p => p.Category).
    ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

ToLookup

Lookup<string,Product> productsByCategory =
    products.ToLookup(p => p.Category);
IEnumerable<Product> beverages = productsByCategory["Beverage"];

OfType

List<Person> persons = GetListOfPersons();
IEnumerable<Employee> employees = persons.OfType<Employee>();

Cast

      ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =
    objects.
    Cast<Order>().
    Where(o => o.OrderDate.Year == 2005);
ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =
    from Order o in objects
    where o.OrderDate.Year == 2005
    select o;

First

string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone == phone);

Single

int id = 12345;
Customer c = customers.Single(c => c.CustomerID == id);

ElementAt

Product thirdMostExpensive =
    products.OrderByDescending(p => p.UnitPrice).ElementAt(2);

Range

int[] squares = Enumerable.Range(0, 100).Select(x => x * x).ToArray();
Repeat

long[] x = Enumerable.Repeat(-1L, 256).ToArray();

Empty

IEnumerable<Customer> noCustomers = Enumerable.Empty<Customer>();

Any

bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);

All

IEnumerable<string> fullyStockedCategories =
    products.
    GroupBy(p => p.Category).
    Where(g => g.Group.All(p => p.UnitsInStock > 0)).
    Select(g => g.Key);

Count

int count = customers.Count(c => c.City == "London");

Sum

int year = 2005;
var namesAndTotals =
    customers.
    Select(c => new {
        c.Name,
        TotalOrders =
            c.Orders.
            Where(o => o.OrderDate.Year == year).
            Sum(o => o.Total)
    });

Min

var minPriceByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        MinPrice = g.Group.Min(p => p.UnitPrice)
    });

Max

decimal largestOrder =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Max(o => o.Total);

Average

var averageOrderTotals =
    customers.
    Select(c => new {
        c.Name,
        AverageOrderTotal = c.Orders.Average(o => o.Total)
    });

Aggregate
var longestNamesByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        LongestName =
            g.Group.
            Select(p => p.Name).
            
Aggregate((s, t) => t.Length > s.Length ? t : s)
    });

Understand Lambda Expressions in 3 minutes

Lambda expressions short tutorial.
  1. What is a Lambda Expression?
  2. A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
  3. Why do we need lambda expressions? (Why would we need to write a method without a name?)
  4. Convenience. It's a shorthand that allows you to write a method in the same place you are going to use it. Especially useful in places where a method is being used only once, and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class.
    Benefits:
    1. Reduced typing. No need to specify the name of the function, its return type, and its access modifier. 
    2. When reading the code you don't need to look elsewhere for the method's definition. 
    Lambda expressions should be short. A complex definition makes the calling code difficult to read.
  5. How do we define a lambda expression? 
  6. Lambda basic definition: Parameters => Executed code.

Simple example

n => n % 2 == 1 
  • n is the input parameter
  • n % 2 == 1 is the expression
You can read n => n % 2 == 1 like: "input parameter named n goes to anonymous function which returns true if the input is odd".
Same example (now execute the lambda):
List<int> numbers = new List<int>{11,37,52};
List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();
//Now oddNumbers is equal to 11 and 37
That's all, now you know the basics of Lambda Expressions.

Thursday, June 18, 2015

Dot net tricks

Difference between LINQ to SQL and Entity Framework

Difference between LINQ to SQL and Entity Framework

LINQ to SQL allow you to query and modify SQL Server database by using LINQ syntax. Entity framework is a great ORM shipped by Microsoft which allow you to query and modify RDBMS like SQL Server, Oracle, DB2 and MySQL etc. by using LINQ syntax. Today, EF is widely used by each and every .NET application to query to database. The difference between LINQ to SQL and EF is given below.
LINQ to SQL
Entity Framework
It only works with SQL Server Database.
It can works with various databases like Oracle, DB2, MYSQL, SQL Server etc.
It generates a .dbml to maintain the relation
It generates an .edmx files initially. The relation is maintained using 3 different files .csdl, .msl and .ssdl
It has not support for complex type.
It has support for complex type.
It cannot generate database from model.
It can generate database from model.
It allows only one to one mapping between the entity classes and the relational tables /views.
It allows one-to-one, one-to-many & many-to-many mappings between the Entity classes and the relational tables /views
It allows you to query data using DataContext.
It allows you to query data using EntitySQL, ObjectContext, DbContext.
It provides a tightly coupled approach.
It provides a loosely coupled approach. Since its code first approach allow you to use Dependency Injection pattern which make it loosely coupled .
It can be used for rapid application development only with SQL Server.
It can be used for rapid application development with RDBMS like SQL Server, Oracle, DB2 and MySQL etc.

Using T4 templates in Entity framework

T4 stands for Text template transformation toolkit which is a template-based code generation engine built into Visual Studio. It is available in Visual studio from Visual Studio 2008 and higher version of Visual Studio. T4 engine allows you to generate C#, T-SQL, XML or any other text files by using ASP.NET – ASPX template like syntax. T4 template has .tt extension.
For example, TextTemplate.tt T4 template has the following code:
  1. <#@ template language="C#" #>
  2. <#@ assembly name="System.Core" #>
  3. <#@ import namespace="System.Text" #>
  4. <#@ output extension=".txt" #>
  5. <# Write("T4 templates with EF!"); #>
The T4 template processor will transform above T4 template code into a text file having extension .txt by executing the code and processing directives inside.
  1. T4 templates with EF!

T4 templates with Entity framework

T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.
To use one of these templates, right-click on the design surface of an .edmx file and select the "Add Code Generation Item" command as given below-
Selecting the command will launch a dialog box allowing you to select one of the installed code-generation items, or to search for new items online.
Selected template will generate the C# or VB code files i.e. entity and context classes as given below.
What do you think?
I hope you will enjoy the T4 template while working with EF. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.