Data Entity Models – Customizing, Mappings and Reference Relationships

by Aref Tue, April 22 2014 12:05

Here is a cheat-sheet of the most commonly used data annotation attributes with Entity Framework

Data Attributes

Data Type: Use this to specify a more specific datatype than what is intrinsically assumed by EF. In this case a Date instead of Date Time.
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }

Column Attribute: The Column attribute specifies the column name that EF will assign (create) when the physical database model is generated. So your entity class (model) property may be called FirstName but with the Column attribute, that specifies [Column(“FNAME”)] will ensure that the corresponding database field name is FNAME.
[Column("FNAME")]
public string FirstName { get; set; }

DatabaseGenerated Attribute: Use this to specify how primary key values will be generated by the database or provided by the user (by using None as in the example below).
[DatabaseGenerated(DatabaseGeneratedOption.None)]

Display Attribute: The Display attribute specifies the caption that will be used for the text boxes instead of the Property Names
[Display(Name = "Full Name")]
public string FullName {get; set;}

DisplayFormat Attribute and the NullDisplayText: Use this to specify a default text in case of nulls.
[DisplayFormat(NullDisplayText = “No Courses”)]

Read-Only Calculated Properties

Here is an example:
[Display(Name = "Full Name")]
public string FullName
{
     get
          {
                 return LastName + ", " + FirstName;
           }
}

Validation

String Length: Specify a maximum length for a string data type. Note: You can also use the MaxLength attribute but this will not provide you with client side validation.
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
public string FirstName { get; set; }

Regular Expression: Specify a regular expression to provide restrictions to an input.
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]

Here are some online tools to help you build and test regular expressions:

http://www.regexr.com/
https://www.debuggex.com/

http://refiddle.com/

 

Required Attribute: Makes the associated property a required field. Not needed for value types such as DateTime, int, double and float
[Required]

 

Reference Relationships

Primary Key – the Key Attribute: Use the Key attribute to specify a Primary Key when naming convention (<entity>Id) was not used for instance. This tells EF to consider the following property as a primary key.

[Key]
public int SID { get; set; }

Foreign Key – the ForeignKey Attribute: Use the ForeignKey attribute on the dependent class, for instance on the many side of a relationship to specify a Foreign Key relationship. For instance lets say the Primary Key for a Student is SID and a Student can have many courses. You will specify the ForeignKey attribute to SID in the Course entity (dependent) to specify the Foreign Key.

… in the Course class …
[ForeignKey(“Student”)]
public int SID { get; set; }

NOTE: You must also include a navigation property to match the ForeignKey name (Student in the example above)!

public virtual Student Student { get; set; }

This tells Entity Framework that the SID property in the Course class is a Foreign Key to the Student class.

 

Navigation

Navigation Properties are lazy loaded (therefore uses Virtual) and provides navigation to other entities if needed. For example if a student has enrolled in many courses, the Student entity can have a navigation property to the Course(s) as shown below. Note that this does not imply a Database Referential Relationship (Foreign Key, Primary Key). Also as in this case if the navigation is required to many of the referenced entity, it’s type must have implemented the ICollection<T> interface such as IList<T> but not IEnumerable<T>

… within the Student class…
public virtual ICollection<Course> Courses { get; set; }

NOTE: If you plan on eagarly loading the navigated properties and expose them as JSON formatted output, you may encounted the following error condition:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.

Self referencing loop detected for property 'parent-entity' with type 'Models.Core.Referenced-Entity'.

One way to get around this is to include the following in your Global.asax, Application_Start:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Re‌ferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

References: Also see the following resources for more information

Creating a more complex data model http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

Implementing Inheritance with the EF6 http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

 

Tags: ,

ORM | SQLServer

Assign SharePoint and Reporting Permissions to your TFS 2012 Users

by Aref Sun, October 14 2012 12:53

When you add a new TFS user he/she may not have access to other, external components or services that TFS integrates with. Namely, this new user may not have permission to use Reporting or the Team Project Portal. In this post, I describe the steps that I have taken to add a new user across all components.

Assumptions

1. You have already created an AD User (and added them to an AD Group, I call mine TFSUsers).

2. You have gone into TFS Administion and added this group or user to the appropriate permission level. I add mine to the "[TFS Project Name] Team" group, which by default is assigned the "Contributors" rights.

Here are the steps then,

SHAREPOINT

1. Launch into the TFS Administration Web page as shown below.

Figure 1.

2. Click on the "Go to project portal" link as shown in Figure 1. Sign on with credentials allowed to administer the SharePoint portal. You will then be taken to the following SharePoint site.

