ASP.NET 4.0 Hosting & ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4.5 Hosting, ASP.NET 4.0 Hosting and .NET 4.5 Framework and its Capabilities

ASP.NET 4 Hosting :: Html Encoded Expressions in ASP.NET 4.0

clock November 17, 2011 06:09 by author darwin

Introduction

We all know <%=expression%> features in asp.net. We can print any string on page from there. Mostly we are using them in asp.net mvc. Now we have one new features with asp.net 4.0 that we have HTML Encoded Expressions and this prevent Cross scripting attack as we are html encoding them.

ASP.NET 4.0 introduces a new expression syntax <%: expression %> which automatically convert string into html encoded. Let’s take an example for that.
I have just created an hello word protected method which will return a simple string which contains characters that needed to be HTML Encoded. Below is code for that.


protected static string HelloWorld()
{
   return "Hello World!!! returns from function()!!!>>>>>>>>>>>>>>>>>";
}

Now let’s use the that hello world in our page html like below. I am going to use both expression to give you exact difference.

<form id="form1" runat="server">
<div>
   <strong><%: HelloWorld()%></strong>
</div>
<div>
   <strong><%= HelloWorld()%></strong>
</div>
</form>

Now let’s run the application and you can see in browser both look similar. 



But when look into page source html in browser like below you can clearly see one is HTML Encoded and another one is not.



Cool, right?? Happy Programming.



ASP.NET Hosting :: How to Display Images with ASP.NET CheckBoxList Control

clock November 3, 2011 06:49 by author darwin

In this tips I will discuss how you can customize the rendering of ASP.NET CheckBoxList control with images.  Let’s consider a scenarios where you want to show some status images with every checkbox with in a CheckBoxList. Many developers use table with checkbox and images in different cell to display Images with checkbox.  But, we can easily achieve the same using CheckBoxList control itself.

Let’s  consider you have items in a CheckBoxList control.



If you run your web application with above CheckBoxList items, you will get below output



Now you want images instead of the text with the list of checkbox controls. If you look in to the code, as of now, nothing has been written with in NewCheckList_DataBound method.  To enable the adding icon  we have to override the content of items which is being  generating during  data bound. Below is a simple code which will enable to add  icons for every CheckBo  item in the CheckBoxList



What we did is just iterating through each element and override the  item text as per our requirement . Once run, you will get the output as below.



If you want avoid the text, you just need change the override content of item.Text.



So not only the icon, you can add any HTML Content as per requirement.



ASP.NET 4.0 Hosting :: SOLVING an error message: “Unrecognized attribute targetFramework”

clock September 22, 2011 07:32 by author Administrator

I recently upgraded from Visual Web Developer 2008 to Visual Web Developer 2010 and have run into an issue, I started seeing a configuration error. In two cases I had been working on web applications in Visual Web developer 2010.


Case 1 appeared after I had opened an existing application and when prompted, do I want to configure the site for use with ASP.NET 4.0, I must have said yes.

Case 2 came when I created a new application and my system is setup to use Framework ASP.NET 4.0

In both situations I got the following error <compilation debug="true" targetFramework="4.0" /> pointing to my web.config file. I like working in Visual Web Developer 2010, but my hosting server is not yet setup for .Net Framework 4.0, so I needed to find out how to down-grade from 4.0 to 3.5 framework.



The following is what I did to change the target Framework from ASP.NET 4.0 to ASP.NET 3.5.

1) Ensure IIS and the ASP.NET properties are configured for Framework 2.0. Note: Framework 3.5 will not show up in the list of installed options due to the fact that framework 3.5 is an extension of 2.0 and not a stand alone release


 2) Configure you web application to use target Framework 4.0 by right clicking your website in the solution explorer >> Property Pages >> Build >> Change "Target Framework" to .NET Framework 3.5.

T



ASP.NET 4 Hosting :: The Difference between Response.Redirect and Response.RedirectPermanent

clock September 20, 2011 07:46 by author Administrator

In ASP.NET 4.0 there are new features that enable developer to make SEO friendly websites very easily. And if you google out, you will find plenty of article which explain this feature. But I am more interested in Response.RedirectPermanent. As the name suggest it is used to redirect permanently moved resources to new location. And most of all articles on the net just explain this with some example. But how can we visualize that whether resource is redirected permanently or not. So here is the answer for that. I have used FireBug to examine the same


