Vince Plaza's Blog

...Microsoft .NET programming ideas and samples

Sort on the last name in full name field using T-SQL string functions

Written by Vince Plaza on October 20th, 2009

A friend asked me if it was possible to sort on just a portion of a text field, but not necessarily the first word. For example, lets say you have a full name field that is formatted  as ‘[FirstName] [LastName]‘. There is a simple, if not flawless, way to do this with T-SQL string functions. First, you need to generate a small list of names to work with. I will use a table variable to do this. It is easy to spin up and is disposed of as soon as the query is done running.

declare @MyNames table (FullName nvarchar(20));
insert @MyNames
values ('Betty Ferguson'),('Sam L Jackson'),('Horatio Alger');

Note that I used the much simpler SQL Server 2008 syntax to add the names. If you are using SQL Server 2005, you will need to add the names like this:

insert @MyNames
values ('Betty Ferguson');
insert @MyNames
values ('Sam L Jackson');
insert @MyNames
values ('Horatio Alger');

Since you can’t control people adding a middle initial, I will find the last name by counting the number of characters starting from the right before I find a space character. The best function to use for this is charindex.

select charindex(' ', FullName) as 'LastNameLetterCount' from @MyNames;

The problem is that the charindex function counts from the left. In order to count from the right, I need to flop the text over by using the reverse function. This function will take a string of characters such as ‘My dog spot’ and return it as ‘tops god yM’. I also subtract 1 so that I only return the length of the last name, not the last name and the space.
Click to continue »

“Could not find default endpoint” error with Silverlight, WCF, and MVVM

Written by Vince Plaza on October 16th, 2009

I have done this a couple of times, and so thought I would log it so that I remember next time. When I set up a Silverlight project using the MVVM pattern, I prefer to make separate projects for the View and ViewModel sections. I then create a service reference to my data service (WCF) in the ViewModels project. If you have tried this, you may have received a “Cannot find ‘ServiceReferences.ClientConfig’ in the .xap application package.” error message the first time you run the solution. This is caused by the Views project not containing the ServiceReferences.ClientConfig file created in the ViewModels project. No problem, just drag a copy from the ViewModels project into the Views project and you are set to go.

Where I get into trouble is when I reconfigure the WCF service or reference and forget to update the client config file I dragged into the Views project. The error message that gets generated is similar to:

Could not find default endpoint element that references contract ‘ServiceReference.Service’ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

Well, I was much happier with the error message telling me the file was missing. With this new message, I end up opening the client config file in the ViewModels project like 6 times looking for a typo, but of course it was auto generated while making the service reference, and so is fine. What I need to do is to replace the ServiceReferences.ClientConfig file in the Views project, and then run the application again. Problem solved.

Great post on using Dependency Properties with custom user controls in Silverlight

Written by Vince Plaza on September 10th, 2009

I was stuck on implementing data binding with custom Silverlight controls, and found this post to be a lifesaver: http://geekswithblogs.net/PeterTweed/archive/2009/07/05/taking-advantage-of-data-binding-in-silverlight.aspx

Good reference on SSIS tuning techniques

Written by Vince Plaza on September 2nd, 2009

I am troubleshooting a memory allocation issue with an SSIS package and came across the following article. It is a couple of years old, but still very relevant:
Integration Services: Performance Tuning Techniques

Missing SQL Server 2008 templates in Visual Studio Team System 2008 Database Edition

Written by Vince Plaza on September 1st, 2009

I have a new install of Visual Studio Team System 2008 Database Edition that is updated to SP1. I went to make a new SQL Server 2008 project and noticed that there was not a template available. I thought this was odd as I have SQL Server 2008 installed locally. After a little research, I was pointed to the following update: Microsoft® Visual Studio Team System 2008 Database Edition GDR R2. After closing VSTS and installing the update file, I restarted VSTS and the templates were there.

Use a view to encapsulate business logic and reduce code

Written by Vince Plaza on August 28th, 2009

This post adds to a previous post:Working with additive values in tables with different levels of detail

In the last post, we used a subquery to only show the latest value in a table that has a time component. The table holds an employee’s pay rate history and includes a “RateChangeDate” field. Although our use of a subquery makes sense, over time it will become tedious to type the same code every time we want to show an employee’s current pay rate. In addition, the use of the subquery adds risk to the quality of our application. The business logic represented by the subquery will need to be tested every place the subquery appears, increasing the odds for an error down the road.

Since we know the subquery is a handy block of code, we will take advantage of a common database feature called a “view”. In a nutshell, a view is a persistent select query that is given a name and can be referenced just like a table. With a view, business logic can be defined once and shared between future queries and even between programmers.

Taking our last example, lets turn the subquery for the latest pay rate and turn it into a view. Note how we use the “create” statement just like when making a table.
create view HumanResources.CurrentEmployeePayrateView
as
select    e.EmployeeId
          ,eph.Rate as Payrate
from      (
               select   EmployeeId
                        ,max(RateChangeDate) as RateChangeDate
               from     HumanResources.EmployeePayHistory
               group by EmployeeId
           ) e
inner join HumanResources.EmployeePayHistory eph on e.EmployeeId = eph.EmployeeId
                                    and e.RateChangeDate = eph.RateChangeDate

Click to continue »

Working with additive values in tables with different levels of detail

Written by Vince Plaza on August 25th, 2009

Downloads: Sample Database

There are times when you need to perform a calculation on values stored in two different tables. The first value is stored in a summary level table, and the second is stored in a detail table. I will use the Adventure Works employee tables to demonstrate.

Let’s say you need to calculate the accrued vacation time for your employees that exceeds the company limit of 120 hours and derive the total liability to the company in terms of dollars. Using the Adventure Works database, that would require three tables: HumanResources.Employee, Person.Contact, and HumanResources.EmployeePayHistory. To start, we know we need to identify the employee so we include the EmployeeId field from the Employee table and the LastName and FirstName fields from the Contact table. Make sure and include the schema when declaring the tables, as this is required for any schema that is not ‘dbo’. This is a good practice anyway. Also, note the use of the table aliases ‘e’ and ‘c’ to save typing and add clarity.

select      e.EmployeeId
            ,c.LastName + ', ' + c.FirstName as EmployeeName
from        HumanResources.Employee e
inner join  Person.Contact c on e.ContactId = c.ContactId

Click to continue »

Update EF Model Properties to Match Conceptual Model

Written by Vince Plaza on August 13th, 2009

Before reading this post, read the previous post: Create an Adventure Works Entity Framework Model

Now that you have created an Entity Framework model for the Adventure Works database, you can begin to update properties to align the model with your business. In this example, I will change a few simple table properties to support future samples that use the model.

To start, open the AdventureWorks.edmx file in the Visual Studio GUI design tool. Select the SalesOrderDetail table by clicking on the table just below the table name in the header. The properties pane should look like this:

(click to enlarge)

(click to enlarge)


Click to continue »

Create an Adventure Works Entity Framework Model

Written by Vince Plaza on August 11th, 2009

It is easy to create a simple Entity Framework model using the Adventure Works SQL Server database. I will use a WPF Model View project as my container. To start, create a new WPF Model View Application as described in this posting:

Right click on the Model folder in the Solution Explorer, select Add and then select New Item from the context menu.

(click to enlarge)

(click to enlarge)

Select the ADO.Net Entity Data Model template and name it AdventureWorks.edmx.

(click to enlarge)

(click to enlarge)

Click to continue »

Resetting metadata references in Entity Framework connection strings

Written by Vince Plaza on August 9th, 2009

I needed to move a couple of Entity Framework edmx files into a new project directory. Although I used the “add existing item” functionality of VS 2008, I still managed to corrupt the connection string entries in the App.config file, likely by using a subfolder. This led to a string of the following error message when I tried to run the app: “Unable to load the specified metadata resource.” After searching for a fix, I found that by toggling a property of the edmx file, it is possible to realign the connection to the new project.

To do this, open the model in the Visual Studio GUI tool for editing edmx files. Use your cursor to select any point in the background of the diagram where there is not an object. If you look at your properties pane, you will notice a property for the diagram called “Metadata Artifact Processing”.

Screenshot of VS2008 designer and properties pane

Screenshot of VS2008 designer and properties pane

 

The default value for this property is “Embed in Output Assembly” and this appears to be accepted as the best default practice. To repair your metadata reference, though, change the value to “Copy to Output Directory” and build the project. Now set the value back to the original “Embed in Output Assembly”.  Build the project again and you should be set to go. As this updates the App.config file, don’t forget to copy the updated entries to other projects that rely on the setting at run time.