Figure 2.

3. Click on "Site Actions" as shown in Figure 2. and then click on "Site Permissions" as shown in Figure 3.

Figure 3.

4. Now follow the steps shown in Figure 4 to grant the AD Group or User the appropriate permission(s).

Figure 4.

REPORTING

1. Click on "View Reports" as shown in Figure 1. Sign on with the appropriate administrative credentials to the Reporting site, as you are taken to the following page as shown in Figure 5.

Figure 5.

2. Click on "Folder Settings" as shown in Figure 5 as you are taken to the Role Assignments page shown in Figure 6.

Figure 6.

3. Click on "New Role Assignment" as shown in Figure 6, and then assign the appropriate role to the AD Group or User.

Figure 7.

That's all folks! Now your added user or group should have appropriate permissions to work with Team Foundation Server.

Tags:

Hyper-V | IIS | SQLServer | TFS | Virtualization | Visual Studio

Deploying TFS 2012 using Secure Socket Layer (SSL) - Success!

by Aref Tue, October 09 2012 13:53

Introduction

In my scenario, I have chosen to deploy the Standard TFS 2012 product on a SINGLE SERVER machine (by far, the most popular deployment scenario supporting shops with 500 developers or less). I am using a virtual server served up by Hyper-V and configured to 2 processors and 10 GB memory (SharePoint + TFS requires it). As the standard deployment process is fairly self-explanatory and straight-forward I will concentrate more on the configuration steps post TFS deployment. However, here are some best practices that I can suggest. (Remember, my deployment uses Windows Server 2008 R2 on a Hyper-V virtual server with 2 processors and 10 GB memory allocated to it. If you do not want to deploy SharePoint and Reporting, you will need at least 4 GB memory.)

   1.      Start with a clean Windows Server 2008 R2 (virtual) machine.

   2.      Install all patches using Windows Update AND Microsoft Update.

   3.      Enable the Application Server and Web Server Roles.

   4.      Install the .Net Framework 3.5 Feature.

   5.      Install all patches using Windows Update AND Microsoft Update.

   6.      Create or prepare a local or domain login and make sure password never expires or changes.

   7.      Give this login (let’s say, DOMAIN\tfsservice) the right to Logon as a service via the Local Policy snap-in.

   8.      Install SQL Server 2008 or 2012 (I installed 2012). Make sure that you install at least the following (use the service account you created above e.g. DOMAIN\tfsservice):

a.       Database Engine

b.      Reporting Services

c.       Analysis Services

d.      Full Text Indexing

   9.      Install all patches using Windows Update AND Microsoft Update.

   10.  Install TFS 2012 using the single-server, Standard option.

   11.  Configure TFS 2012 for SharePoint and Reporting using the service account you created above e.g. DOMAIN\tfsservice). Make sure that it runs.

   12.  If you get repeated prompts for login from a browser to the SharePoint Central Administration or TFS Web Access on the server you installed TFS, you may need to implement the “loopback hack”. Refer to Microsoft’s KB article here: http://support.microsoft.com/kb/896861

   13.  At this point, you should have a fully functional, non-SSL TFS deployment that you can test using the Team Explorer within Visual Studio, TFS Web Access from a browser, TFS Administration Console Application layer, SharePoint extension and SharePoint configuration. This is the point that we will start from to enable SSL access.

Figure 1. The Application Tier Holy Grail from the TFS Admin Console.

Pre-requisites

In order for us to SSL-enable our TFS deployment we will first need a few things in place.

   1.      We will need a SSL Certificate issued from either Windows Certificate Authority that you deploy on your domain or from a Trusted Certificate Provider. Make sure that the common name for the certificate points to the Fully Qualified Domain Name (FQDN) of your TFS server.

   2.      We will use some ports for the various web applications on the TFS server, namely (and you can choose any available ports, this is just an example)

a.       SharePoint Default Site (or alternately named site): 6443

b.      SharePoint Central Administration Site: 7443

c.       Reporting Services Site: 8443

d.      Team Foundation Server Web Access site: 443

   3.      You will want to make sure that these ports are allowed in through any and all firewalls in your infrastructure. In the minimum you must create an Inbound Rule in the local TFS Server by running wf.msc to allow TCP ports 6443, 7443, 8443, 443 inbound. Also, don't forget to allow all communications to your database services through any firewalls as applicable. For more information on firewall ports for SQL Server, here is a link for SQL Server 2012: http://technet.microsoft.com/en-us/library/cc646023.aspx.

   4.      You must also prepare your SharePoint site to allow your external host access to it. You can view a video describing this here: http://tinyurl.com/8qa67sx Here, allow your FQDN (e.g. www.mytfs.com) inbound recognition by adding that FQDN as the host name and enabling SSL access on port 6443 if you are using the ports above.

   5.      Next, you will need to configure Reporting Services using its configuration tool to use SSL on port 8443 (again, if you are using the ports defined above). Reporting services will automatically retrieve the FQDN from the certificate you pick. Make sure that you pick the right certificate. http://tinyurl.com/9dujbnc

Get er done

    Configure the Alternate Access Mapping in SharePoint for the Central Administration and your Default SharePoint websites.

Figure 2. Configuring Alternate Access Mapping Collection in SharePoint.

   1.      Bind the sites in IIS Manager. In your IIS 7.5 management console, for each of your web sites (Default SharePoint, SharePoint Admin, Team Foundation Server), do the following:

Figure 3. SSL Binding for the TFS Site in IIS.

a.       Click on binding, choose Https as the protocol and specify the appropriate ports (as suggested in pre-requisites, #2 above). I would further suggest that you do not enforce only SSL to be used though the SSL Settings in the IIS console, instead try using URL Rewrite to redirect your users to the secure site. You can download URL Rewrite from iis.net downloads.

b.  Edit the directory security and make changes to DISABLE Anonymous Authentication and ENABLE Integrated and Basic Authentication.

   2.      Launch the TFS Administrator Console as an Administrator and click on the Application Tier/URL configuration dialog. Here provide the secure URL to your TFS web access site and leave the server to server communication account.

   3.      Next follow the following to update your web.config in the Message Queue web folder. Make sure you backup your existing web.config:

·  Open the web.config file for Team Foundation Server in any plain-text editor, such as Notepad. By default, this file is located in the following directory: %PROGRAMFILES%\Microsoft Team Foundation Server 2012\Application Tier\Message Queue\web.config.

·  Remove the following endpoints from the file:

        <!-- An empty relative address means the endpoint will pick up the base address of the svc file -->

        <endpoint address=""

                  binding="customBinding"

                  bindingConfiguration="TfsSoapBinding"

                  contract="Microsoft.TeamFoundation.Framework.Server.WebServices.MessageQueueWebService" />

        <!-- An empty relative address means the endpoint will pick up the base address of the svc file -->

        <endpoint address=""

                  binding="customBinding"

                  bindingConfiguration="TfsSoapBinding"

                  contract="Microsoft.TeamFoundation.Framework.Server.WebServices.MessageQueueWebService2" />

·  Navigate to the <system.serviceM

odel> section, and add the following protocol mappings:

<protocolMapping>

      <remove scheme="http" />

     <add scheme="http" binding="customBinding" bindingConfiguration="TfsSoapBinding"/>

      <add scheme="https" binding="customBinding" bindingConfiguration="TfsSoapBindingHttps"/>

</protocolMapping>

·  In the same <system.serviceModel> section, add the following binding to <customBinding>:

<binding name="TfsSoapBindingHttps">

          <textMessageEncoding messageVersion="Soap12WSAddressing10" />

          <httpsTransport authenticationScheme="IntegratedWindowsAuthentication" manualAddressing="true" />

</binding>

   4.      Next, from within the TFS Administrative Console, go to SharePoint extensions and add a new access to the secure SharePoint default site that you had created in step Pre-requisites #4 above. Remove the old access mapping.

Figure 4. Configure Extensions for SharePoint Products.

   5.      Next, from within the TFS Administrative Console, go to SharePoint configuration and use the new extension and secure URL’s.

Figure 5. SharePoint Web Application Configuration.

 

Post Installation Lessons Learned

1.      Do NOT use a service account for Reporting Services. Instead USE the NETWORK ACCOUNT. Otherwise you may get errors when you try to create a Team Project complaining that the Report Folder could not be created.

Figure 6. Use NETWORK SERVICE for your Reporting Services, Service Account.

Figure 7. Reporting Tier configured in TFS Admin Console.

2. Configure your Build setup as necessary.

Figure 8. Build Configuration.

3. Configure your Lab Management as necessary.

4. Configure your Proxy as necessary (TIP. Only use Proxy if you have a fair amount of remote users who will be accessing your TFS site from that location).

5. Back up all databases and your configuration.

Good luck, and please do share your experiences here as well.

 

Tags:

IIS | Solved | SQLServer | TFS | Visual Studio