Whenever we redirect with Response.Redirect, we can see following activity in FireBug console



As we can see that page which issues Response.Redirect its response status code 302(Found) which means requested url(default.aspx) is found but it is temporarily moved to about.aspx. More information on HTTP status code can be found here.

Now whenever we redirect with Response.RedirectPermanent, we can see following activity in FireBug console



As we can see that page which issues Response.RedirectPermanent its response status code 301(Moved Permanently) which means requested url(default.aspx) is moved Permanently to about.aspx. 301 status code is used by search engine crawler to update search index to new moved information.

I hope information provided here would be more helpful to distinguish between Response.Redirect and Response.RedirectPermanent



ASP.NET 4 Hosting :: Main Differences of Custom Control and User Control

clock August 23, 2011 07:57 by author Administrator

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:

UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.

Limitation of UserControl :

1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.

2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.

3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.

Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.

Note: Please don’t create a new custom control just to change the UI appearance as you can do this with any control available using custom Template

Limitation :

1. You have to define each behaviour for your control using Code. So it is hard way of achieving a behaviour.

2. Generic style is needed to be defined with your custom control to ensure that your control has a default look and feel.

Hence, based on your own requirement, if you are looking for a new behaviour which is different from existing userinterfaces available with WPF, you go for a Custom Control. A customControl can be styled and templated and best suited for a situation when you are building a Control Library.

On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don’t need to use it as a Control Library.

I hope this gives you a brief idea on the differences between the two.

Happy Coding.



ASP.NET 4 Hosting :: How to Register HTTP Module at Runtime without Editing web.config?

clock July 4, 2011 08:35 by author Administrator

The ASP.NET pipeline allows HTTP modules to be plugged-in to a request and intercept or modify each individual request. Modules can be used for processes like caching, authentication etc. However a basic requirement for an HTTP module to function, is that it must be registered in your config file. This leads to editing the Web.Config whenever you have to add/remove modules. I hate fudging with my config file too often!

Not known to many developers, ASP.NET 4.0 provides the PreApplicationStartMethodAttribute which allows you to run code even before any app_start event gets fired or any dynamic compilation occurs (App_code).

So how do I register an HTTP Module at Runtime using PreApplicationStartMethodAttribute and DynamicModuleUtility.RegisterModule?

It’s a simple 3 process step!

Step 1: Implement your Module. In the code shown below, we are implementing the IModule interface and subscribing to the BeginRequest event of the HttpApplication object. The OnBeginRequest method hooks up to the BeginRequest event.



Step 2: Register the Module dynamically using the DynamicModuleUtility.RegisterModule method. Write this code in the same class you created above



Step 3: The final step is to use the PreApplicationStartMethod attribute. Just add this  attribute at the assembly level in the AssemblyInfo file or as shown below:

There you go! You have just registered an HTTP module into the ASP.NET pipeline without making any changes to web.config file.

 

 

 

 



ASP.NET 4.0 Hosting :: ASP.NET GridView UI Tips and Tricks by using jQuery

clock September 27, 2010 14:52 by author Administrator

This article demonstrates how to create simple UI effects in an ASP.NET GridView control using jQuery. These tips have been tested in IE 7 and Firefox 3.

Set up an ASP.NET GridView as you usually do, binding it to a datasource. For demonstration purposes, here’s some sample markup where we are using the Northwind database and a GridView bound to the SQLDataSource to pull data from the database.

<form id="form1" runat="server">

<div>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">

    </asp:SqlDataSource>   

    <br />          

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"

        DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >

        <Columns>                          

            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />

            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />

            <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />

            <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />

            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />

        </Columns>

    </asp:GridView>

</div>

</form>

The <connectionStrings> element in the web.config will look similar to the following:

      <connectionStrings>

            <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>

      </connectionStrings>

Note: In most of the tips shown here, we are using a complex jQuery row ‘filter’ suggested by Karl Swedberg to a user in a jQuery forum. This filter is required due to the fact that a GridView does not render (accessibility tags) a <thead> and a <tfoot> by default. For the header, the GridView generates <th>’s inside <tr>. Similarly for the footer, the GridView generates a <table> inside a <tr> and so on. Hence it is required to use additional filters to exclude header and footer rows while adding UI effects on the GridView. These tips have been tried out on a GridView where paging is not enabled. When the paging is enabled, the pager however gets highlighted. We are still working on a solution to prevent the UI effects from being applied on the pager. We will update this article, once we find a solution. If you have a solution that works cross browser, please share it with us.

