Entity Framework Stored Procedure Instructions

This is a how-to on getting Entity Framework (EF) version 5 and 6 to include stored procs and how to consume the resulting entities in code.

  1. In the EF designer choose Update Model From Database.
  2. When the page to Choose Your Database Objects and Settings comes up which allows one to add new tables/views/stored procs, select the stored proc of interest. Remember the name for the resulting data mapping entity will be the name with the extension _Result.2015-06-12_19-10-39
  3. Once the wizard is finished EF will contain the stored proc in the Model Browser. The model browser can be displayed by right clicking the EF design surface and selecting Model Browser.2015-06-12_19-51-20
  4. Here is an explanation of what has happened.
    (1) You have added the stored proc into the Stored Procedures / Functions as an item of interest.
    (2) EF has created a function import of the stored proc and placed it into Function Imports.
    (3) If EF was able to determine the *result set entity* it will most likely be in the Complex Types folder.
  5. If the mapping has gone right you should be able to call the stored proc off of the EF context in code and it will return a list of the complex type xxx_Result. If it works you will know it, but there could be problems with the mapping.

Mapping Problems and How to Resolve

  • One can delete at anytime the any object in the folders of 1/2 or 3 shown above and regenerate or create a custom mapping. Don’t be afraid to delete.
  • Sometimes very complex stored procs will not divulge the right mapping of the entity in the result set and the resulting complex type will cause failures. One way around that is to create a faux data return in the stored proc which leaves no ambiguity for Ef.
          1. In the database change the stored proc as follows.  Comment out the meat of the result select and replace it with a one-to-one column stub faux select such as this example: “SELECT 1 AS ResultId, ‘Power1’ AS GroupName, ‘Test’ AS Description”. Note to be clear you will need to match every column and name.
          2. In EF’s Model Browser delete all things associated with the stored proc in folders 1, 2 and 3 above.
          3. Regenerate all by usingUpdate Model From Database.
          4. Check the results.
  • If the above steps fail one can always create a function mapping by hand. Be careful not to create duplicates, if so delete all and start over.
        • Open up and find the stored proc you inserted into folder #3 above. Right click and selectAdd Function Import…2015-06-12_20-09-09
        • One can get the column information, change items on the above screen; it is trial and error.
        • You will need to play around with this until you have the right columns for your function import. Be wary of numbered copiesof the complex types which may be created from the mapping.

Remember to reset the stored proc back to its original state instead of the faux stub mentioned.



Entity Framework Cascading Deletes; Set it from the database.

To achieve cascading deletes, one must specify the cascading deletes on the FK relationships from the top level table in the database. The default is not to cascade.

Here is the visual Process in SQL Server Management Studio.

  1. Select the top level table which will handle the delete and right click.
  2. Select design mode.
  3. Right click any row in the design mode.
  4. Select Relationships.
  5. Find all the FK relationships and set them to cascade.

Then in Entity Framework update the edmx file after these changes are made so entity framework knows about the cascading constraint.  Once all this is done a cascaded delete is possible using Entity Framework.





Visual Studio: How to Resolve TestWindowPackage.Initialize Failure

I began to receive the error message box in Visual Studio after a restart from an install of an unrelated to test Visual Studio plugin (which I have used in the past):

The ‘TestWindowPackage’ package did not load correctly.  … examining the file … AppData\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml

Looking at that log showed these errors:

TestWindowPackage.Initialize failed with exception … System.InvalidOperationException:

Loading MEF components failed with the following exception:
The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

No exports were found that match the constraint:
    ContractName    Microsoft.VisualStudio.TestWindow.VsHost.PackageContainer
    RequiredTypeIdentity    Microsoft.VisualStudio.TestWindow.VsHost.PackageContainer


To resolve the issue I did step 1 and 2 but am showing step 3 in case it helps.

  1. Close all instances of Visual Studio.
  2. Delete all files in AppData\Local\Microsoft\VisualStudio\12.0\ComponentModelCache Note that directory is not found in Roaming as the activity log file, but in Local.
  3. Restart, if that doesn’t work then start over with step 4.
  4. From a Visual Studio Command Line do this operation: devenv /setup /ResetSkipPkgs See (/Setup (devenv.exe)) for more information.


