I found a good walkthrough here on how to setup Microsoft Account Identity, after I’d worked it out myself unfortunately.
Using your local IIS for testing is fine as long as you modify your hosts file to point to a dummy host name as per this SO post.
Make sure when you register your apps base path with Live Connect Developer Centre (GB link) you specify your app’s base path + “/signin-Microsoft”
Knockout options binding not refreshing – Breeze
I’m coding a detail screen with a drop down showing instances of child entities. The user can add a new instance of a child entity and the fields for the new instance appear for editing below. Alternatively the user can select an existing instance from the drop down and edit that.
When the user adds a new child entity, they need the dropdown focussed on the new child entity name and the fields for the new entity displayed for editing below.
The fields were appearing, but the drop down wasn’t refreshing.
Html for drop down:
<div class="col-md-8"> <div class="form-group"> <label for="childItemList">Child items:</label> <select class="form-control" id="childItemList" data-bind="options: childItems, optionsText: 'name',value: $root.selectedChildItem, height:3"></select> </div> </div>
The binding context is a “with:parentEntity” binding. The solution was pretty simple, call “valueHasMutated” on the parent after the new child entity is created:
addChildEntity = function () {
var newChildEntity = datacontext.createChildEntity(parentEntity());
parentEntity.valueHasMutated();
selectedChildEntity(newChildEntity);
},
Import from Excel to SQL Server 2012 – The ‘Microsoft.ACE.OLEDB.12.0’ provider is not registered on the local machine
I hit this one trying to load Excel data into a table on my development server. Most recommend the “Microsoft Access Database Engine 2010 Redistributable” which didn’t work for me.
This one did: “2007 Office System Driver: Data Connectivity Components”
Cannot drop database because it is currently in use
This is a common scenario and there are lots of posts on this. The following works for me:
My database is located on a virtual machine running Server 2012 and SQL Server 2012 under Hyper-V locally on my development machine.
In SQL Server Management Studio In the object explorer pane right click the database and select “Detach” from the context menu. Check “Drop” in the resulting dialog:
Field validation with Knockout and Breeze
I’ve struggled a little with this today. I’m used to knockout validation, and I wanted to make a start using Breeze validation to compare two date fields bound using knockout.
This is what I wanted to achieve:
Here’s a reminder on how to make this work:
I’m basing my app on the nuget package “ProvenStyle.Durandal.StarterKit” v 0.0.7. This is pretty much brand new at the time of writing and I’ve found it to be a great starting point, together with these Breeze packages:
<package id="bootstrap" version="3.0.3" targetFramework="net451" /> <package id="Breeze.Client" version="1.4.11" targetFramework="net451" /> <package id="Breeze.Server.ContextProvider" version="1.4.11" targetFramework="net451" /> <package id="Breeze.Server.ContextProvider.EF6" version="1.4.11" targetFramework="net451" /> <package id="Breeze.Server.WebApi2" version="1.4.11" targetFramework="net451" /> <package id="Breeze.WebApi2.EF6" version="1.4.11" targetFramework="net451" />
As per the great John Papa’s advice in his 2013 course “Single Page Apps Jumpstart” on Pluralsight, I created a datacontext to handle things like the configuration of the Breeze EntityManager. In this code snippet from the datacontext module, I get the metadata and then call a function “initializeCustomValidators” which I’ve called from a module called “model”, ( again recommended by John P).
var primeData = function () { return manager.fetchMetadata() .then(function (data) { utils.getOptionSets(data.schema.enumType, optionSets); model.initializeCustomValidators(manager); Q.resolve(); }).fail(function (error) { Q.reject(error); }); };
The initializeCustomValidators function is just configuring one validator here for “end Date” (“end”). This works at the entity level and supplies a validator object with details of the “end” property:
function initializeCustomValidators(manager) {
// returns an endDateValidator with its parameters filled
var endDateValidator = new breeze.Validator(
"endDateValidator", // validator name
endDateValidationFn, // validation function
{ // validator context
messageTemplate: "'start and end date' must be present, start must be less or equal to end",
property: manager.metadataStore.getEntityType("ClientLicense").getProperty("end"),
propertyName: "end"
});
function endDateValidationFn(entity, context) {
var end = entity.getProperty("end");
var start = entity.getProperty("start");
if (end === undefined || start === undefined) {
return false;
}
return start <= end;
};
var clientLicenseType = manager.metadataStore.getEntityType("ClientLicense");
clientLicenseType.validators.push(endDateValidator);
};
It’s worth stepping through the “getValidationErrors in breeze.debug.js to see how this works, this helped me populate the validator correctly ( specifically looking at how the filter works, see below, this helped to supply the correct parameter for property, above).
proto.getValidationErrors = function (property) {
assertParam(property, "property").isOptional().isEntityProperty().or().isString().check();
var result = __getOwnPropertyValues(this._validationErrors);
if (property) {
var propertyName = typeof (property) === 'string' ? property : property.name;
result = result.filter(function (ve) {
return ve.property && (ve.property.name === propertyName || (propertyName.indexOf(".") != -1 && ve.propertyName == propertyName));
});
}
return result;
};
This suggests one way to listen for changes to the Breeze validation errors connection and update a ko observable to which I can bind. Very handy. I call this in the EntityType post-construction initializer as suggested by Ward:
function addhasValidationErrorsProperty(entity) {
var prop = ko.observable(false);
var onChange = function () {
var hasError = entity.entityAspect.getValidationErrors().length > 0;
if (prop() === hasError) {
// collection changed even though entity net error state is unchanged
prop.valueHasMutated(); // force notification
} else {
prop(hasError); // change the value and notify
}
};
onChange(); // check now ...
entity.entityAspect // ... and when errors collection changes
.validationErrorsChanged.subscribe(onChange);
// observable property is wired up; now add it to the entity
entity.hasValidationErrors = prop;
}
I call it like this from my model class:
function clientLicenseInitializer(clientLicense) {
addhasValidationErrorsProperty(clientLicense);
clientLicense.name = ko.computed(function() {
var orgName = clientLicense.crmOrganisationName() ?clientLicense.crmOrganisationName():'--';
var type = clientLicense.licenseType() ? clientLicense.licenseType():'--';
var hostingModel = clientLicense.hostingModel() ? clientLicense.hostingModel():'--';
return orgName + ', ' + type + ', ' + hostingModel;
});
}
data binding is done as suggested in Ward’s post:
<div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label">Start Date</label> <input data-bind='datepicker:start' class="form-control"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label">End Date</label> <input data-bind="datepicker:end" class="form-control"> <div data-bind="if: hasValidationErrors"> <pre data-bind="text: entityAspect.getValidationErrors('end')[0].errorMessage "></pre> </div> </div> </div> </div>
Breeze 1.4.11 breaks MVC Spa with Durandal 2.0.1 starter kit
I created a Web API/ MVC project in VS 2013 using the SPA template, added the Durandal Starter Kit NuGet package, which pulls in Bootstrap 3, which worked fine. When I added the Breeze Client and Server Package and ran, the app fell over:
‘Could not load file or assembly ‘Microsoft.Data.Services.Client, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′
The version installed in the project was 5.6.1.0
Added the following to web config & this fixed the issue:
<dependentAssembly> <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.1.0" /> </dependentAssembly>
Use server side enums with Breeze in Knockout dropdown binding
I’m using Entity Framework Code First (v6.0.2) for my data layer. Enum support was added in v5.0 and .NET 4.5 must be targeted to use enums.
At the time of writing, my version of Breeze (1.4.11) does not provide enum values in the Breeze Metadata.
When editing or creating entities client side using Breeze, I want to fill dropdowns with options from the server side enums. Breeze populates the client side models it creates with string values for each enum property.
This StackOverflow answer shows how to use the Breeze metadata to create global javascript objects on the client:
I use the “options” custom binding provided by the Knockout library to render my option sets, and most of the time I want the value selected by the user to replace the value of an entity column. Ideally I want a sort of associative array indexed by enum name that I can bind to my views. I came up with this utility function that works for me.
1: var getOptionSets = function(enumSchema, optionSets) { 2: var manageOptionSets = function() { 3: var registerOptionSet = function(optionSetName) { 4: optionSets[optionSetName] = ko.observableArray([]); 5: } 6: , addToOptionSet = function(optionSetName, memberName, memberValue) { 7: var optionSet = optionSets[optionSetName]; 8: if (optionSet !== undefined && optionSet !== null) { 9: var newOptionSet = new optionSetValue(memberName, memberValue); 10: optionSet.push(newOptionSet); 11: } 12: } 13: , parseOptionSet = function(optionSet) { 14: registerOptionSet(optionSet.name); 15: $.each(optionSet.member, function(i, m) { 16: addToOptionSet(optionSet.name, m.name, m.value); 17: }); 18: }; 19: return { 20: parseOptionSet: parseOptionSet 21: }; 22: } 23: , optionSetValue = function(typeName, typeValue) { 24: var self = this; 25: self.name = ko.observable(typeName); 26: self.value = ko.observable(typeValue); 27: return self; 28: } 29: , getEnums = function() { 30: // extract all enums 31: ko.utils.arrayForEach(enumSchema, function(c) { 32: manageOptionSets().parseOptionSet(c); 33: }); 34: }; 35: getEnums(); 36: };
I call this from a function in my view model. “optionSets” is just an empty javascript object:
1: getEnums = function() { 2: return $.Deferred(function(def) { 3: return em.fetchMetadata() 4: .then(function(data) { 5: utils.getOptionSets(data.schema.enumType, optionSets); 6: 7: def.resolve(); 8: 9: }).fail(function(error) { 10: def.reject(error); 11: }); 12: }).promise(); 13: }, This populates my empty optionSets object with an array of optionsets indexed to lists of "optionSetValue" classes. I can then bind to the optionset I need in a view using the "options" binding, where the enum server-side is called "LicenseType" in this case.
1: <div class="form-group"> 2: <label class="control-label">License Type</label> 3: <select data-bind="options: $root.optionSets['LicenseType'], optionsText:'name', optionsValue: 'name', value:LicenseType" class="form-control"></select> 4: 5: 6: 7: </div>
Net result:
Breeze metadata service returns 404
I’m experimenting with Breeze as I’m rewriting a legacy Web Forms app as a SPA using MVC and Web API.
I’m using EF6 and it’s clear Breeze is going to cut out an awful lot of work writing JavaScript model classes, mapping code and data contexts on the client, not to mention filters and projections. I’m going to post a quick guide to setting up Breeze with EF6 ( mainly for myself ) later. I noticed I’m getting 404s on the metadata service Breeze calls if I stop the app in debug mode and then re run.
This Stackoverflow answer appears to have solved this issue.
http://stackoverflow.com/questions/15715701/metadata-query-failed-for-breeze-js
.. Relative URLS seem work just as well. See the url passed to the breeze.DataService object below.
define('app/vm.accounts', [ 'ko', 'breeze', 'app/config' ], function (ko, breeze, config) { var accounts = ko.observableArray([]) , dataService = new breeze.DataService({ serviceName: "/api/licensing/" , hasServerMetadata: false }) , em = new breeze.EntityManager({ dataService:dataService }) , currentAccount = ko.observable() , logger = config.logger , getAccounts = function() { var query = breeze.EntityQuery.from("Accounts") em.executeQuery(query) .then(function(data) { accounts(data.results); }) .fail(errorLoading); } , errorLoading = function(error) { logger.error(error.message, "Loading failed"); }; return { accounts: accounts, }; });
Configure 1:1 relationship in code first
When I tried to load some test data into a database I’d just created in code first I hit the following error:
“a dependent property in a referential constraint is mapped to a store-generated column. column ‘id’
Example loading code:
1: myDbContext.Accounts.Add( 2: new Accounts{ 3: Name = "Account #1", 4: ReferenceData = new Entity2 5: { 6: RefLocator = "Ref #1" 7: } 8: }) I eventually configured the POCO classes for the two entities as follows:
1: namespace Test.Model 2: { 3: [Table("Account")] 4: public class Account 5: { 6: [Key, ForeignKey("ReferenceData")] 7: public Guid Id { get; set; } 8: public string Name { get; set; } 9: public ReferenceData ReferenceData { get; set; } 10: 11: } 12: [Table("ReferenceData")] 13: public class ReferenceData 14: { 15: [Key, ForeignKey("Account")] 16: public Guid Id { get; set; } 17: public string RefLocator { get; set; } 18: 19: 20: } 21: } I tend to prefer using attributes to the fluent mapping when writing EF classes. Hopefully this saves someone a little time.