The link to download the code for all these samples can be found at the end of this article. Let’s see some tips.


1. Highlight an ASP.NET GridView row by clicking on it     

This tip lets you highlight a row when you click anywhere on the row. Clicking back on a highlighted row, removes the highlight.

<head id="Head1" runat="server">

<title>Highlight Row on Click</title>

<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function() {

        $("tr").filter(function() {

            return $('td', this).length && !$('table', this).length

        }).click(function() {

            $(this).toggleClass('currRow');

        });

    });

</script>

<style type="text/css">

    .currRow

    {

        background-color:Gray;

        cursor:pointer;

    }   

</style>

</head>

After applying the filter on the rows (to prevent the user from highlighting the Header and Footer row), we use the toggleClass to highlight/remove highlight on the row.

Output:

2. Remove/Hide the Highlighted rows of an ASP.NET GridView

If you want to remove/hide the highlighted rows from the GridView, then here’s how to do so. We have added a HTML button control (Button1) to the form

<input id="Button1" type="button" value="Remove Rows" />

The jQuery is as shown below:

<head id="Head1" runat="server">

    <title>Hide Highlighted Rows>/title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("tr").filter(function() {

                return $('td', this).length && !$('table', this).length

            }).click(function() {

                $(this).toggleClass('currRow');

            });

            $("#Button1").click(function() {               

                var hideRows = $("tr").hasClass("currRow");

                if (hideRows == true) {                   

                    $("tr.currRow").remove();

                }

            });

        });

    </script>

    <style type="text/css">

        .currRow

        {

            background-color:Gray;

            cursor:pointer;

        }   

    </style>

</head>

Here the user first highlights the rows and then clicks on the ‘Remove Rows’ button to remove the highlighted rows

3. Remove/Hide ASP.NET GridView Rows on Mouse Click     

In our previous sample, we were following a two step process of first highlighting multiple rows and then removing them. Let’s say if we want to remove the rows as the user clicks on them, then follow this approach:

    <script type="text/javascript">

        $(document).ready(function() {

                $("tr").filter(function() {

                    return $('td', this).length && !$('table', this).length

                }).click(function() {

                    $(this).remove();

                });

        });       

    </script>

4. Highlight an ASP.NET GridView row on Mouse Hover     

In case you do not want to define a separate style for the row and want to highlight a row on mouse over (instead of the click), follow this tip:

<head id="Head1" runat="server">

    <title>Highlight Row on Hover</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("tr").filter(function() {

                return $('td', this).length && !$('table', this).length

            }).css({ background: "ffffff" }).hover(

                function() { $(this).css({ background: "#C1DAD7" }); },

                function() { $(this).css({ background: "#ffffff" }); }

                );

        });

    </script>

</head>

Output:

5. Drag and Drop Rows of an ASP.NET GridView

 

 

 

 

This tip comes very handy when you are presenting a set of data in a GridView and want to rearrange rows at runtime. We are using the Table Drag and Drop Plugin for this example and it’s as simple as calling tableDnD() on the table. This plugin enables drag/drop on a table.

<head runat="server">

    <title>Drag Drop Rows</title>

    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

    <script src="Scripts/jquery.tablednd_0_5.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            $("#GridView1").tableDnD();

        });

</script>

</head>

Output:

Before Drag

After Drop - dragging row with Customer ID ‘ANATR’ below ‘BLONP’

That’s it for now. We saw some UI tips that can be applied to an ASP.NET GridView using jQuery. Stay tuned to see some more in the forthcoming articles. We are also planning to write an article to store these UI changes when the user paginates through the Grid or a postback occurs

 

 

 

 



ASP.NET MVC Hosting :: ASP.NET MVC Model Binder for Repositories

clock September 21, 2010 08:11 by author Administrator

How do you take the values posted by an HTML form and turn them into a populated domain entity? One popular technique is to bind the POST values to a view-model and then map the view-model values to an entity. Since your action method’s argument is the view-model, it allows you to decide in the controller code if the view-model is a new entity or an existing one that should be retrieved from the database. If the view-model represents a new entity you can directly create the entity from the view-model values and then call your repository in order to save it.  In the update case, you can directly call your repository to get a specific entity and then update the entity from the values in the view-model

However, this method is somewhat tedious for simple cases. Is a view-model always necessary? Wouldn’t it be simpler to have a model binder that simply created the entity for you directly? Here’s our attempt at such a binder:

public class EntityModelBinder : DefaultModelBinder, IAcceptsAttribute
{   
readonly IRepositoryResolver repositoryResolver;
    EntityBindAttribute declaringAttribute;

    public EntityModelBinder(IRepositoryResolver repositoryResolver)
    {
        this.repositoryResolver = repositoryResolver;
    }

    protected override object CreateModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext,
        Type modelType)
    {
        if (modelType.IsEntity() && FetchFromRepository)
        {
            var id = GetIdFromValueProvider(bindingContext.ValueProvider, modelType);
            if (id != 0)
            {
                var repository = repositoryResolver.GetRepository(modelType);
                object entity;
                try
                {
                    entity = repository.GetById(id);
                }
                finally
                {
                    repositoryResolver.Release(repository);
                }
                return entity;
            }
        }

        // Fall back to default model creation if the target is not an existing entity
        return base.CreateModel(controllerContext, bindingContext,
odelType);
    }

    private static int GetIdFromValueProvider(IValueProvider valueProvider, Type modelType)
    {
        var result = valueProvider.GetValue(modelType.GetPrimaryKey().Name);
        return (result == null) ? 0 : (int)result.ConvertTo(typeof(Int32));
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = base.BindModel(controllerContext, bindingContext);
        ValidateEntity(bindingContext, controllerContext, model);
        return model;
    }

    protected virtual void ValidateEntity(
        ModelBindingContext bindingContext,
        ControllerContext controllerContext,
        object entity)
    {
        // override to provide additional validation.
    }

    private bool FetchFromRepository
    {
        get
        {
            // by default we always fetch any model that implements IEntity
            return declaringAttribute == null ? true :
declaringAttribute.Fetch;
        }
    }

    public virtual void Accept(Attribute attribute)
    {
        declaringAttribute = (EntityBindAttribute)attribute;   
    }

    // For unit tests

    public void SetModelBinderDictionary(ModelBinderDictionary modelBinderDictionary)
    {
        Binders = modelBinderDictionary;
    }
}


We have simply inherited ASP.NET MVC’s DefaultModelBinder and overriden the CreateModel method. This allows us to check if the type being bound is one of our entities and then grabs its repository and gets it from the database if it is.

Now, We are most definitely not doing correct Domain Driven Development here despite our use of terms like ‘entity’ and ‘repository’. It’s generally frowned on to have table-row like settable properties and generic repositories. If you want to do DDD, you are much better off only binding view-models to your views

 



Web Deployment with Visual Studio 2010 and IIS7

clock September 6, 2010 11:03 by author Administrator

Today, deploying a web application is not as easy as it should be. Whether you are deploying your web to a shared hosting environment and paying monthly to maintain it OR whether you have a web server/s managed by your enterprise, there are a lot of manual steps involved in getting your application from point A to point B.

If you are deploying your web application to a shared hoster then today you have to use technologies like FTP which take a long time to get your web content to the hosted server. After deploying your content you have to manually go to hoster control panel and install your database by running sql scripts and configure various IIS settings like marking a folder as an application to isolate it from the rest of the application.

If you are in an enterprise environment and you want to get a web application deployed you have to systematically document each step that your server admins and DBAs have to perform. In most circumstances you also have to ask your admins to modify the web.config files and go to IIS Manager and configure your settings apart from deploying your web content. Your DBA has to do the necessary steps of running the sql scripts in the right order to get your DB up and running. Such installations many a times take hours to complete.

With Visual Studio 2010 and IIS Web Deployment Tool (MsDeploy.exe / Web Deploy) we are introducing a set of technologies which can seamlessly deploy your applications taking care of the problems stated above. Microsoft Web Deployment Tool is a free download available on the web… You can download MSDeploy from below location:

http://blogs.iis.net/msdeploy/archive/2008/10/29/the-web-deployment-tool-beta-2-is-now-available.aspx

Do note that installing Visual Studio 2010 will automatically install MSDeploy for you. Visual Studio 2010 CTP can be downloaded from below location:

http://www.asp.net/vwd/

Web Deployment feature sets in VS 2010 can be broken down into following major areas:

1. Web Packaging - VS 2010 uses MSDeploy to create a .zip file for your application which we call as a web package. This file contains meta data + the below artifacts

· All of your IIS Settings (e.g. application pools, error pages etc)
· Web Content (e.g. .aspx, .ascx, .js, images etc)
· SQL Server DB
· Various other artifacts like Security Certs, GAC Components, Registry etc

A web package can then be taken to any server and installed either via IIS Manager UI Wizard or even via command line or API for automated deployment scenarios.

2. Web.Config Transformation – With VS 2010 web deployment we are introducing XML Document Transform (XDT) which will allow you to transform your development time web.config file to production/deployment time web.config file. The transformation is controlled by web.config TRANSFORM files named web.debug.config, web.release.config etc. The naming of these files is tied to the MSBuild configuration you are trying to deploy. The transform file will need just the changes that you really want to make to your deployed web.config… You can control the type of changes by instructing the XDT engine using simple and easy to understand syntax…

e.g. the below syntax in web.release.config will replace the connectionString section with new values in the web.config file which is produced for deployment of your release configuration.

3. DB Deployment – VS 2010 allows you to deploy your application along with all of its dependencies including database dependencies on SQL Server. Just by providing the connection string of your source database VS10 will automatically script its data/schema and package it for deployment. VS will also allow you to provide custom .sql scripts and also sequence them correctly to run on the server. Once your DB is packaged along with your IIS Settings and web content you can choose to deploy it to any server by providing the connection string at the install time.

4. 1-Click Publish - VS 2010 will allow you to not only package your web applications with all of its dependencies but also use IIS remote management service to publish the application to remote server. VS 10 will now allow you to create a publish profile of your hoster account or of various testing servers and save your credentials securely so that going forward you can deploy to any of these publish profiles with just one click using Web One Click toolbar. With VS 10 you will also be able to publish using MsBuild command line so that you can configure your team build environment to include publishing in continuous integration model

 



ASP.NET 4 Hosting :: Working with a Database using Model-First Development Technique

clock March 2, 2010 11:15 by author Administrator

Introduction


The upcoming release of Visual Studio 2010 will contain the Entity Framework 4 which is Microsoft's second release of the Entity Framework.  The new and improved EF4 contains a boat load of new features which many developers have suggested after using version 1.  It also comes closer to the features offered in other Object-Relational Mapping tools such as NHibernate.  Object-Relational Mapping tools are used to eliminate much of the tedious code needed to have an application persist and retrieve data from a database.  The developer uses a visual interface to build classes that map to tables, relationships, stored procedures, and other objects in a database.  One of the great new features of EF4 is the ability to create an ADO.NET Entity Data Model and then build the database from the model.  Previously the developer needed to create the database first and then generate the model.  EF4 still supports reverse engineering a database but being able to use Visual Studio to design a database based off of an object model is a big step forward with this tool.

Today, we are going to discuss a way to create a database using Model-First Development Technique. ASPHostCentral.com, as the premier ASP.NET and Windows Hosting provider, proudly presents this article to anyone and we believe it will help many ASP.NET communities; especially to those who are using ASP.NET 4 Framework. In case you are looking for ASP.NET 4 Hosting, you can always consider ASPHostCentral.com and you can start from our lowest Standard Plan @$4.99/month to host your WCF-service site.

The goal of this article is to show you how to create an ADO.NET Entity Data Model using the Entity Framework 4.  This article uses Visual Studio 2010 Beta 2 so some of the steps may change once the final version is released to production.  Future articles will build upon this application to dive deeper into the EF4 to demonstrate how to query and display data, incorporate stored procedures, customize the classes generated by the EF4, and much more.


Creating a Database using Model-First Development


Step 1: Create a New Solution

1. Launch Visual Studio 2010 Beta 2
2. Click the New Project link on the Start Page.  The New Project dialog box should appear
3. Click on the Visual C# node from the tree view of installed templates
4. Select Empty ASP.NET Web Application from the list of templates
5. Enter OrderSystem for the project name and click the OK button

Visual Studio will create a solution file in the folder you specified and also create a sub folder that contains the web site's project file and config files


Step 2: Create an ADO.NET Entity Data Model

The next step is to create the ADO.NET Entity Data Model.  For this application we'll model the concept of users and addresses.  A user can have more than one address so we'll build an entity data model that models this relationship

1. Right click on the OrderSystem project in the Solution Explorer and select Add à New Item…
2. Click the Data node under the Visual C# node in the Installed Templates tree
3. Select the ADO.NET Entity Data Model template
4. Change the name to OrderDB.edmx and click the Add button
5. Visual Studio will display the Entity Data Model Wizard.  This is where you can decide to build the model from an existing database or create the model first and then build the database
6. Choose Empty model from the wizard and click the Finish button

The OrdersDB.edmx file will be added to your project and the file will be displayed in the Entity Framework Designer


Step 3: Create the Entities and Associations


The next step is to model the user and user's addresses relationship. Let's first create the user entity.

1. Right click on the Entity Data Model Designer and select AddàEntity… from the pop-up menu
2. The Add Entity dialog box should appear.  Enter UserAccount for the Entity name.  Notice that as you type the Entity name the Entity Set name pluralizes the Entity name.  Think of the Entity name as the class that represents a record and the Entity set as the class that represents the table of those records
3. By default the Entity Framework will create a Primary Key called Id.  If you wish to not create a primary key you can uncheck the Create key property checkbox from the dialog box.  For this example we want a primary key so leave the box checked
4. Click the OK button. The UserAccount entity will be added to the entity diagram
5. The next step is to add properties to this entity. Properties will map to fields in a table. We'll first add the First and Last name properties
6. Right click on the UserAccount entity and select AddàScalar property from the pop-up menu
7. Change the property name to FirstName
8. In the properties window change the MaxLength to 50. Scalar properties are strings by default
9. Add another property called LastName the same way and set its MaxLength to 50

The next step is to add and insert date and update date properties.  I like to have the inserted and updated dates on every entity just for the sake of trouble shooting.  These are two properties that will be added to every entity so it is the perfect candidate for a Complex Type.  A Complex Type allows you to define a set of properties and then associate them with multiple entities.

10. In the Model Browser window, left click on the Complex Types nodes.  Sometimes you have to click more than once for the node to be selected.  I'm using Beta 2 so hopefully this will be fixed when it goes live.  Once the node is selected right click and select Create Complex Type from the pop-up menu



11. Change the name of the complex type to AuditFields
12. Right click on the AuditFields complex type in the Model Browser and select AddàScalar PropertyàDateTime from the pop-up menu
13. Change the name to InsertDate
14. Follow the same steps to add the UpdateDate property to the complex type
15. Now you can add the Complex property to the UserAccount entity.  Right click the UserAccount entity and select AddàComplex Property from the pop-up menu
16. Change the name to AuditFields.  The type should have already defaulted to AuditFields

When the database is created from this entity it will contain the two audit fields defined in the complex type.Now let's add the address entity.  A user can have more than one address so there is a one-to-many relationship between these two entities

17. Right click the designer and select AddàEntity from the pop-up menu
18. Change the name to Address and then click the OK button
19. Add scalar properties to the Address entity for Address1, Address2, City, State, and Zip.  All of these properties should be strings with lengths of 50, 50, 50, 2, and 5 respectively
20. Change Address2 to be nullable by settting the Nullable property to True in the properties window.  All other properties are required
21. Now add the Audit Fields to this entity by right clicking the Address entity and selecting AddàComplex Property from the pop-up menu.  Set the name to AuditFields and the type to AuditFields

The next step is to create an association between the UserAccount and Address entities.

22. Right click on the UserAccount entity and select AddàAssociation from the pop-up menu
23. The Add Association dialog appears.  It assumes correctly that you want to create a one-to-many relationship between these two entities.  You use the Multiplicity drop down to define the variations of relationships but for this example you can leave the defaults and click the OK button.  Notice that a UserAccountId property was added to the Address table

Step 4: Generate the Database

Now that the entities are defined we can create the database.  Visual Studio makes this quite simple.  A script is generated with the correct DDL statements to create tables, indexes, and relationships which you can then execute against your database

