Learn Breeze | John Papa

John Papa

Evangelist on the loose

Learn Breeze

...

It is no secret that I am a huge fan of Breeze as I use it as a core component in my web applications and I use them extensively in my SPA courses. And now the first in depth training on Breeze has hit Pluralsight. My friend Brian Noyes recently published his Building Data-Centric Single Page Apps with Breeze course and it truly is tremendous!

Brian’s course covers the full gamut of what Breeze can do for you, such as formulating rich queries on the client side (filtering, sorting, and paging) that get executed on the server side, saving changes in batches, and validating changes on the client side. In modules 7 & 8 Brian dives into validation and shows how Breeze can automatically create some client validation rules for things like type checking, required fields and string length. He then shows how you can use other built in client validation rules such as phone, email, and regular expression checking as well as creating custom validation rules. The course covers Breeze, which works with Knockout/Durandal and Angular. Brian uses Knockout, but the Breeze concepts and syntax is all the same either way you want to go.

Validation

The following code snippet shows how you can hook up built-in validation rules as your Breeze EntityManager is initialized when your main page/app loads:

var app = app || {};

function initValidation(em) {
    // Add phone validation rule 
    var store = em.metadataStore;
    var userType = store.getEntityType("User");
    var phoneProp = userType.getProperty("phone");
    phoneProp.validators.push(breeze.Validator.phone());

    // Add email, credit card, and URL validators
    userType.getProperty("email").validators.push(breeze.Validator.email());
    userType.getProperty("creditCard").validators.push(breeze.Validator.creditCard());
    userType.getProperty("webSite").validators.push(breeze.Validator.url());

    var userKeyValidator = breeze.Validator.makeRegExpValidator(
        "userKeyVal", 
        /^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$/, 
        "%displayName% '%value%' is not a valid GUID");

    userType.getProperty("userKey").validators.push(userKeyValidator);

};

app.em = new breeze.EntityManager("breeze/ValDemo");

app.em.fetchMetadata().then(function () { initValidation(app.em); });

Here you can see the demo app running with a validation error toastr alert highlighting the error. By using the manual validation invocation that is demonstrated in module 8, you can block dismissing the dialog if there are any validation errors. You can also do async server calls to execute server validation rules, get back the errors and act on them or display them on the client side, all also discussed and demonstrated in the validation modules.
val-demo-image

This year (2013) I will be releasing a course that shows how to use many of these concepts in a powerful SPA built with Angular and Breeze. So I recommend watching Brian’s course in preparation for my upcoming one!