WPF : A Future Xaml Home For LOB and IE

stockxpertcom_id21167841_jpg_96cea7cca529ddc8485f5b21de62e2f6I was recently asked to provide my humble opinion on the future of WPF , literally how it should it be charted going forward. This is my utopian vision for WPF going forward.

I am going to answer that question as if I had received the the Wonka Golden Ticket and was able to go to Microsoft and ultimately become a sort of  Scott Gu of  Microsoft and direct the future of WPF, here is what I would order the Umpa Lumpas to do. To be clear, I only use the term Umpa Lumpa to mean a hard diligent worker at Microsoft and not any short and blue person or a minion doing one’s evil bidding; heck a combination of both but better paid. 

Before one can come to grips with my future utopia vision of what WPF would be, one would have to look into the past to see what Xaml technologies has provided the the Line Of Business (LOB) developer. For that is what I am, a Line of Business developer who gets paid to create business applications to the highest bidder. My ego is inflated enough to think that my services actually go to a “highest bidder” , but let us not touch that fourth wall of  my reality ok?

Where Have You Been Xaml?

Currently a LOB developer is basically in charge of bringing data and all related business rules to the corporate environs. Historically that vehicle has been Xaml used in WPF, Silverlight and just recently Windows 8 tablet.  All of them use subtle flavors of Xaml to achieve that work. Xaml is great because through the use of MVVM and a kick ass way of leveraging a graphical based solution to displaying that data, it has provided the developer with a rich toolset bar none in the industry. Let me repeat that, bar none people.

What is my anecdotal evidence?

I was tasked with bringing such a graphical solution to a cable industry partner. To anyone who is not aware of the cable industry, it is, now, a few providers spread out over the country, if not the world, and they are frankly a Java shop. The Oracle flag flies over their realm and very few if any .Net projects are done within the differing companies.

With that backdrop in mind, Java, the small company I ended up working for was seeking to bring tools to the major cable vendors. One of the tools needed a graphical front end to allow for a back and forth way of editing business related data for their end clients. There was no Java, still isn’t, technology which could fill that gap, only a Xaml solution in the form of the Silverlight tool provided the best working solution and they took it.

Take out the Silverlight of the last story and keep in mind Xaml and WPF. For what they needed was a way to bring a rich client experience to the end user and there was a viable Xaml based solution available to them.

Xaml As a Means and Not an End

The LOB business developer needs to be able to bring that graphical data experience to the table. “What about the Javascript solutions out there?”, one might ask? Javascript and HTML 5 solutions have come a long way, but frankly any developer who has spent anytime dealing with the non strongly typed environment comes away with a bad taste in their mouth due to the unwieldy nature of any app which grows past a certain size and cannot be managed.

Javascript solutions are frankly unmanageable at a certain point and any developer knows and dreads that.

If only businesses could understand that WPF in a managed language is the best use of large scale applications and providing a rich, yes rich, client experience to the end user, it would go a long way.


Very few businesses want to install, and update applications to the end user. Period end of story.

That is why Silverlight to both the developer and businesses was so appealing. Not that it would work cross browser or anything else, just that it provided a vehicle to supplant IT and go around having to install applications on locked up corporate PCs.

From the cloud came a solution to avoid the IT department and it was, and still is, the best way to bring data and more critically the viewing of said data to the corporate person.

WPF Future

That leads me here, to my goal of WPFs future. If I could provide the corporate end user with a way to bring a rich graphical experience without having to install it, that would be my goal.

How would I achieve it?

I would bake a WPF visual experience into IE. Where IE under certain approved circumstances would provide a gateway to a rich client experience. As a developer I don’t care what IE has to do, just that it would allow me to interact with a client at the end of the tunnel from the server without having to get my feet wet in Javascript and HTML 5.

As a LOB experience, I don’t care that this it would not be available outside IE; because my target audience is required to to have IE for this business purpose. In as much as we provide a PC, not a Mac to the corporate user, we provide a specific browser.

If I could provide the best of WPF, in a better browser experience (not Silverlight) that is what I would be the task the Umpa Lumpas would create.

WPF Realities

The reality is that someone like a Scott Gu would have to champion such a project at Microsoft. This person would have to sell the idea of a managed GUI environment (similar to C# being managed and not C++)  to the browser based LOB customer as a WPF Future solution.

But I truly believe it would be a game changer in the business world…just that I don’t have the golden ticket and my voice is just one out here on the Western Front of the internet at this time.


Tags: ,

WCF: Creating Custom Headers, How To Add and Consume Those Headers

When creating a C# WCF service (version .Net 3.0 and above) there may be a value in identifying the clients (consumers) which a web service is providing operational support to. This article demonstrates in C# and config Xml how to have clients identify themselves and pass pertinent information within the soap message’s header. That information in turn will be processed by the Web Service accordingly.

Client Identifies Itself

The goal here is to have the client provide some sort of information which the server can use to determine who is sending the message. The following C# code will add a header named ClientId:

var cl = new ActiveDirectoryClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientId",       // Header Name
                                                   string.Empty,     // Namespace
                                                    "OmegaClient")); // Header Value
cl.Endpoint.Address = eab.ToEndpointAddress();

// Now do an operation provided by the service.

What that code is doing is adding an endpoint header named ClientId with a value of OmegaClient to be inserted into the soap header without a namespace.

Custom Header in Client’s Config File

There is an alternate way of doing a custom header. That can be achieved in the Xml config file of the client where all messages sent by specifying the custom header as part of the endpoint as so:

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
                <binding name="BasicHttpBinding_IActiveDirectory" />
          <endpoint address="http://localhost:41863/ActiveDirectoryService.svc"
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IActiveDirectory"
              contract="ADService.IActiveDirectory" name="BasicHttpBinding_IActiveDirectory">

The above config file is from a .Net 4.5 client.

Server Identifies Client Request

Finally the web service will read the custom header and distinquish between any WCF client and process it accordingly.

var opContext = OperationContext.Current; // If this is null, is this code in an async block? If so, extract it before the async call.

var rq = opContext.RequestContext; 

var headers = rq.RequestMessage.Headers;

int headerIndex = headers.FindHeader("ClientId", string.Empty);

var clientString = (headerIndex < 0) ? "UNKNOWN" : headers.GetHeader<string>(headerIndex);

Tags: ,

C#: ToString To Report all Properties Even Private Ones Via Reflection

At some point one needs to view all the properties of an instance outside of a debugger such as for a unit test reporting the results or possibly a console application informing its status to the output. To achieve the results one overrides ToString() and by hand writes the information of the instance’s properties and their values to the output string. This can become cumbersome if the class instance is changing or when one realizes that the time ratio of creating such a reporting operation verses the size of what is being reported can lead to valuable time taken away from the developer.

This article demonstrates a C# extension which will take any class instance and report any non null properties as well as any string lists. The goal of the report is to provide information on the standard properties (string, int, datetime, etc) as well as string lists and ignores any  complex objects. Also provided is the ability to show the non-public properties.

For the resulting visual list, the code lines up the output report in key value pairs where the largest character count key name (the property name reported) will be spaced out along with all other names.

Here is an example result of a class instance with differing properties. Note that MemberOfAsList is a List<string> property which internally splits out the property MemberOf string (by its comma) into a list. This extension shows the list as a string.join of ", ".

DistinguishedName : CN=Write Frank,OU=Test,OU=Acme Industries,DC=amce-co,DC=acme,DC=net
CommonName        : Write Frank Lloyd
MemberOf          : CN=2042_Identity,CN=UserIdentities,CN=AlphaVision,DC=acme-co,DC=acme,DC=net
MemberOfAsList    : CN=2042_Identity, CN=UserIdentities, CN=AlphaVision, DC=acme-co, DC=acme, DC=net
otherTelephone    : 303-555-555
Name              : Wright Frank
WhenChanged       : 3/17/2014 9:04:06 PM
LogonCount        : 0

Extension Method