1. Right click on the Designer and select Generate Database from Model… from the pop-up menu.  The Generate Database Wizard will appear
2. Click the New Connection… button
3. Enter your Server Name. Choose either User Windows Authentication or Use SQL Server Authentication.  Whichever you choose you need a user that has permissions to create a database on the server.  For this example I'll use Windows Authentication
4. Enter OrderSystem for the name of the database and click the OK button
5. You should get a message stating "The database 'OrderSystem' does not exist or you do not have permissions to see it.  Would you like to attempt to create it?"  Click the Yes button
6. The database should be created and you'll be returned to the Generate Database Wizard dialog.  Click the Next button
7. The wizard will now generate the DDL statements needed to create this database
8. Click the Finish button
9. A new file will be added to the project called OrderDB.edmx.sql. The file contains the DDL statements to create the database.  The text of the file is as follows:
-- --------------------------------------------------

-- Date Created: 01/17/2010 09:39:04

-- Generated from EDMX file: C:\Documents and Settings\VinceVarallo\

-- my documents\visual studio 2010\Projects\OrderSystem\OrderSystem\OrderDB.edmx

-- --------------------------------------------------

 

SET QUOTED_IDENTIFIER OFF;

SET ANSI_NULLS ON;

GO

 

USE [OrderSystem]

GO

IF SCHEMA_ID(N'dbo'IS NULL EXECUTE(N'CREATE SCHEMA [dbo]')

GO

 

-- --------------------------------------------------

-- Dropping existing FK constraints

-- --------------------------------------------------

 

 

-- --------------------------------------------------

-- Dropping existing tables

-- --------------------------------------------------

 

 

-- --------------------------------------------------

-- Creating all tables

-- --------------------------------------------------

 

-- Creating table 'UserAccounts'

CREATE TABLE [dbo].[UserAccounts] (

    [Id] int  NOT NULL,

    [FirstName] nvarchar(50)  NOT NULL,

    [LastName] nvarchar(50)  NOT NULL,

    [AuditFields_InsertDate] datetime  NOT NULL,

    [AuditFields_UpdateDate] datetime  NOT NULL

);

GO

-- Creating table 'Addresses'

CREATE TABLE [dbo].[Addresses] (

    [Id] int  NOT NULL,

    [Address1] nvarchar(50)  NOT NULL,

    [Address2] nvarchar(50)  NULL,

    [City] nvarchar(50)  NOT NULL,

    [State] nvarchar(2)  NOT NULL,

    [Zip] nvarchar(5)  NOT NULL,

    [AuditFields_InsertDate] datetime  NOT NULL,

    [AuditFields_UpdateDate] datetime  NOT NULL,

    [UserAccountId] int  NOT NULL

);

GO

 

-- --------------------------------------------------

-- Creating all Primary Key Constraints

-- --------------------------------------------------

 

-- Creating primary key on [Id] in table 'UserAccounts'

ALTER TABLE [dbo].[UserAccounts] WITH NOCHECK 

ADD CONSTRAINT [PK_UserAccounts]

    PRIMARY KEY CLUSTERED ([Id] ASC)

    ON [PRIMARY]

GO

-- Creating primary key on [Id] in table 'Addresses'

ALTER TABLE [dbo].[Addresses] WITH NOCHECK 

ADD CONSTRAINT [PK_Addresses]

    PRIMARY KEY CLUSTERED ([Id] ASC)

    ON [PRIMARY]

GO

 

-- --------------------------------------------------

-- Creating all Foreign Key Constraints

-- --------------------------------------------------

 

-- Creating foreign key on [UserAccountId] in table 'Addresses'

ALTER TABLE [dbo].[Addresses] WITH NOCHECK 

ADD CONSTRAINT [FK_UserAccountAddress]

    FOREIGN KEY ([UserAccountId])

    REFERENCES [dbo].[UserAccounts]

        ([Id])

    ON DELETE NO ACTION ON UPDATE NO ACTION

GO

 

-- --------------------------------------------------

-- Script has ended

-- --------------------------------------------------


It is important to note that the tables weren't added to the database yet.  In order to actually create the tables you need to right click in the OrderDB.edmx.sql file and select Execute SQL from the pop-up menu.  You'll be prompted to log into the server that contains your database.  Once you are logged in the script will execute and the objects will be added to your database


Conclusion

That's all you need to do to create a database using the new Entity Framework's Model First methodology. This is a big improvement over the first edition because it allows you to use Visual Studio to work through the design of you objects first and then VS can figure out how to create the database tables, indexes, and relationships for you.





ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!

 

Calendar

<<  March 2024  >>
MoTuWeThFrSaSu
26272829123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar

Sign in