tags: breeze javascript pluralsight SPA
  • Rusty

    John, when is your course coming out? It is October already!

    • johnpapa7

      Rusty – Glad you are excited! I’m not sure, it usually takes a few days or a week or 2 to get through the final edits.

  • faber75

    are you leaving Knockout for Angular ?

    I know that Knockout != Angular and should be Durandal for Angular but… you know what i mean.

    I see you writing much about Angular and … a long time ago a saw a similar struggle with jQuery-Scriptacolous-MooTools.

    I want to choose the right horse :)

    • johnpapa7

      faber75 – Nope. I do both Durandal/Knockout and Angular. I have 4 courses that use Knockout already, and this is the first Angular one. Both horses run well :)

      • faber75

        Thanks. Glad to hear it, i’ll keep my knockout close.

        Still scared when there are many horses around :)

        • John

          faber75 – Understood :) Knockout is still excellent and very much in use and being evolved. KO v3 is here. But the momentum seems to be behind Angular right now. Things change, things shift, so I keep my fingers on the pulse of the leaders which are, IMO, Knockout (with Durandal), Angular, and Ember.

        • tiagor

          Why would you be scared? Read “Javascript: The good parts”, by Douglas Crockford and “Javascript Patterns” by Stoyan Stefanov. If you know JavaScript, you won’t have any reason to be scared.

          • faber75

            Thanks tiagor, i own the Crockford book and it’s one with the highest proportion of value * page i have (some parts are still hard for me, to be honest).
            I’m scared more on the pratical side than on the technical one, i mantain 5-7-10 yo apps and the less variations i have to mantain, less frequently i have to rewrite them or bang my head with a browser incompatility and no support available.
            If today i had to mantain a 4 yo app with scriptaculous/ironruby/other less succesful tools i would be worried/scared, at the end there will be a winning horse and i try to bet on the winner, if possible.

          • tiagor

            I get what you’re saying. I think the same way, unconsciously.

            My favourite horse is AngularJS, for sure. I find it cleaner, more powerful, very intuitive, and “respects” HTML a lot more. Guess what? I was “scared” to find it too hard, but it’s not. – it’s still missing lazy loading of controllers (a huge drawback in my opinion) – but you can have it, using RequireJS.

            Think about the huge impact of someone like John… he started using Durandal (I had never heard about it), he did a course on it – and all of a sudden thousands and thousands started using it as well (even on corporate apps).

            I think KnockoutJS will stay for a long time (specially because it’s very common in the .NET stack, in companies, etc). I certainly use it a lot, on several projects while contracting.

            Take John’s next course… maybe you’ll switch horses :)

          • Tolga Yaramis

            I agree with you about the huge drawback, missing built-in requirejs support in angularjs. I hope, AngularJs solve this problem in comming version.

  • Josh

    One thing that has worried me about breeze is that it seems to basically leak your database into your user interface. This is fine when you have small projects or really simple business logic, but it’s not the case at all when you have more complex software.

    It’s certainly true that you don’t have to use breeze this way. You could use it so that you have a clean separation, but this framework was not designed for that story at all. It appears to basically try to be a thin layer over a server side entity framework context, and I just cannot wrap my mind around how that is a good thing. It seems like many people figured out that this was really bad just when you are doing straight MVC (i.e. not a SPA). Never-the-less, your courses have been very valuable to me and my team as we’ve learned much of this technology.

    • johnpapa7

      Leak? Not sure I agree with that term. If you choose to use Breeze with EF you still need to expose the data via web service methods (via Web API perhaps) to the client. You get to choose what is exposed to the client. You can create your own “views” into this information, add security, intercept calls and run business logic, and more. Breeze is very flexible like this.

      if you feel otherwise, I’d love to know how specifically and what you would expect it to do. The breeze folks are always listening for ideas on how to make it work with less friction. So please let them know (better than telling me). They do listen.

      I would not hesitate for a second to use Breeze in a large application. In act, I think Breeze makes the most sense there since it adds so much that would be painful in a large app (sharing of data, different data contexts, caching, local storage serialization and re-consitution, validation, and more).

      While I agree it appears like breeze and EF just do magic at first glance, when you dive in (as Brian’s course does) you will see how flexible it really is. I have been able to customize a lot for my apps and it has helped make them more powerful and saved me time/money.

      I do appreciate your feedback and I highly recommend contacting the breeze folks to tell them your concerns. I’d love to see what comes of that. If you still feel that way afterwards, perhaps I missed something. It doesnt do everything for certain, and there are areas I have asked to be improved (like making it easier to get metadata for non EF back ends).

      And thanks for commenting and for the compliment on my courses :)

    • Ward Bell

      Josh – I think I know what you mean.

      The server setup in samples and demos tend to show virtually unobstructed client access to the database and JS models that mirror the ORM (and the DB tables) almost exactly. Breeze also ships with tooling that can reinforce this impression when used blindly,

      But you have a phrase that sticks in my craw: “this framework was not designed for [a clean separation] story at all”

      Where do you get that? For months we’ve been striving to show that the server (aside from the optional OData Query support) is mostly incidental and that BreezeJS has no commitments to the server technology … as demonstrated by the NoDb, ESPN, Edmunds, Mongo, and Ruby samples.

      Sure we show you a server-side “productivity path” (Visual Studio, Web API, Entity Framework) AND push-button server scaffolding. But that’s mostly to get you going quickly so you can focus on the client. Because Breeze is most interesting for its value on the client: querying, caching, self-assembling model object graphs, change tracking, change notification, validation, and change-set save. You’re supposed to evaluate the benefits (and costs) of those client-side features … not the server.

      Let me push back a little. I’m a mite suspicious of your critique … and I’ll tell you why. For years people have been decrying the “leaky abstraction” of ORMs and web APIs. Some misperceptions of Domain Driven Design and CQRS have energized this “critique”.

      I’m sympathetic to a point. But I’d be more sympathetic if I saw some examples that didn’t just turn around and DO THE SAME THING. Instead, in article after article (book after book) I see the same ToDo, Customer, Order, Product models that we’re building in our samples. They are no less anemic; most of them have not a shred of business logic. Then pile on a DTO layer with a CustomerDTO that looks exactly like Customer. More work + no actual value = YAGNI.

      Yeah, I know these are just demos showing me **how** to follow the patterns to get clean separation. I’m supposed to take it on faith that you will write clean code in practice? Well why do you deny Breeze the same argument? Clean separation, while not shown, can be yours if you apply yourself.

      I’m not ducking the server-side issues. I think the “productivity path” and the scaffolding are great places to start … but you can’t stop there. You can and should refactor for separation of concerns. You should prevent clients from partying on your database by layering in security and validation. And you use DTOs where they add value; the client doesn’t know if the object on the wire is a DTO or not. Maybe the Breeze team can do a better job of showing you how.

      Or don’t use the “productivity path” at all.

      Here’s the deal. We encourage you to build the server the way you want to do it. If you like the productivity path, great … you can be as clean, maintainable, secure and performant as you choose to be.

      Don’t trust that path? That’s cool too. BreezeJS does not care.

      We are eager to learn how we can demonstrate these points more clearly. And we want to do our best to minimize the friction between your Breeze client and the server of your choice. Write some code, tell us your stories, and send in your suggestions. BreezeJS is a community driven, open source project. Let’s make it great together.

      • Josh

        Ward, first thank you for your very thoughtful reply. Rereading my initial post, I definitely regret the wording and I think I sound much more combative than I meant to be (which is none). First let me be clear – I’m not claiming to know a lot about Breeze. Only from a half day or so poking around in it. I probably should have stated something along the lines of “my understanding of breeze is limited and I’m concerned about how it appears to leak your database into the UI layer. Perhaps watching this new course will allay my fears.”

        The querying functionality is a big code smell. I know that is only a portion of the library, but it is heavily emphasized on the examples home page. Queries like in those examples seem very inappropriate for the UI layer. Perhaps I’m reacting too hard against some of the legacy code I’ve been dealing with, but that is my major concern. I know there are lots of other parts of the framework. Right now I’m mainly using amplifyjs for most of those features and it seems to work well, but I’m always on the lookout for something better and will be learning more about breezejs.

        • Ward Bell

          No worries, Josh.

          I personally see many advantages to the client query facility when used properly (that is, when you take appropriate steps on the server to guard against abuses). And I wouldn’t expose every model type as an IQueryable. I expose the types where it is safe and convenient to do so.

          But I don’t mind at all if you are completely uncomfortable with a generalized approach to client-defined queries. Many folks are and for such reasons they don’t like OData either. I think Breeze has plenty of value for these folks too.

          I’m not quite sure what you mean by “the UI layer”. Do you mean the SPA client or just the presentation layer on the client? I don’t like any querying – or any persistence activity – in the presentation layer. But I have no problem with a client-side service component that encapsulates persistence concerns on the behalf of the presentation layer. That’s what John’s “DataContext” or “DataService” is about.

          I think amplifyjs is a marvelous library … but last I checked it offered nothing in the way of “caching, self-assembling model object graphs, change tracking, change notification, validation, and change-set save” which are the Breeze features I highlighted.

          All the best,
          Ward

  • simon

    And please please John. Put the authentication with angular. It really confused me a lot.

    • johnpapa7

      Simon – to do auth properly, you must address authentication and authorization. And to do both justice, they need to be taught as how they can be threaded throughout your app. That’s a course in itself … hint hint.

      • tiagor

        Hi John. So yes, this gives me 2 hints: 1. you’re not covering auth in your upcoming course and 2. you’re planning a new course on the subject – to be fair to one of the most important evangelists in the world (you), I think it makes sense.

        Can I give a suggestion? If you do a new course on the matter, maybe it would be good to take your upcoming App and apply auth to it? That way, your upcoming course (the one due this month) would give a lot of context to the (possible) separate course on Auth.

  • Prakash Singh

    LOL, Its should be a Breeeze to learn

  • Kevin Brown

    Totally looking forward to the new class. This area of technology moves so fast and I appreciate the exposure to how to wade through the details. Brian’s class on Breeze is very detailed. It’s a great resource. Keep all that great content coming. The classes are worth my Pluralsight subscription alone.

    • johnpapa7

      Kevin – Yes, Brian’s class is awesome! I’m glad he did this, so now I can just refer to it in my courses for deeper information and I can focus on cool uses for Breeze :)

  • markrendle

    Is there an existing way of integrating Breeze validation into AngularJS as an alternative to the markup-side form validation?

    • johnpapa7

      markrendle – Im not sure I follow you. What is it you’d like? You can create validation entirely in JavaScript using Breeze. And/or you can use validation that Breeze gleens from the metadata And/or you can use the breeze directive for Angular to enforce the validation in the UI.

      • johnpapa7

        markrendle – After re-reading this I think you mean you want to know if there is a way to do validation without having to add all the HTHML5 validation monikers. If that is your question, you are in luck. Breeze has a great validation plugin for angular that works awesome. I’ll be showing this in a course before the end of this year.

        http://www.breezejs.com/breeze-labs/breezedirectivesvalidationjs

        • markrendle

          You re-read my meaning correctly, and that is brilliant. Will definitely be taking a closer look at this now.

  • Pingback: Learn Breeze | Nova Tech Consulting | Scoop.it

  • Charlie Kaiman

    I’d use Breeze in a second if it would work with Django (Python) and APIs like Tastypie or Django REST.

  • Pingback: Nova Tech Consulting Blog | Learn Breeze

  • Miguel Couto

    my Problem With breeze is on how can i block querys on the server.
    Example: I have Orders on the table Orders.
    A client can only see His own orders and not from other clients.
    With breeze i can’t block the server from not giving this information.

    If i return a list or IEnumerable the cliente side query suport of breeze don’t work.

    • johnpapa7

      Miguel – You dont have to return all rows, you can filter them however you like. In the controller you can filter them by the user id of the principal, for example. our server business logic is entirely up to you.

      • Miguel Couto

        Thx for the answer, john.
        But my main problem is that my app have lots of permissions, this can be high level like block a certain area of the app, to a low level like block 1 property of a table.

        Example, my produt page have 7 prices (pvp1,pvp2,productionCost, RetailPrice, etc)
        Person A can see (pvp1 and pvp2 and can’t see the others.
        Person B can see ProductionCost only.
        And so on.

        And its all this over all app. How could i use breeze in this context?

        i would like to have a method like “BeforeSaveEntityDelegate”

        that could do the same for query.
        Then i could for each Entity tell Breeze “Hey this is the list that the current user can see”.

        Is this Possible??

        • Ward Bell

          Breeze doesn’t have anything specific for this but you have complete control over the Web API query endpoint.

          As John observed, it is easy to write the server query method to filter results by what the user can see.

          However, you moved the goal posts a bit. You want to change the property values based on user permissions. When I see logic like this, I think it may be time for something like DTOs for the permission sensitive types.

          For example, your Web API method can project into a custom type that the client “thinks” is an entity type. You can still use IQueryable while projecting into that type. Of course when the client saves such a type, you intercept it and translate it into the proper server-side model type.

          Alternatively, you could do some custom JSON.NET configuration to manipulate the actual JSON values as they are being serialized on the server for the client. You could do something similar with a Web API action filter.

          We have thought about adding an interceptor to the (unseen) Breeze action filter that would spare you the pain of setting up your own. You’d still have to write the mutating logic. Would this meet your needs? Would you use the Breeze.NET components if that feature were available?

          These are all advanced techniques that add complexity. But then you apparently WANT that complexity, else you wouldn’t have these business rules.

          • Miguel Couto

            i have downloaded the Breeze.NET components source. And i know how the iquerable is interpreted in the action filter.

            i would like is something like, on the anction input:

            public IQueryable Sessions(ODataQueryOptions opts)
            {

            //this could return a list of objects instead of a string
            var selects = opts.RawValues.Select;

            //also this could be manipulated, so that if i change select like remove some properties of tell properties to block

            return _contextProvider.Context.Sessions;

            }

            this would allow me to tell Breeze that i only allow X,Y,Z collumns to be show for this user.

  • tiagor

    Come on John, I’m holding off all TV Series, just waiting for your new course on Pluralsight :D Do you have any updates from them, as when will it be available? Thanks

    • johnpapa7

      Guest – hehe – it is available now. Went live earlier this past week :)

  • Jacked

    John,

    Thanks for the info. I just started watching the course, although I’ve seen your SPA course where you talk a little bit about Breeze. Either way, I’m certainly just a beginner with Breeze.

    My biggest concern with Breeze and using Web API is that you seem to be forced to use Entity Framework. I could be wrong about this, but in our project we are using Web API but we are NOT (and won’t be) using Entity Framework. We would like to use Breeze in our SPA client that will talk with our ASP.NET Web API but if Breeze only works with a Web API that uses EF (i.e., being forced to use the Breeze Server Infrastructure, Breeze Routing, Breeze Controllers, EFContextProvider, etc.), then we’ll probably have to pass on Breeze.

    Can Breeze be used with ASP.NET Web API but not have to be used with EF? If so, how would you do this? Is there any guidance on the subject? Everything out there always ties Breeze to Web API and EF.

    Thanks.

    • Ward Bell

      Short answer: no you don’t have to use EF. You don’t have to use Web API either. What you’re seeing is the .NET “productivity path”. But you can talk to anything … node, RoR, no ORM, EF, NH … etc.
      Of course if you deviate from the productivity path you’ll do a little configuration (more of it the farther you stray). But it’s just config.

      • Tolga Yaramis

        Is it really config issue?
        I could not find any example which shows using asp.net web api with azure table storage?
        How can I produce metadata in web api without using EFContextprovider?

  • Nga

    Hi John,

    I have a column in my table that is required to be unique but I don’t know how to create validation rule for unique check in Breeze? Is it possible and how to ?

    Thanks,
    Nga

    • johnpapa7

      Sounds like a job for a server validation. The client likely wont know the entire domain for uniqueness, so you would have to either do a async call to the server to check or just check when you save since you go to the server already.

      • Nga

        Thanks for your suggestion.

        I have one more question related to validation error message, could you please help?

        I want to create a checklist with many checklist items.

        If data of checklist and checklist items are invalid, after call manager().saveChanges(), I can get all validation error messages of checklist and checklist items via error.entityErrors.

        I tried to show validation error messages before calling manager().saveChanges() by using: checklist

        .entityAspect.getValidationErrors but the result of this does not contains error messages for checklist items.

        Is there any way to show error messages of checklist items too? Or I have to iterate checklist items and collect its error message if existed.

        Thanks,
        Nga

        • Ward Bell

          You’ll have to iterate. FWIW, saveChanges will run the validation checks by default and report all errors that it finds in the fail callback. You could just let it do the work.

          • Patrick Schutte

            Hi, I only get back a text message, no validation errors.
            saveChanges.then(success).fail(saveFailed); In saveFailed(error) the error contains just a string, entitesWithErrors is undefined. I’m using the lastest Version of breeze and build my SPA anlong the pluralsight SPA JumpStart. Since the course something must have changed but I don’t get it. Is there any Kind of configuration to be done or should Validation with Server side Attribute still work out of the box?
            Thanks,
            Patirck

          • Nga

            Hi Ward, I have a question related to Breeze.EntityQuery at http://stackoverflow.com/questions/21239570/breeze-query-from-custom-type-entitytype-clientpropertypathtoserver-is-not-a-f. Could you please take a look and help? Thanks a lot. Nga

  • Nga

    Hi John,

    Can Breeze perform left join? For example: A kid can have zero or 1 pet. I want to print list of kid with their petname.

    I cannot call .expand(“pet”) because my generated poco class does not have [public virtual Pet Pet { get; set; }].

    This is my poco class:
    public partial class Kid {

    public Nullable PetId{ get; set; }
    }

    I tried to call GroupJoin between Context.Kids and Context.Pets. Return result is custom collection IQueryable.
    But I cannot call breeze.EntityQuery.from(resourceName) because CustomKid entity is not in metadata store.

    Do you have any suggestion for this?

    Thanks,
    Nga

    • johnpapa7

      you can always have breeze point to a specific query and not bother with iqueryable. sounds ike what you want here. if not, check stackoverflow and lay out what you need and the breeze folks can chime in

  • Marcelino Jorge Romero

    Hello John. I watched recently your courses on pluralsight and i admire your coding style and the structure of your code. At this moment i’m trying to build a small website with hot towel and angularjs using a micro-orm technology instead of Entity Framework but i’m stack in Breeze part because i can’t find anywhere a small example on how to use breeze with different technology… I would appreciate if you could give me a bit of help and guidance…

%d bloggers like this: