Introduction

In December 2011, Microsoft released an early Release Candidate (RC) of SQL Server 2012 (formerly known as codename Denali).

There are a bunch of new things in SQL Server 2012 – here’s a list of just a few:

To find out more about what is coming in SQL Server 2012 check out the following “What’s New?” page

Downloading SQL Server 2012 RC 0

I’ve found the easiest way to proceed with the RC0 is to obtain a DVD .iso (image) of the whole kit, otherwise, you can download it in component parts to keep your download footprint minimal.

The following location is the “correct” download link: http://www.microsoft.com/download/en/details.aspx?id=28145 or you can just go directly to the beta experience website here: http://www.microsoft.com/betaexperience/pd/SQLDCTP3CTA/enus/

Installing SQL Server 2012 RC 0

SQL Server, in recent years, has had one of the best setup and installation experiences of any Microsoft product on the market.  Well, based on y experience with the 2012 RC 0 release, this is getting a little more complicated.

The next few screenshots will guide you through a fairly straightforward configuration, using the latest release.

Installation Screenshots

1. Execute the installation package
2. In the SQL Server Installation Center, select the Installation option
3. From here, jump right in and click on “..new installation”
4. You’ll get all the prerequisite checks and loading of setup files, just proceed as you would with a prior
    edition of SQL Server
5. Once the main installer kicks in (you passed all the prerequisite checks etc), you’ll get to the intro page
6. Click through to the licensing page – note we’ll keep it on Evaluation:

0-2

7. Next, we’re going to select the first option (feature installation):

0-3

8. In the feature selection page, I’m selecting all features, but you should select just what you’re going to want
    to evaluate:

0-4

9. Skipping ahead through some screens now (they are unchanged from 2008 R2), the Server Configuration page has changed, requires you to individually set service accounts.

Best Practice: Use a different account for each service
Best Practice II: In a domain environment, if you wish to use Kerberos, ensure you use a Domain account for the service identity, and ensure the proper ADSI settings are set

0-5

10. Assign some user accounts as System Admins.  I always assign the local machine admin (in non-Production environments) and a Domain Admin (in a Domain environment) so that we don’t get accidentally locked out.

1-1

11. Same procedure for Analysis Services (if applicable):

1-2

12. Reporting Services has changed a little since 2008 R2, you have a few options for configuring native mode or SharePoint Integrated mode.  The native configuration is handy if you don’t have any exotic configuration requirements:

3

13. The Distributed Registry Controller (optional) is new to 2012.  You can only assign user accounts (not groups).  If you accidentally add a group, it’ll complain – and then (in my experience) crash..

4

13.1. Oops, a soft crash when trying to remove the offending group (best to avoid this situation):

2

14. If you’ve chosen it, the Distributed Replay client needs a Controller name:

5

15. Finally, assuming you’ve accepted most of the defaults, you may arrive at the summary screen:

6

16. When you are happy, you can kick off the install.  It may take a while, if you’ve selected a number of features.  Finally, if all goes to plan, you hopefully will end up with a success:

image

..and it’s probably time for a reboot. 

Post-Install Sanity Check

After the system has restarted, we can check out all the new stuff installed:

image

image

image

Summary

Well, this was a lesson in patience from my perspective.  Whilst nowhere near as challenging of some other products, there are a few new things to consider when installing SQL Server 2012. 

As always, it helps to read the installation guide.  There are a number of new changes this time around, so even if you’ve done plenty of SQL Server 2008 installs, it might pay to do a quick skim of the install material first.

Lastly, as always, it pays to properly plan your infrastructure.  I’m usually installing into sandboxes, so what I’ve presented here is by no means what I’d recommend for a production system.  If you are planning a production system with a pre-release edition, all power to you (brave).

Please always keep these issues in mind when planning your SQL/Infrastructure:

  • Disaster Recovery,
  • Fault Tolerance,
  • Availability and Scale,
  • Persisted Storage requirements,
  • Physical hardware limitations, and,
  • Backup and test your backup strategy!

Further Reading

Tutorials and Samples for SQL Server 2012 RC 0

Microsoft SQL Server Data Tools (SSDT)

 

There are times when you want to get a little creative about your investigative work when it comes to SQL Server.  In this case, this is a very short article highlighting some efficiencies in locating information about specific programmatic resources within a database.

If you haven’t used the INFORMATION_SCHEMA views before, well you’re in for a treat. 
Let’s say you need to query the details of a Stored Procedure, and all you know is the name of the proc. 

How would you go about retrieving the information?

One way is to use the INFORMATION_SCHEMA.ROUTINES.  For this example, let us assume our proc is called “usp_TestProcedure”, and execute the following:

SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ‘PROCEDURE’
  AND ROUTINE_NAME =
‘usp_TestProcedure’
ORDER BY ROUTINE_NAME

This results in a plethora of information (some of it not used).  Of interest are the following columns:

ROUTINE_CATALOG – location of the routine
ROUTINE_SCHEMA – schema of the routine
ROUTINE_NAME – name of the routine