The following is an extension method whose goal is to reflect the type being passed in, determine the sizing of the data for output and then reports the properties each on a different line. String lists values are specified by a , (comma and space) separator between each value.

public static string ReportAllProperties<T>(this T instance) where T : class

    if (instance == null)
        return string.Empty;

    var strListType = typeof(List<string>);
    var strArrType  = typeof(string[]);

    var arrayTypes   = new[] { strListType, strArrType };
    var handledTypes = new[] { typeof(bool), typeof(Int32), typeof(String), typeof(DateTime), typeof(double), typeof(decimal), strListType, strArrType };

    var validProperties = instance.GetType()
                                  .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                  .Where(prop => handledTypes.Contains(prop.PropertyType))
                                  .Where(prop => prop.GetValue(instance, null) != null)

    var format = string.Format("{{0,-{0}}} : {{1}}", validProperties.Max(prp => prp.Name.Length));

    return string.Join(
             validProperties.Select(prop => string.Format(format, 
                                                          (arrayTypes.Contains(prop.PropertyType) ? string.Join(", ", (IEnumerable<string>)prop.GetValue(instance, null))
                                                                                                  : prop.GetValue(instance, null)))));


public override string ToString()
    return ( this.ReportAllProperties() );

Test & Results

var test = new MyClass("Admin") { Name = "Omegaman", 
                                  ID = 1,  
                                  StartDate = DateTime.Now,
                                  AccessPoints = new List<string> { "Alpha", "Beta", "Gamma" },
                                  WeekDays = new string[]{ "Mon", "Tue" }

 Console.WriteLine (test.ToString());

Name         : Omegaman
ID           : 1
Role         : Admin
AccessPoints : Alpha, Beta, Gamma
WeekDays     : Mon, Tue
StartDate    : 3/18/2014 12:16:07 PM


public class MyClass
    public string Name               { get; set; }
    public int ID                    { get; set; }
    private string Role              { get; set; }
    public List<string> AccessPoints { get; set; }
    public string[] WeekDays         { get; set; }    
    public DateTime StartDate        { get; set; }

    public MyClass(string role)
        Role = role;

    public override string ToString()
       return ( this.ReportAllProperties() );




Tags: , , , ,

Azure Build: How to Enable A Build Definition in Visual Studio


In Visual Studio 2013 one may run into this error  when getting a build running with Windows Azure online TFS.

Team Foundation Error

TF215079: The build definition NexusTFS_CD is disabled. Enable the build definition and try again.

TFS Error

Here are two things to look for/ to do. But both of the items require one to bring up the build definition file (internally named xaml (not the wpf kind)) by (in Visual Studio) right clicking on the build definition which shows the disabled build with an x in the icon in the Team Explorer, Build section:


  1. There may be build problems other than the build definition is disabled. Select the Process section by clicking it and look for any triangle warning signs in the window/tab which opens. If the triangle icon is there, that may mean that something is missing and needs your attention. If in TFS, your Team Project Collection has multiple solutions, the actual solution to build may not be set. Set it in the Projects section.
    Yellow Warning
  2. To enable the build definition go to the General settings and and change the Queue Processing  from Disabled to Enabled.


If everything is a go, the icon should change after you save the xaml file. Queue a new build and run.



Tags: , ,

Azure: Failed to Create Web Site in Visual Studio Using Azure

If you have a valid azure account but receive this message in Visual Studio 2013 (or 2012 with the Azure toolkit installed) while trying to create a website

This subscription is not registered to use the following resources: Website. The remote server returned an unexpected response: (400) Bad Request.


Here are the steps to fix and or pinpoint the issue.

  1. Log into to manage the account Azure Portal (Opens in new window). Is this account the same one that is tied to Visual Studio?
  2. Find the WebSites section along the left hand side.
  3. Create a new website.

If you are able to do those steps, you have eliminated the sign on issue (wrong account) and the general ability to create websites in Azure.

  1. Try to create a website again in Visual Studio using the account specified above used to log into Windows Azure Portal.

If it still fails at this point, trying installing the latest Azure Toolkit (2.2 of this writing) into Visual Studio. Tell me what you have run into…I would like to hear.


Tags: , ,