ROUTINE_TYPE – Type of routine, e.g. Procedure/Function etc
ROUTINE_BODY – Whether it is T-SQL, other etc
ROUTINE_DEFINITION – The actual text of the routine

CREATED  – Created Date
LAST_ALTERED – Modified date

All well and good.. but what of those Parameters?  We can query those details from INFORMATION_SCHEMA.PARAMETERS as follows:

SELECT 
  COALESCE(PARAMETER_NAME, ‘<no params>’) as ‘Parameter’,
  COALESCE(UPPER(DATA_TYPE) +
  CASE
    WHEN DATA_TYPE IN (‘NUMERIC’, ‘DECIMAL’) THEN
     ‘(‘ + CAST(NUMERIC_PRECISION AS VARCHAR) 
        + ‘, ‘ + CAST(NUMERIC_SCALE AS VARCHAR) + ‘)’ 
    WHEN RIGHT(DATA_TYPE, 4) = ‘CHAR’ THEN
        ‘(‘ + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ‘)’
        ELSE ” END + CASE PARAMETER_MODE
    WHEN ‘INOUT’ THEN ‘ OUTPUT’ ELSE ‘ ‘
    END, ‘-’) as ‘Data Type’
FROM INFORMATION_SCHEMA.PARAMETERS
WHERE SPECIFIC_NAME =
‘usp_TestProcedure’
ORDER BY ORDINAL_POSITION

Obviously this applies a bit of logic to format the output, depending on the type of parameter, there are plenty of useful columns in this view which would help you determine more about each parameter, such as numeric precision, maximum lengths, parameter direction (in/out) and so on.

Now, what happens when you alter a Stored Procedure and the information isn’t immediately refreshed in the INFORMATION_SCHEMA?  Well, for SQL Server, try running a Stored Procedure recompile by executing the following:

EXECUTE sp_recompile <proc name>

Enjoy using INFORMATION_SCHEMA!

 

Recently I alluded to writing a series of posts on the Entity Framework Futures, now referred to as the “Microsoft ADO.NET Entity Framework Feature Community Technology Preview 5“ which could really, really use a cool codename.

Introduction

If you’ve been following along on the Windows Workflow Rules Engine series of posts (links at the bottom of this article), you’d know that we have a working model sample already underway.  It is my plan to reuse this solution to embrace learning about code first and the recent Entity Framework CTP5.  I’m going to reuse the objects in that small sample, and demonstrate how to do some initial plumbing to get you up and running.

Here’s a link to the original solution, in case you’d like to see a “before and after” view of the solutions.  What we’ll be doing in part 1 is to simply provide a data storage solution underneath the existing data objects.  You’ll find that we don’t need to do much to “bolt” the Entity Framework onto the object model and to use a context to persist data to a database – all created through code.

Preparing the Solution

The Data Access Assembly

The first thing I had to do was add another class library (“DataAccess”) to the solution, to contain the actual data context definition and to provide for any helper methods and anything else specific to data persistence.  To this new class, I added references to System.Data.Entity and a local reference (relative) to the EntityFramework.dll (which you need to copy from the CTP5 release).  We also need a project reference to the BusinessObjects class.

Next, I added a data context class which for this example is very straightforward:

namespace DataAccess
{
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }       
    }
}

Unit Test Project

Next, I added a new unit test project (DataAccess.UnitTests) to the solution explicitly to test the data access functionality.  I added a reference to System.Data.Entity and also a reference to the EntityFramework.dll and also added a new App.Config file, which I’ll use to explicitly provide connection string information for the Data Context.  This project also has project references to BusinessObjects and to the DataAccess assembly, of course.

Business Objects Assembly

I like to try and keep the data objects themselves as separate and clean as possible, so the only change to the existing project is to add a reference to the System.ComponentModel.DataAnnotations assembly.  We need this so we can add Data Annotations to the classes for use with the Entity Framework.

image

The Solution Structure

Changing the Data Object(s)

Now that we have everything pretty much in the right location, we need to modify the Employee class a little bit.  Thankfully, this is a fairly easy task.  I did a little refactoring to create a one-to-many relationship between an Employee and his/her manager, as well as a reverse navigation relationship, Manager to Employees.  Referencing System.ComponentModel.DataAnnotations allows us to decorate the class with attributes which the Entity Framework will use to create the database schema.

Here is the new and improved Employee entity.  You can see the data annotations – there was a small catch with the navigation properties, modelled as self joins, there seems to be a bug in CTP5 so the only realistic option right now is to go with Code First’s default column.  I couldn’t guarantee the use of Manager/Employees, so instead it has to be tested with a unit test for now.

namespace BusinessObjects
{
    public class Employee
    {
        [Key]
        public int EmployeeNumber { get; set; }

        [StringLength(100)]
        public string FirstName { get; set; }
        [StringLength(100)]
        public string Surname { get; set; }
        [StringLength(100)]
        public string JobTitle { get; set; }

//Enums are not supported!!?
//h
ttp://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/9a5d5a64-4de8-4685-8896-c5e8f66fda65
        public StateEnum Location { get; set; }

        [Required]
        public DateTime DateHired { get; set; }       

// we’ve got a bug here with self-joins
//h
ttp://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/05198b97-f178-49ba-91da-7a2516a9ad8d
// for now, we have to accept the default column generated by code-first
        public virtual Employee Manager { get; set; }
        public virtual ICollection<Employee> Employees { get; set; }
    }
}

Some notes on entity support..

  • Self joins are still a bit of a mess
  • No support for enums!  Bitterly disappointing really.
  • the Fluent API can be used to add extra annotations at runtime

Unit Test Configuration

In our unit tests, we can add the following method to ensure that the database model is dropped and recreated anytime the schema changes.  You’ll need a more practical solution for any real product work, of course.

[ClassInitialize]
public static void TestInitialize(TestContext testContext)
{
   DbDatabase.SetInitializer<EmployeeContext>(new
                  DropCreateDatabaseIfModelChanges<EmployeeContext>());
}

Finally, I’ve added an app.config to the unit test project, and in it, I’ve added a connection string which uses the same name as the Data Context.  This allows us to specify the connection settings (the default is to use SQL Express).

<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
<connectionStrings>       
<!–
http://blogs.msdn.com/b/adonet/archive/2010/09/02/ef-feature-ctp4-dbcontext-and-databases.aspx
–>
<add 
name="EmployeeContext"
providerName="System.Data.SqlClient"
connectionString="Server=.;Database=Employee;Integrated Security=True" /> 
</connectionStrings>
</configuration>

Basically, every time the tests are run, the model will be dropped and recreated.  It’s also a good time to seed test data for the unit tests.

Putting it all together

So to test out Code First for the first time, I’ve mocked up a very simple test which is almost verbatim from the sample linked below.  Please note that this is for demonstration purposes only and does not constitute a valid unit test approach – I’m merely demonstrating how Code First works.

[TestMethod]
public void TestAddData()
{
    using (var db = new EmployeeContext())
    {
        // Add an employee
        var john = new Employee {  EmployeeNumber = 1,
                                   FirstName = "John",
                                   Surname = "Smith", 
                                   DateHired = DateTime.Now.AddYears(-1) };
        db.Employees.Add(john);
        int recordsAffected = db.SaveChanges();

        Trace.WriteLine(String.Format("Saved {0} entities to the database", 
                                      recordsAffected));
    }
}

That’s pretty easy.  If we execute the test and everything is configured correctly, we should get the database created, and the single row inserted:

image

If we add a second test, we can add another record and include a relationship to the first row added in our initial test:

[TestMethod]
public void TestAddRelationshipsData()
{
    using (var db = new EmployeeContext())
    {
        Employee john = db.Employees.Where(x => x.EmployeeNumber == 1).First();

        // Add an employee
        var gary = new Employee { EmployeeNumber = 2,
                                    FirstName = "Gary",
                                    Surname = "Smith",
                                    DateHired = DateTime.Now.AddYears(-1),
                                    Manager = john};
        db.Employees.Add(gary);
        int recordsAffected = db.SaveChanges();

        Trace.WriteLine(String.Format("John has {0} Employees", 
                                       john.Employees.Count));
    }
}

Notice that we reload the first employee and specify the relationship when constructing the second employee.  Easy stuff!

image

Obviously this is for demonstration purposes only!  You should always encapsulate your test data either loaded as a static set (and cleaned up), or use a transaction scope to prevent any permanent commits to the database – unit tests should never leave any test data persisted!

Conclusion

That’s pretty much the rundown for Part 1.  We’ve seen how we can bolt EF’s code first onto an existing (albeit shallow) model, and programmatically cause the schema to be created.  There’s so much more to do though, and (as I’m frequently finding out) there are a lot of roadblocks to overcome, but thus far it is promising!

We’ll continue with Part 2 next week, once I’ve had a chance to explore more advanced concepts – mostly to do with security, configuration and indexing and so forth.

If you are interested in the updated solution files, please leave a comment and I’ll happily post them to this article.

Further Reading

Entity Framework CTP 5
[ http://www.microsoft.com/downloads/en/details.aspx?FamilyID=35adb688-f8a7-4d28-86b1-b6235385389d ]

Code First Walkthrough
[ http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-code-first-walkthrough.aspx ]

More on configuring Data Context
[ http://blogs.msdn.com/b/adonet/archive/2010/09/02/ef-feature-ctp4-dbcontext-and-databases.aspx ]

The fluent API samples
[ http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx ]

Referenced Articles

[ Rules Engine Part 1 ]
[ Rules Engine Part 2 ]

 

A little late, but better late than never – the Entity Framework CTP 5 was released last month before Christmas, and now that I’m back, I’ll be doing a series of posts on Code First and CTP 5.  This is mainly to test out the new Object Validation which currently only is supported by Code First architectures.

Before we get into the nitty gritty behind the most recent CTP, why don’t we stop and take a quick look at where things are with the latest release.  First off, you’ll need .Net Framework 4 and a copy of Visual Studio 2010.  Next, grab the CTP from MSDN located here.

Let’s take a look at what is new in the fifth community technical preview (CTP) – from the release notes:

What is new?

This is the list of new and improved features in CTP5:

DbContext API

  • Model-First and Database-First support:
    New T4 templates is included for using DbContext/DbSet

  • Validation of objects on SaveChanges:
    Validation is based on the use of Data Annotations and currently only supported in Code First

  • Change tracking API:
    Allows you to access information and operations applicable to objects that are tracked by a DbContext

    • Access to Original, Current & Store Values

    • Entity state (i.e. Added, Unchanged, Modified, Deleted)

    • Explicit Loading: API to load the contents of a navigation property from the database

  • Databinding:
    DbSet.Local exposes an ObservableCollection representing the local contents of the DbSet. This is particularly useful when performing databinding in WPF applications. The new ToBindingList extension method can be used to obtain a binding list for Windows Forms applications.

  • No-Tracking Queries:
    This can be achieved via the AsNoTracking extension method on IQueryable<T>.

  • DbContext Configuration:
    Allows the following options to be configured for a DbContext instance:

    • Lazy Loading

    • Validate On Save

    • Auto Detect Changes

  • Raw SQL Query/Command execution:
    Allows raw SQL queries and commands to be executed via the SqlQuery & SqlCommand methods on DbContext.Database. The results can optionally be materialized into object instances that are tracked by the DbContext via the SqlQuery method on DbSet.

  • Improved concurrency conflict resolution:
    We have added better exception messages that allow access to the affected object instance and the ability to resolve the conflict using current, original and database values

  • DbContext.ObjectContext has moved:
    Rather than being a protected member we have made the underlying ObjectContext available via an explicitly implemented interface, this allows external components to make use of the underlying context. Getting the context now looks like: ((IObjectContextAdapter)myContext).ObjectContext

  • Excluding EdmMetadata Table:
    If Code First is generating your database and you wish to exclude the EdmMetadata table, this is now done by removing a convention (note that you do no longer need to do this when mapping to an existing database).

  • Types renamed in System.Data.Entity.Database namespace:

CTP4 Name

CTP5 Name

Database

DbDatabase

RecreateDatabaseIfModelChanges

DropCreateDatabaseIfModelChanges

AlwaysRecreateDatabase

DropCreateDatabaseAlways

Code First

  • Better Code First to Existing Database Support:
    CTP5 removes the need to switch off Database Initializers when working with existing databases with Code First. If you map to an existing database that Code First did not create then it will just ‘trust you’

  • Support for additional Data Annotation attributes:
    The full list of supported attributes now encompasses:

    • KeyAttribute

    • StringLengthAttribute

    • MaxLengthAttribute

    • ConcurrencyCheckAttribute

    • RequiredAttribute

    • TimestampAttribute

    • ComplexTypeAttribute

    • ColumnAttribute (placed on a property to specify the column name, ordinal & data type)

    • TableAttribute (placed on a class to specify the table name and schema)

    • InversePropertyAttribute (placed on a navigation property to specify the property that represents the other end of a relationship)

    • ForeignKeyAttribute (placed on a navigation property to specify the property that represents the foreign key of the relationship)

    • DatabaseGeneratedAttribute (placed on a property to specify how the database generates a value for the property, i.e. Identity, Computed or None)

    • NotMappedAttribute: Placed on a property or class to exclude it from the database

  • Fluent API Improvements:

    • Simplified table and column mapping

    • Ability to ignore classes & properties

  • Pluggable Conventions:
    Based on the large amount of feedback requesting this feature we have included an early preview in CTP5. We still have some work to do on this feature but we wanted to give you the chance to provide feedback before we RTM. We’ll provide more details on this feature in the coming weeks.

Other changes

  • New Assembly Name:
    Our assembly name has changed to EntityFramework.dll

There are a bunch of exciting new changes here, most notably around DataContext and Object binding properties.  I’m going to put together a few samples using Code First over the next week or so to show you how these new changes come into play in a real world scenario.

Whilst some of this functionality is new or improved, you might notice a lot of naming changes – it is quite clear that there is a great deal of refactoring going on under the covers including renaming of the assembly file!  This would seem to indicate a number of naming changes which will create significant code changes when porting from EFv4 to EFv5 in the future.

I’ll try to keep an eye on the most widespread changes as EFv5 CTPs are evolving.  Please keep in mind that the CTP releases are not sacrosanct, and sometimes the refactoring is reversed in later releases, so don’t treat it as set in stone.. yet.

 

If you are like me, you probably aren’t a huge fan of Kerberos, but it does have some advantages.  When using an Active Domain (AD) account as a service account, it is handy to reduce the attack vector by minimising the chosen Domain Account’s permissions and privileges.

If you are using a Domain Account as a service account for Microsoft SQL Server, for example, it’s highly likely that you will want the chosen service account to be able to automatically register and unregister Service Principal Names (SPNs) automatically when the service is started and stopped.  To avoid giving the account far reaching permissions (such as domain administration rights) you’ll be required to do some editing of the Domain Account’s ADSI properties.

This isn’t as daunting as it sounds (trust me).  Below are some articles worth reading – don’t be afraid to allow the account the ability to read and write service names.  In case you are in a hurry, here’s exactly what you must do to allow a Domain Account the ability to automatically register SPNs for services (from link #2, below) :

  1. Click Start, click Run, type Adsiedit.msc, and then click OK.

    Note The ADSIEdit tool is included in the Windows Support Tools. To obtain the Windows Support Tools, visit the following Microsoft Web site:

    http://www.microsoft.com/downloads/details.aspx?familyid=6EC50B78-8BE1-4E81-B3BE-4E7AC4F0912D&displaylang=en

  2. In the ADSI Edit snap-in, expand Domain [DomainName], expand DC= RootDomainName, expand CN=Users, right-click CN= AccountName , and then click Properties.
    Notes
    • DomainName is a placeholder for the name of the domain.
    • RootDomainName is a placeholder for the name of the root domain.
    • AccountName is a placeholder for the account that you specify to start the SQL Server service.
    • If you specify the Local System account to start the SQL Server service, AccountName is a placeholder for the account that you use to log on to Microsoft Windows.
    • If you specify a domain user account to start the SQL Server service, AccountName is a placeholder for the domain user account.
  3. In the CN= AccountName Properties dialog box, click the Security tab.
  4. On the Security tab, click Advanced.
  5. In the Advanced Security Settings dialog box, make sure that SELF is listed under Permission entries.
    If SELF is not listed, click Add, and then add SELF.
  6. Under Permission entries, click SELF, and then click Edit.
  7. In the Permission Entry dialog box, click the Properties tab.
  8. On the Properties tab, click This object only in the Apply onto list, and then click to select the check boxes for the following permissions under Permissions:

    • Read servicePrincipalName
    • Write servicePrincipalName
  9. Click OK two times.
    Note For help with this process, contact Active Directory product support, and mention this Microsoft Knowledge Base article.
    Note To use the dsacls tool to determine if the self account has the Write ServicePrincipalName permission, use the dsacls command. The following is the syntax:

    dsacls <distinguished_Name_of_service_account>

    If the self account has the Write ServicePrincipalName permission, you see the following output:

    Allow NT Authority\SELF SPECIAL ACCESS for Validated Write to Service principal nameWRITE PROPERTY

    The dsacls tool is part of the Support Tools.

  10. In the CN= AccountName Properties dialog box, click Attribute Editor.
  11. Under Attributes, click servicePrincipalName in the Attribute column, and then click Edit.
  12. In the Multi-valued String Editor dialog box, remove the service principle names (SPNs) for the instances of SQL Server that use this SQL Server service account.
    Warning You should only delete the SPNs for the instances of SQL Server that you are currently working on. The other instances of SQL Server that use this service account will be able to remove the SPNs that are related to these instances the next time that you start these instances.
  13. Exit the ADSI Edit snap-in.

Leave a comment is this helped or hindered you!  Cheers..R

Further Reading is Recommended

[1] http://msdn.microsoft.com/en-us/library/ms191153.aspx
[2] http://support.microsoft.com/kb/319723

 

You may have heard of the upcoming SQL Server Modelling suite formerly known as ‘Oslo’.  The suite, know known as the SQL Server Modelling CTP, features the ‘m’ modelling language and a graphical workbench known as (or codenamed) ‘Quadrant’.  I’ve been meaning to look into codename ‘Oslo’ for a while now, and I’ve finally had a chance to review how it works this weekend.

Designing for SQL Server has always been a fairly subjective art form.  Microsoft has not exactly been kind to data architects, continually changing its position on the how and why of data modelling tools.  Once upon a time, a database architect could rely on tools like Visio (for Enterprise Architects) for forward and reverse engineering database schema.

Microsoft is endeavouring to build a more comprehensive set of tools for what we term “DSL” languages or domain specific languages.  This essentially allows data architects to focus on business specific (or domain specific) architecture and to abstract away from the physical implementation of persisted storage in large enterprise designs.

What is SQL Server Modelling?

Well, let’s see what the official MSDN article mentions, below.

[1] The SQL Server Modelling CTP includes:

  • A database designed for models (built on SQL Server 2008 and called SQL Server Modeling Services) that is highly optimized to provide your data schemas and instances with system-provided best practices for scalability, availability, security, versioning, change tracking, and localization.
  • A visual tool (Microsoft code name “Quadrant”) for browsing any SQL Server database without writing a line of code. Using “Quadrant” you can easily browse any set of related tables by dragging and dropping icons that represent the related data. You can also filter data by writing “M” queries (you do not have to know Transact-SQL), and you can customize the viewer to display data how you want to see it, rather than seeing the physical database implementation.
  • A language (Microsoft code name “M”) with features that enable you to model (or describe) your data structures, data instances, and data environment (such as storage, security, and versioning) in an interoperable way. It also offers simple yet powerful services to create new languages or transformations that are even more specific to the critical needs of your domain. This allows .NET Framework runtimes and applications to execute more of the described intent of the developer or architect while removing much of the coding and recoding necessary to enable it.

At this point I haven’t had much to do with the ‘M’ language, aside from briefly reviewing the demonstration project which describes some aspects of the Windows Management Instrumentation model [2] which you can download and use with the latest CTP.  From what I understand, the ‘M’ language is designed to allow architects to query data without needing to know Transact-SQL.

The ‘M’ Language

The ‘M’ language also allows for design of models outside the traditional tools, in domain-specific environments. 
From the official website:

[1] The “M” Language and Features

Use the "M" language and its features to define custom languages, schema for data (data models), and data values. Doing so brings the meaning of the code you write closer to your own domain of experience. With more of your own intent encoded in models, it becomes easier for you—and other developers working with your domain—to write code and applications faster, especially by sharing models and reusing them.

  • You can use the schema (or model) definition feature of “M” to design interoperable models—data schemas—for the data in your particular field of interest (called a domain). Using the schema definition feature makes statements about the structure, constraints, and relationships, but says nothing about how the data is stored or accessed, or about what specific values an instance might contain. By default, “M” models are stored in a SQL Server 2008 database, but you are free to modify the output to any storage or access format. If you are familiar with XML, the schema definition feature is like XSD.
  • You can also use the value definition feature of “M” to create model (that is, schema) instances of your data structures. The value features make statements about the data values that are to populate instances of the models you or others have created, but again, interoperability is maintained. While the default compilation output can be inserted into SQL Server 2008 or into a Modeling Services database, you can transform the output into any format you need to support your scenario. If you are familiar with XML, defining values is like creating an XML file that conforms to an XSD file.
  • You use the language definition feature to create new, custom languages (sometimes called domain-specific languages, or DSLs) for your own domain of expertise that you control, without having to build a parser, lexer, or any other supporting infrastructure. Building a custom language makes it vastly simpler for you or your customers to express their specific desires, dramatically lowering the barrier to using your particular domains and applications built on them.
  • By default, the output of “M” is either Transact-SQL that can be inserted in any SQL Server 2008 database, or a more customized version of Transact-SQL that uses the advanced features of Modeling Services, such as security, versioning, change tracking, and so on. However, “M” languages are extensible and can output any specific format you care to implement. Model-driven applications must be interoperable, and where they interoperate depends upon your circumstances, requirements, and resources.

There’s also a utility called ‘Intellipad’ which appears to be an editor for the ‘M’ language and can be used if Visual Studio is unavailable, and supports solutions and projects.

image 
Intellipad showing the primer/help

Let’s take a look at the various parts of the Modelling Toolkit –

The Model Database (Repository)

The database sits in a local instance, so you’ll need access to an instance of SQL server.  Since SQL Express [3] is free, you shouldn’t really have any trouble with installing a local copy.  Once installed, you can install the CTP and take a look at the database that SQL Modelling uses.

image image
The Repository Database                            The WMI Model Sample

As you can see, the Modelling Service uses a database and many tables to persist the working models.  We’ll come to see how this is useful shortly, when we take a look at possibly the most useful part of the suite – codename ‘Quadrant’.

image

Let’s take a look..

image
The ‘Quadrant’ Workbench

Above is the main environment for the ‘Quadrant’ application.  I’ve got four windows open, and they constitute some of the key areas you’d be using when modelling.  On the top left is a view of a database I have attached in my local instance called ‘Vinyl’.  Below in the center is a view of some of the data from the “Album” table in that database.

In the top middle window is a T-SQL command window where ad-hoc queries can be performed.  Lastly, the top right window contains the default view of ‘Quadrant’’s own view – you can see all the namespaces and, if you have installed it – also the WMI modelling.

For more on ‘Quadrant’ take a read of this overview: http://msdn.microsoft.com/en-us/library/dd857506%28v=VS.85%29.aspx

Anyhow, this is a brief overview of the main parts – in the next entry we shall take a more proactive look at what we can do to model with a more domain-specific view.

You may download the CTP Here.

[1] http://msdn.microsoft.com/library/dd129514.aspx
[2] http://code.msdn.microsoft.com/SQLModCTPWMI/Release/ProjectReleases.aspx?ReleaseId=3470
[3] http://www.microsoft.com/express/database/

 

There’s going to be more to this in coming posts, but I thought I’d add all the articles I’ve been reading ahead of schedule.  The long and short of the story is this –

I’ve managed to implement round trip CRUD operations using POCO (Plain Old CLR Objects) using a WCF Service & Client in conjunction with the ADO Entity Framework v4 (and Visual Studio 2010 RC).

In doing so, I’ve implemented all the “fun stuff” (plumbing, configuration, attributes, etc) but I’m currently investigating the options for supporting non-lazy loading queries which return a partial object graph.  Part of the problem I’m facing is with the POCO Proxies (which are unknown types at runtime) though I hope to have a solution soon.

Enjoy the reading, or please be patient, and I’ll write a post going into more detail soon!

POCO Templates for Entity Framework v4 (applies to RC as well):

http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/

How to set up POCO Entities using the template:

http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx

ADO Team – Creating and Serializing POCO Proxies:

http://blogs.msdn.com/adonet/archive/2009/12/22/poco-proxies-part-1.aspx
http://blogs.msdn.com/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx

MSDN – Serializing POCO Proxies:

http://msdn.microsoft.com/en-us/library/ee705457%28VS.100%29.aspx

Exposing POCO Entities via WCF (forum):

http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/1c37447a-e303-4947-a3ee-d2e6592aac0a

Debugging/Trace tips and tricks:

If you find yourself with the dreaded “Object graph for type ‘X.Y.Z’ contains cycles and cannot be serialized if reference tracking is disabled error”
then check out this outstanding article:  http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html

 

Today I learnt an important lesson about moving a PC from one Active Directory domain to another – the process will strip (domain) logins from SQL Server!  Yes, I know this is kind of obvious and expected, but also easy to overlook.

So our scenario is that we don’t have any Windows Accounts which can authenticate to SQL Server (via SQL Management Studio or via command line tools) and/or we have no accounts as members of the sysadmin role.  the “sa” account is not usable because mixed mode authentication is not enabled.  We can’t administer the SQL instance.

This is a big problem if you rely on Windows Authentication (i.e. no mixed mode authentication), and you haven’t got any local (built in or otherwise) accounts which have been assigned sysadmin permissions. 

You’re basically stuck!  You can’t log onto the instance and you can’t administer SQL Server, even locally.  You can’t use the Dedicated Administration Console (DAC) either since it requires the active user to be in the sysadmin role!

SQL Server 2005 Service Pack 2 came with a handy utility called the User Provisioning Tool for Windows Vista (sqlprov.exe) and allowed you to assign sysadmin logins for your account (and other accounts).  This tool unsurprisingly doesn’t work with SQL Server 2008, and as far as I can tell there is no equivalent tool available (please correct me if I am wrong).

At this point you might be reaching for the installation media for a reinstall, but never fear – there is a solution.  The solution was actually quite obvious now that I think about it. You have to start SQL Server in single user mode.

This allows you to log on (using SSMS) from the localhost with sysadmin permissions. From there, you can then create new logins (including domain account logins, if so desired).

Here’s how to start SQL Server in single user mode and here’s more information on how to start SQL Server from the command prompt (which you will have to do for single user mode).

Big thanks to Rob Farley for supplying the suggestions.

 

Today I have been modifying a very repetitious SSIS package which does bulk import of data form a flat file.  The Data Import Wizard is a pain when you want to import the same format but from different source files, especially since it is unstable and tends to crash when you make changes and try to re-run its SSIS package.

So I created a package using the Wizard, then created a new Integration Services project in Visual Studio 2008 (no word on when support will be added for SQL Server projects in VS 2010?).  I imported (add existing item) the package the Wizard created and started to much around with adding variables so that I could set the input file path and the destination table name before executing the SSIS package in question.

The power here is we only have to set column definitions and the schema of the destination once, rather than having to re-jig every time we go to (manually) import from a flat file.  Below is what the wizard-generated SSIS package looks like:

image

The package created by the Wizard uses a hardcoded table name (for the destination) and input file paths (pointing to the source flat file) – so in order to work around this I had to do the following:

- change the hardcoded destination table (which is defined in a Script task) to something generic
- add a second SQL Task which renames the generic table to the value we want from config
- add a configuration for the package (so I can set the source path and the destination table name)

So here is the Control Flow of the package, now modified, from the original rendition:

image

The second task simply calls a system stored procedure to rename our “generic” table (in this example called, tmp) to a name set by configuration:

image image

Note here that I have created a User defined variable which is then set via configuration.  Speaking of configuration, how does one go about establishing an external config file for an SSIS package?  Actually, it’s quite easy..

image

Right click your package designer and select “Package Configurations…”.  Create a new configuration, and use the wizard to specify the location to store the file, and the settings you wish to override via the configuration.  It’s all very simple, I’m not going to go into detail here.  You can see the settings in the screenshot below.

image

You can also set the values of your Data Source components – in the case of the flat file connection manager, this is the ConnectionString property.  Anyhow, hope this entry helps any of you who are lost in overriding SSIS settings using configuration!

R

 

This is part of a series of entries written about Microsoft’s new SQL Azure database service and the Entity Framework v4.

Following on from my previous posts (check them out before continuing) – this article assumes you have followed steps outlined in the  previous posts to create various models and accounts etc.

Continuing along..

Our next step is to create a Dynamic Data website.  If you haven’t come across this yet, it’s most likely because you haven’t been using Visual Studio 2010 or the .Net Framework 4.0.  Recently introduced and compatible with both LINQ-to-SQL and the Entity Framework, this nice site template makes use of the dynamic nature of both LINQ-to-SQL [.dbml] (SqlMetal) and Entity Framework [.edmx] data models.

Continuing within the solution we created in Part 3, we shall now add a Dynamic Data website to our solution.  Open the solution in Visual Studio 2010 Beta 2 and then Right click the solution, “Add –> New Project..”.

Please note: this portion of the solution will also work in conjunction with any other database provider supported by the Entity Framework, not just SQL Azure.  To use a Dynamic Data site all you need is a LINQ-To-SQL or Entity Framework Data Context!  For details, read on..

image

I’ve called the new project “SQLAzure.Application.Web” and it sits in a subfolder off the root folder level for the solution.  Once you click the OK button, you’ll be presented with the Global.asax.cs (or .vb) which, at first, I found a little unusual.  We’ll explore why shortly.

First things, let’s add a project reference to our DataAccess project.  Right click the References solution folder and add the reference.  You might notice that the project already has the appropriate references for the Entity Data objects.  At this point if you compile, it will build without any errors (and if not, you are off to a bad start indeed!).

Configuration Bliss

There are some configuration options which will need to be set.  First, double click on the web.config and copy your <connectionString> values from the app.config located in the DataAccess project.

image

Once you’ve updated the Web.Config, save and close it.  You should now be looking at the aforementioned Global.asax.cs (or vb).  To get us up and running, with the very minimum of configuration (and hassle), we’ll keep the default settings (using the ASP Development Server a.k.a Cassini).  Right click the Web project in the Solution Explorer and “Set as StartUp project”.

Web Scaffolding and other treats

Next, in the Global.asax.cs (or .vb) in the method “RegisterRoutes” uncomment all the code lines, remembering to substitute the value (line 31) “YourDataContextType” with the name of the actual data model context (in our case, SqlDataModelContainer) and you’ll also need to add “using SQLAzure.Application.DataAccess;” at the top of the file.

In the first line, change { ScaffoldAllTables = false }); to { ScaffoldAllTables = true });
We can always customize the data model later to only scaffold specific tables (if we want to).

Once this is all done, you should be able to cleanly compile the project/solution.  Assuming you’ve followed all the steps I’ve outlined, your Global.asax.cs should look like the following:

image

Compile and run the solution (without debugging).  You should notice the ASP Development Server load into the System Tray, and then your default web browser should open and browse to your nice new site.  If you get the following error message:

Server Error in ‘/’ Application.


There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages.

It means you haven’t changed the value on Line 31 from false to true:

image

You *should*, assuming everything has been correctly set, see the following in your web browser, a list of tables in your SQL Azure database!  If you click on the “Albums” link, you should drill into a paginated view of the first 15 records in the Albums table in your nice SQL Azure database in the cloud..

Prepare to be amazed!

image image

Notice the combo boxes in the top left hand corner?  Yes, the site has automatically created those so you can filter the results according to foreign keys in the entiry relationship model – very nice.  Go ahead, select an artist.  I’ve selected “Bob Dylan”:

image

…but wait, there’s more..

That was pretty effortless, wasn’t it?  You want more functionality?  Of course – click on the “Edit” button for the first result.  You’ll be treated to this “details view” of the record:

image

You’ll notice, of course, that again the site has detected all the relationships (including many-to-many) and created combo boxes/checkboxes according to the cardinality of the relationships.  You may edit any of these settings and hit the “Update” button – you are now updating your data in the cloud!

Another nice touch is that you can navigate the relationships (hyperlinked) as well.  All the tables are inter-related (where applicable).  I’ll leave you now to play with your shiny new website, backed with a SQL Azure data store.

The big picture

This was, by far, the easiest website-to-database project I’ve ever wired up, period.  The functionality is uncanny for an out-of-the-box template driven site, and what’s more, if you hook it up to a Server instance (as opposed to SQL Azure) you can run SQL Profiler and see that the queries (T-SQL) themselves aren’t terrible, either.

This is amazing value – foreign key filters, paginated data views, complete with full edit/delete functionality.

However, it also has some additional work which should be addressed in any decent implementation, for example, security and brevity (reducing the footprint of the tables).  We could also do with some optimization and customization!  For example, the screen (1) below could obviously be truncated as the results run right off the screen, and clearly look better in the “Details” view (2).

image image

There are many more things which a “production” quality implementation would require.  I may (or may not) go into details in future posts, but off the top of my head you would need to address any of the following:

- Move from Cassini to IIS (should be done early for serious multi-access websites)
- Add a custom App Pool and Identity
- Strong name the assemblies
- Edit all the templates with a scheme
- Restrictions/reductions in the data displayed in “grid views”
- Optimization of some T-SQL to suit the data model design
- Implementing a security model to restrict read/write/deletion of data
- Auditing changes
- Create an automated build and deploy script

However, this is a great start and would probably suit a number of “intranet” style applications.

Looking ahead

In my next entry, we’ll look at some customizations as well as the technology underpinning this great functionality.  I do hope you are enjoying this series of entries, please leave comments!

Aussie Wine Guy


© 2012 Rob Sanders: Sanders Technology Suffusion theme by Sayontan Sinha
WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera