What Breeze can do for You | John Papa

John Papa

Evangelist on the loose

What Breeze can do for You

...

Right about now you are wondering what Breeze brings that you can’t do on your own. Right about now you are wondering why you should bother learning another technology. Right about now you are wondering if you should continue to read this post. If you do, you won’t be sorry. Breeze is that valuable to rich web apps.

sansbreezeBreeze.js is a client side JavaScript library that manages rich data. Before Breeze existed, I wrote a SPA and it had 20 JavaScript files and modules for data management that total about 1550+ lines of code. I wrote all of this code to do a fraction of what Breeze does. It was painful to write and every time I added a new entity or CRUD method it got much bigger. I rewrote this logic using Breeze and ended up with 2 files (datacontext.js and model.js) and had 350+ lines of code, more functionality, and every time I add a new entity the code increases by just a few lines. That’s 1/4 the code, about 1/4 the time, and more value. Does that interest you?

Remember Upshot?

You may recall a library that the ASP.NET team started a while back called Upshot.js. Upshot had a lot of promise for rich data management, but was dropped due to resources. That left the door wide open and in came a Breeze. Breeze does quite a bit, including making all entity properties observable (for Knockout), but for this post let’s focus on the features below as they are proof enough that you should take it seriously:

  • Caching and Sharing
  • Easy Queries
  • Object Graphs
  • Works with Knockout and Angular
  • Support

spajs
Learn more about Durandal and these topics from my beginner level SPA JumpStart course for Pluralsight, available now.

Separation

I choose to use separation patterns. So my data logic goes in a datacontext module in JavaScript. It exposes that data logic to the view models or controllers on the client. I slide Breeze right inside of the datacontext and expose a simple API so my viewmodels and controllers can share the datacontext. This makes it easy for the viewmodel to call for data doing something like datacontext.getCustomers or datacontext.Save.

Caching and Sharing

Let’s say you have an app with customer data. You may show customer information on views for a customer list, customer details, orders, sales, reports, and more. If you change a customer’s name or other information in one view, you expect it to ripple throughout the app. If you get the customer data in each viewmodel and store it separately, this becomes problematic. Sure you could use events to communicate with them all, but then you are storing that customer data in several places: not very DRY.

Breeze helps cache the customer data the first time you get it. Then when you go to another view that needs that data, Breeze supplies it. By wrapping this all in the datacontext, you have one place to go for your data. If you update the customer, Breeze has 1 copy of it and all places that point there are updated. Pretty slick!

Easy Queries

A library isn’t valuable unless it’s you can use it easily. Who wants to maintain something convoluted? Not me. Words can’t say how easy it is to query Breeze. So let’s just look at some examples.

var query = breeze.EntityQuery
           .from("Customers")
           .where("CompanyName", "startsWith", "A")
           .orderBy("CompanyName");

var promise = manager.executeQuery(query)
              .then(querySucceeded)
              .fail(queryFailed);

This code creates a query that gets customers whose company name starts with the letter A and orders them by the company name. Then the query is executed against the remote data service and the data is returned through a promise. Pretty simple and self-explanatory.

Object Graphs

Real apps use object graphs. Real apps need to navigate between the entities in an object graph (both parent-child and child-parent). Real apps can be difficult. Breeze can retrieve object graphs and make it easy to navigate their relationships. Go from customer to one of their orders to one of the order details, and then back up if you like. Grab an entire object graph in one call or just get the top-level. Whatever you need, it’s pretty great to be able to get parts of or entire object graphs as needed.

Breeze allows you to connect objects on the client that you retrieved in separate calls, too. For example, go get a list of sales people objects (for customers). Breeze caches the sales people entities. Then go get a list of customers and their orders and Breeze caches those too. breeze also sees that the customer objects have a salesperson. We already have the sales people in cache so Breeze connects the entities and allows you to navigate between them. So as you get the data Breeze connect them in its cache.

Knockout and Angular

Breeze is built to adapt to other frameworks. So if you want to use Angular, Knockout, or Backbone you are in luck: Breeze is very happy to work with all of those. Out of the box Breeze works with Knockout, but you can change the adapter setting and switch to using Angular or Backbone. This gives Breeze a big advantage for future proofing in case you want to use one of these frameworks now and in the future choose a new popular framework.

breezestack1

Here is an example of getting employee data with Breeze and data binding the resulting entities using Knockout.

<!-- Knockout template -->
<ul data-bind="foreach: results">
  <li>
    <span data-bind="text:FirstName"></span>
    <span data-bind="text:LastName"></span>
  </li>
</ul>
 
// bound to employees from query
manager.executeQuery(breeze.EntityQuery.from("Employees"))
   .then(function(data){ 
       ko.applyBindings(data);
    });

Here is an example of getting employee data with Breeze and data binding the resulting entities using Angular.

<!-- Angular template -->
<li data-ng-repeat="emp in employees">
    <label>{{emp.FirstName}}</label>
    <label>{{emp.LastName}}</label>
</li>
 
// bound to employees from query
manager.executeQuery(breeze.EntityQuery.from("Employees"))
   .then(function(data) { 
       $scope.employees = data.results; 
    });

Need SPA Support?

Want someone to have your back? The folks who make Breeze licensed it with an MIT license. They also offer support and consulting services for building a SPA with Breeze using technologies such as Durandal, Knockout, Backbone and Angular. IdeaBlade has been in the rich data business for a decade and has a great track record in this space with various other products. Breeze is their answer to the JavaScript and web space. So if you need support for your project, check out your options here.

What Else?

Do you want to save entities to local storage and later pull them back into Breeze? No problem. Do you want to query locally first and if the data is not there go to the remote service? No problem. Do you want the client to tell the server to do server-side paging and filtering? No problem! Breeze can do quite a lot and has saved me tons of code in my apps. I highly recommend checking it out.

SPA Jump-Start Series

tags:
  • Pingback: What Breeze can do for You | WebDevStuff | Scoo...

  • Randhir

    John,

    Great artical..But i am little bit confused because all the database and business logic on client side
    like:
    // bound to employees from query
    manager.executeQuery(breeze.EntityQuery.from(“Employees”))
    .then(function(data){
    ko.applyBindings(data);
    });
    If we will handle all thing in JS/Client side, then it may cause a security issue. as all the code will be available on client side and user can see or download the logic part.So please clarify it?

    • John

      Randhir – There is no database interaction nor business logic in the client. Think of those lines of code as simply asking for a list of employees from the web api on the server. Same thing as using $.ajax to go get the data over http. This is a common confusion, though. To clarify, first, let me be absolutely clear that no business logic nor insecure data should be on the client in a web app. Second, you could secure the employee data such that certain columns or rows cannot be returned to the client (passwords, for example). The client can only retrieve what you allow it to ask for. It can retrieve a subset of those, however, which is where Breeze excels. Breeze allows you to include other entities in navigations, further limit the columns, limit the rows, order them, ask for the next 10, and more. But all of that is within the constraints of any security and limits you put on the web api on the server. Thus all logic is on the server. You can also secure the calls in the web api using any auth mechanism you want on the server.

      Hope this helps.

    • http://www.breezejs.com Ward Bell

      Randhir – I understand your concern. I think John has addressed it but I’ll add my words too. First, no server code comes over to the client. None. Zero. Nada. The user cannot “see or download the logic part”. Second, the client only sees the data that you allow it to see. Our demos tend to send everything that is listed in the database. But they are just demos. You don’t have to do that. You can exclude anything that you don’t want on the client. Third, entity type names and property names tend to be the same on client, server, and database. This is a convenience. I personally don’t see a threat in using the same type and property names everywhere and I don’t think much can be gained by “security through obscurity”. But you can change those too if you want to go through the trouble of doing so.

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1335

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1335

  • Rick

    I want to love Breeze. I am a big fan of Entity Framework and Web API approach. I love the server side Breeze controller. I love how John integrated within the Pluralsight SPA course.

    However, in my app, when it makes the call for metadata on my data context, it bombs. It provides no error message other than Metadata query failed for the service.

    My data context is a little more complicated than the examples used in the demos, but it is not extreme.

    Still working through it. I am going to try and debug thru the Breeze and jQuery code to figure it out. I am also creating a second data context that only contains the classes I need to start with.

    Will post an update if I figure it out. In the meantime, I am questioning if this is ready for more complicated scenarios. I sure hope it is.

    Thanks, Rick

    • http://www.breezejs.com Ward Bell

      Rick – Metadata generated by EF should not bomb in Breeze … unless you’re using inheritance. We do not support inheritance today but it is super-high on our priority list so you can expect it very soon. The best place to get our attention on potential bugs is StackOverflow with the “breeze” tag. Thanks for giving it a try.

      • Rick

        Thanks Ward. I have spent the day tracking this. I am using Breeze inside of a Web Forms site. I have added a ‘mini SPA’ inside. In comparing the requests from Web Forms and a demo in MVC, I noticed that the Accepts header on the Web Forms was: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

        In Fiddler, if I remove this, it works.

        I am debating just separating this mini app into it’s own MVC app to avoid these issues.

        I will post a question on stack overflow if not solved by tonight.

        Thanks for the response, Rick

        • http://www.breezejs.com Ward Bell

          Rick – AHA! Breeze is expecting JSON, not XML. I recommend using Web API (with [BreezeController] attribute on your Web API controller] for external facing data and reserving Web Forms/MVC for your HTML traffic. While that alleviates many problems, I don’t know if that is feasible in your application.

          • Rick

            Thanks Ward. I am using Web API with the breeze controller attribute. I suspect it is a config setting somewhere.

            Will keep digging. Thanks

          • Geethanga Amarasinghe

            Hi John,

            Nice to see this post about Breeze and it’s even nicer to see all these questions and conversations. I’m working with Breeze in a SPA which is backed by an ASP.NET WebAPI/ EF server side. I have a few concerns which I would like you to clarify.

            We are hoping to use Repository and Unit of Work patterns on top of EF in the server side, we have exposed our repositories in the Breeze controller as GET actions and it looks fine. But the problem comes when we are saving the data using SaveChanges action, since it’s taking a bundle (changed entities) we have no easy way of using our repositories for saving data. When you say “Your business logic is in the server” where exactly are we supposed write this business logic code?

            And do you agree that Breeze only servers JSON, which kind of defeat the purpose of WebAPI content negotiation.

            Thanks,
            Geethanga

  • Tariq

    So what is the best method for SPA using ASP.NET

    KnockoutJS SPA Template
    Breeze/Angular template
    Breeze/Knockout template
    etc

    http://www.asp.net/single-page-application/overview/templates

    Which one should use when and why?

    and is there any template that generate some auto-genreate startup (Javascript) just like MVC Controller generate (Edit,Delete, View, Insert)

    • John

      Tariq – there is a chart in my post and on the asp.net site that shows some of the differences between the templates. That said, the KO template that comes out of the box is very basic and is an example of what you can do. The Breeze/KO one adds to that by using Breeze for data access (so its a superset of the other template). The Breeze/Angular template does the same thing as the other Breeze/KO template except it uses AngularJS. These 3 are here just to show the differences between the techniques. You should pick between KO/Durandal vs Angular. Then choose if you want to use Breeze with them (it works ewith either).

      There is no template that gives you a CRUD method for everything like in MVC. If there was one, what would you expect from it? A datacontext with CRUD methods for some object? That means controller methods for it. It also means adding models on the server too and EF. It also means adding a view and viewmodel for it. As you can see, it adds a bunch of code tha tyou would rip out later because whatever the tempalte gives you that is specific can certainly not be what you need (Todo’s for example). That said, Code Camper gives you an example of how that all works together http://jpapa.me/ccjsdemo

      Please let us know what you would like to see. This is the type of feedback the Microsoft team wants to hear. So also be sure to tell them via forums.

  • Tariq

    Further you shows different methods and ways (Using different libraries)

    Also mention that are the pros and cons of individual libraries

    Its hard to put all eggs in one basket

    • John

      Tariq – Watch the course and it explains what the libraries do and how to use them. :) if you have specific questions, feel free to post them or head to StackOverflow too.

  • Tariq

    Thanks for such short notice reply

    Which video you are refering?

    Single Page Apps JumpStart
    Single Page Apps with HTML5, Web API, Knockout and jQuery

  • mick

    breeze requires Entity Framework yes???

    is there a way to use it with just an IQueryable? we have a pretty large amount of NHibernate, plus MongoDB. so as much as it appeals to me breeze is not an option at the moment?

    cheers.

    • http://www.breezejs.com Ward Bell

      mick – the good news is that Breeze does not require Entity Framework. Take a look at the NoDb sample (http://www.breezejs.com/samples/nodb) which uses no EF and no database. If you have a way of accessing your database through IQueryable (as one can with NH), go for it. You would not use the EFContextProvider obviously. You might try inheriting from the base ContextProvider class instead (as the NoDb) sample does. We need to add an NH sample to our stable. If you feel like beating us to it with your own NH sample, the entire Breeze community would welcome your contribution.

      • mick

        thanks ward, i’ll take a look at it and hopefully if i can get it all working i’d be happy to contribute back.
        regards

  • Martin

    The main concern with breeze that I see is it encourages you to simply materialise the full entity framework entities to client.

    Filtering the rows before materialising them is straightforward enough (i.e. to those a specific user can see), but what about columns?

    How do you prevent the client selecting the password hash from the users table?

    A specific example of where I immediately had trouble trying using breeze was returning a list of images from my database. I don’t want to send byte arrays to the client I want to send links to the client which can follow the links and get the images.

    So almost immediately, I saw myself having to create DTOs, and found materializing the database object dangerous from a security perspective and not useful.

    By using DTOs, I lose most of the features of breeze don’t I?

    If you use breeze as per the examples, you are allowing arbitrary queries against a database.. this is supposedly one of it’s main advantages…

    example above: .where(“CompanyName”, “startsWith”, “A”)

    but what if I changed it to .where(“CompanyName”, “endsWith”, “A”)

    This will always cause a table scan!.. surely this feature is actually a real disadvantage too. I know I can check the expression tree of a IQueryable before it is executed to exclude anything which I may deem unsafe but surely enabling this kind of functionality by default unless explicitly prevented is a) dangerous and b) more code than a traditional method

    Is it expected that I have to sanitize each query, ensuring it only filters on indexed columns?

    Hopefully someone can help me understand how to avoid the dangers above so I can get real value from breeze

    • John

      Martin – Thanks for the thoughtful feedback. Most of this is not breeze, its exposing your data in the web api the way you want it to look to the client. You have so many questions I should charge by the question here (kidding)

      • RE: Filtering columns – you can filter columns. I do this in the course with the session and speaker partials. Its a projection.
      • RE: Password column – Don’t expose the entire table. Expose the user data columns that you want in the web api.
      • RE: images – I dont store images in a DB, and I agree that you should just send url paths instead. This is where you can either create a DTO or just expose a projection of the data from the web api.
      • RE: DTO’s and security – DTO’s or projections are a fine solution. Not hard to do solves your issues securely.
      • RE: DTO’s and breeze – DTO’s work just fine with Breeze. If you want to save a DTO, you will need to handle that too, of course. See Breeze docs for help or open StackOverflow
      • RE: IQueryable – If you do not want to open IQueryable, then don’t. You can just expose a list of the objects. It may not do a table scan though. It depends on your indexing.
      • RE: Filtering on indexed columns – Nothing is expected of you. You seem to have concerns with IQueryable. I suggest you avoid it or research more til you are comfortable with it (or not).

      Best advice I can give you is to open a dialog with the Breeze folks on StackOverflow. They live and breathe their product and have done this for 10 years (in other technologies too). They also have paid support options :)

      • http://www.breezejs.com Ward Bell

        Martin: your concerns are shared by many others. I really must do an essay on this subject in the Breeze docs. Thanks, John, for the point-by-point, all of them correct and well said. The essence is (a) control what you send to the client (b) use as much or as little of IQueryable as you feel comfortable with (c) use DTOs when appropriate and (d) re-read John’s points about the value of Breeze other than its support for IQueryable. Developers who have written their own client-side data management layers in JavaScript discover that the query was the least of their problems (I’m looking at you, John :-).

      • http://chrisjakubowicz.wordpress.com Chris

        John

        RE: Filtering columns – you can filter columns. I do this in the course with the session and speaker partials. Its a projection.
        RE: Password column – Don’t expose the entire table. Expose the user data columns that you want in the web api.

        I understand the overall idea here and do like it, but it would be great to see an example. I created an SO regarding this: http://stackoverflow.com/questions/16091496/using-partials-and-projections-of-entities-in-web-api

        If you (or Ward) get a chance to reply to it then that would be great!

        • John

          Chris – There is an example of this in the course with the speaker and session partials. I return projections from those where i do not return the description field (for sessions) nor the bio field (for speakers). Check that out and use the same style for not showing your SSN field for your Employee class

  • http://www.pehas.com Adam

    First off, I want to say that I love your Pluralsight courses and blog. Currently I working through your SPA jump start course and it is really helping me wrap my head around building my first SPA. The one piece that I can’t fit in is where does my business logic fit. For example lets say I need to send a notification to the accounting system every time a new order is saved.

    I love the fact that Breeze can reduce so much plumbing code but where does it make sense to write the core business logic of my app. Would it make the most sense to put it in a partial class with in the server side models? I’m coming from a web forms background where I’ve used many ORMs over the years and I will generally put the custom business logic in a partial class in a service or business logic layer. I guess I’m really trying to figure out what that pattern looks like.

    Thanks !

    • John

      Adam – Thanks for the feedabck. Glad you like it.

      Business logic goes on the server. Not on the client. Breeze does not and should not do any business logic. So yes, write that code on the server and have your client app kick it off when needed. That should be the same as your Web Forms experience.

      • http://www.breezejs.com Ward Bell

        Spot on, John! The only logic on the JavaScript client should be application logic, the code that delivers the great user experience. Keep the secret sauce on the server.

      • razorbackwriter

        Isn’t your query business logic? Won’t your client code become brittle by doing this on the client (i.e. change “customer” to “client” on the server and now you have a heap of changes to make)?

        • Ward Bell

          The server controls what the client can see and do. The query interface is a convenience to the client … and no more. In Web API you have great control over what you allow a query to do.This is no more (and no less) “business logic” than any API you expose to a client. As for the coupling to the server names and schema, that too is up to you. Change from “customer” to “client” and you break something that you must fix. But it doesn’t have to be a “heap of changes”. You don’t have to change the client at all; just remap on the server … which is EXACTLY what you would do in any imaginable API scheme. Breeze doesn’t know what you’re doing on the server; it only knows what you expose at the service boundary. Of course at some point, the “types” at the service boundary are so different from the server business types that you lose IQueryable support. Hey … that’s your choice; Breeze works fine w/o IQueryable.

    • Callum Vass

      Hi Adam. I’ve recently started integrating Breeze with my app and am in a scenario now where I need to integrate it with custom business logic using a service layer. I am interested in how you went about doing this with partial classes and at what point did you apply those business logic? Ie BeforeSaveEntities, AfterSave, SaveChanges etc..?

  • Hoisel

    Hello,
    Will Breeze be included in upcomming MVC versions?

  • http://skilltraxx.com James Fleming

    How does one iterate over a collection of data as returned in the pluralsight demo?

    I had code that previously worked, but now the ‘breezy’ object graph tells me the property is undefined when I know it is not via Firebug

    $.each(positions, function (i, p) {
    var target;
    var tags = p.tags; <– now 'undefined' but positions[0].tags is not….

    • John

      First, confirm that positions is an observableArray. Set a break point there and test its value. Then check to make sure it has array elements. You may want to loop through positions() (with parenthesis). Remember, an observableArray is a function that returns an array. Next, assuming you have data in the array, confirm what p is. It may be an observable or not (I am not sure what you have). A gret tip is to use Chrome and install the KnockoutJS plugin top examine the Knockout observables in the entity. That should help you.

      BTW – I woul dnot use $.each to loop here. jQuery is fine for looping through DOM elements, but for straight looping, it is better to use a for loop, or the array.forEach method (if you use ES5)

      • http://skilltraxx.com James Fleming

        John,
        First thank you for your generous support of the community, and sharing your knowledge. You were spot on – while I was returning my data (because I had modified my API to .Include(childTable), it wasn’t being picked up by Breeze b/c I hadn’t explicitly called it – var query = EntityQuery.from(‘Positions’). The takeaway here is to keep my WebAPI pure and to builid up in Breeze my navigation properties.

        I have come to another issue I’m hoping the community can help me understand. When I was calling my table, which has child properties (Projects, Tags), the breeze.partial-entities.mapToEntity method throws an error: Error retreiving data. Property ‘entityAspect’ of object [object Object] is not a function.

        “entityAspect” I believe is a Breeze construct as it is not part of my object graph.

        I suppose I could wrap mapToEntity with a test inside the for loop to ignore a prop named entityAspect, but I’m not sure that is quite correct.

        function mapToEntity(entity, dto) {
        // entity is an object with observables
        // dto is from json
        for (var prop in dto) {
        if (dto.hasOwnProperty(prop) && prop !=”entityAspect”) {
        entity[prop](dto[prop]);
        }
        }
        return entity;
        }

        While it get’s me passed the above mentioned error, it now complains that
        Error retreiving data. Collection navigation properties may NOT be set.

        My query is
        var query = EntityQuery.from(‘Positions’)
        .where(‘memberId’, ‘==’, id)
        .expand(‘Company, Tags’)
        .orderBy(orderBy.positions);

        Anyone have any thougths as to what I’m doing wrong?

        • http://skilltraxx.com James Fleming

          After getting a few more minutes to debug, I see that part of where I’m stuck now is that when handing an object to the mapToEntity function from the spa video it doen’t like child collections. I thought something was mentioned about that in the Spa video but I reviewed that section again and may have missed it. If other’s have a solution to mapToEntities for child collections, please share. I’ll dig around for a bit and post on Stack Overflow later – thought I’d share my findings thus far here.

  • http://www.breezejs.com Ward Bell

    @Geethanga Amarasinghe – This is a great place for general information and opinion about Breeze in the context of John’s SPA course. But you’ll get faster action on specific Breeze technical questions if you post the on StackOverflow with the “breeze” tag (http://stackoverflow.com/questions/tagged/breeze).

    The prescribed way to manage the incoming SaveChanges bundle is to create a custom Breeze.NET ContextProvider (or EFContextProvider if you’re using EF). Override the virtual methods (BeforeSaveEntities and SaveChangesCore are good candidates) to redirect to existing business logic. I don’t know what your UoW save logic looks like now … and whether you have any flexibility to change that logic … so it’s hard to give you more specific advice.

    I’ll also point you to the “Named Save” option, new in v.1.3.0. Use it on the client to direct a EntityManager.saveChanges call to a dedicated save method on your controller rather than the general purpose “SaveChanges” method. That might help you with more fine-grained save operations.

    If you need more details, please post to StackOverflow. I’ll look for you there :-)

    Re: Breeze demanding data as json … that’s just the way it is. I can’t think of a single good reason for BreezeJS to care about content negotiation. If you care, you’re welcome to bend BreezeJS to your purpose: (a) configure the Breeze AJAX adapter so it sends the accept headers you want and (b) write your own JsonResultsAdapter to map incoming content to Breeze entities. That’s not a beginner chore but it’s not hard either. Maybe we should do something in the box for data arriving as XML. But where does it stop? Atom? The next format? We should concentrate on more common scenarios, don’t you think?

    • Geethanga Amarasinghe

      Hi Ward,

      Thanks for the reply and really sorry for my delayed reply. Yes I agree with you. :)
      We are in the process of using “Named Saves” to have a more fine grained control on the server side, currently we have managed to split the save bundle and use our own services backed by EF to save data. And we are working on way to create the BatchSaveResult so the Breeze client could work without any additional issues. Will get in touch with you guys in SO if things go out of control.

      Thanks.
      Geethanga

  • Pingback: What Breeze can do for You | JavaScript for Bus...

  • Anil

    What about IE-8?

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2; .NET4.0C; .NET4.0E)
    Timestamp: Wed, 24 Apr 2013 07:11:57 UTC

    Message: Expected identifier, string or number
    Line: 5128
    Char: 13
    Code: 0
    URI: http://learn.breezejs.com/Scripts/breeze.debug.js

  • kourosh

    Hi, Do I need to use Entity Framework to use Breeze?

    • http://www.breezejs.com Ward Bell

      @Kourosh – You do NOT have to use Entity Framework; we’re working on an NHibernate sample right now; our “No DB” sample shows Breeze working with “nothing” as a permanent store so you can write your own ticket there. You do NOT have to use Web API; you can use any OData source out-of-the-box. You do NOT have to use ANY Microsoft technologies; see our post on that subject: http://www.breezejs.com/handcuffed-microsoft

  • http://DNAfor.NET chauey

    We love your blog posts and pluralsight training, a huge thanks to you and recommendation to others.

    I think breeze is clearly great for 90% of the data access and CRUD, however, I’m not really clear yet on some more complex scenarios:

    What are the complicated things Breeze doesn’t handle or still is a bit tricky?

    like what if 2 users are using the same data on 2 different machines, how would 1 get changes from the other?

    what if 2 people save at the “same time” or editing the “same version”, who wins? does last save win, or the 2nd saver will get an error that they have an old copy?

    what is there is a list of cities that hardly ever change, do we need to write custom code to pass in the latest timestamp, if there is something newer, we get all or something like that?

    does it automatically handle disconnected scenarios, and will sync when there is internet access, or that needs some custom logic also?

    can you point us to some samples too of how to handle all this if you know of any? thanks.

    • http://www.breezejs.com Ward Bell

      @chauey – Concurrency violation detection is something you do on the server. If you want other than “last one in wins”, you can set that up in your EF model. Then you communicate violations to the client, typically through an exception. BreezeJS is a client-side technology so this really isn’t its business. But when the BreezeJS and the Breeze.NET components are working together, it’s easy on the client to distinguish a concurrency violation exception from other exceptions. And BreezeJS also “understands” properties designated for optimistic concurrency purposes and gives them special treatment in the save payloads so the backend can do the right thing. I don’t want to drown this blog in too many details but I think the basics covered. Of course the real challenge isn’t detecting violations; it’s doing “the right thing” with them. There is no secret sauce for that.

    • http://www.breezejs.com Ward Bell

      @chauey – Breeze itself does NOT provide an offline implementation. Breeze facilitates offline scenarios by making it easy to serialize and deserialize entity-sets on the client. That is no small feat, especially if your entities are defined as observables. But you still have to detect changes in connectivity, figure out what your app can and cannot do while offline, decide when and where to stow the entity data, and decide when and how to persist locally-preserved changes when the connection is restored. I do not believe that simple, automated syncing will be sufficient in the real world. There are just too many ways that things can go wrong. We usually have to put the human in the loop somewhere. That said, I look forward to providing more infrastructure for offline app development. HTH.

    • http://leniel.net/ Leniel Macaferi
  • Geethanga Amarasinghe

    Hi John,

    Nice to see this post about Breeze and it’s even nicer to see all these questions and conversations. I’m working with Breeze in a SPA which is backed by an ASP.NET WebAPI/ EF server side. I have a few concerns which I would like you to clarify.

    We are hoping to use Repository and Unit of Work patterns on top of EF in the server side, we have exposed our repositories in the Breeze controller as GET actions and it looks fine. But the problem comes when we are saving the data using SaveChanges action, since it’s taking a bundle (changed entities) we have no easy way of using our repositories for saving data. When you say “Your business logic is in the server” where exactly are we supposed write this business logic code?

    And do you agree that Breeze only servers JSON, which kind of defeat the purpose of WebAPI content negotiation.

    Thanks,
    Geethanga

    • John

      Geethanga,

      I am happy that you are enjoying the posts, thank you for the feedback. You can use “named saves” with Breeze, a relatively new feature that is in their documentation on their site (somewhere). :) That way you can break them out if you like. If you have specific needs, you should let them know on StackOverflow or their forums.

      You should know that:
      – Breeze expects JSON to be delivered to it
      – JSON is common, and if you don’t have it, there are plenty of options to serve it, not just Web API
      – Modern web is using JSON as the unwritten standard

      If you don’t want to serve JSON for your own reasons, then Breeze may not work for you. It certainly is not a silver bullet … not sure if one exists in any of our tech :)

      • Geethanga Amarasinghe

        Thanks John. I think you have clarified my doubts. Will look in to named saves it looks promising.

  • Luciano

    Hi John,

    Love your videos about Breeze and Knockout.

    I’m trying to make an application, but I’m having trouble with DateTime fields.

    Breeze return a DateTime field like that: “Thu Feb 28 2013 16:00:00 GMT-0800″ and i need to show “MM/DD/YYY”.

    Knockout have no way to format date Date.
    Momment.Js throw a execption when tring to convert that value.

    can you help me?

  • Pingback: What Breeze can do for You | ThisAndThat | Scoo...

  • Richard Davison
  • Richard Davison
  • Pingback: What Breeze can do for You | Michael Lake

  • Basar Simitci

    Maybe I am missing something but, isn’t customizing the web api controllers (BreezeController annotation, using EFContextProvider) to use Breeze on the client is fundamentally against creating a web api in the first place? I want to build a web api to enable or encourage several kinds of clients, ie. web, desktop, mobile, etc. So I cannot see a point, and frankly see more harm than benefit in customizing my api controllers just for the web client. Maybe there is a way to make breeze work without using the BreezeController annotation or EFContextProvider but it is not very apparent (and discouraged in several places) on the docs or tutorials.

    • John

      Basar,

      Thanks for the feedback about the [BreezeController] attribute. You can certainly access a controller that uses the BreezController attribute from any HTTP client. Any “get” method in that controller, for example, just returns JSON. If you do not want IQueryable you don;t have to sue that either. The metadata and save methods are the big time savers, IMO. THe metadata method is what helps Breeze know on the client how the data is shaped, it validation, and relationships. It doesnt get in your way. The save method is a one stop shop for saves, but you absolutely dont have to use it either. You could use named saves, which in effect means you have a controller just like you normally would. There shouldn;t be any friction in you creating a web api controller that you can use anywhere.

      • Basar Simitci

        Thank you for your reply. I think I should examine the NoDb sample thoroughly to get an idea on how to support Breeze without using EFContextProvider.

  • Greg

    Has anyone had any luck using Breeze in a Windows 8 HTML/JS app?

  • Mathew

    Hey John (and Ward) – So I have association tables in my database and I need to add a new association/record in my web application. Using breeze with knockout, do I need to assign the foreign key id’s and push those objects into the relationship properties of then new record and the two associated objects? I made a stack overflow question for this also: http://stackoverflow.com/questions/16513092/adding-a-record-into-an-association-table-using-breezejs

  • Abhijeet

    Trying to understand Code Camper architecture. Few doubts
    1.) What is the use of breeze.partial-entities.js
    2.)var remoteServiceName = ‘breeze/Breeze'; where the code has been written for this ?

    Thanks,
    Abhijeet

  • Will T

    I stopped here because I don’t understand: “This code creates a query that”. What sort of query does it create? It talks with my SQL Server, or MongoDB somehow? What about MySQL? Neo4J? What sort of code do I need to create to support the code that a Breeze query creates?

    • John

      Will T – Breeze has its own query syntax, as shown in the examples. Its a breeze query. Breeze sends that query down to a web service that receives the http message. So in the server you need a web service to receive it. If you use Web API this is super easy. If you use other web service layers, you can also do this. See the Breeze site for examples or open a StackOverflow issue if you need specifics.

  • Nicolas

    Hi John,

    First thanks for all this stuff, it’s just great.
    Question about Breeze and DTO’s: I read in the documentation that the metadata is based on DbSets from the DbContext. So when you say Breeze is ok with DTO’s, do you mean it’s possible to send a DTO’s metadata? Because I could not figure out a way to achieve this yet.
    I’ve looked at the Breeze Knockout SPA template, but also in there, the metadata is based on DbSets from the DbContext passed to the EFContextProvider. So is it possible to work with something else than DbSets? I mean If I understand well, a DTO is by definition not a DbSet.

    Thanks

    • http://www.breezejs.com Ward Bell

      @Nicolas The short answer is this: Breeze needs metadata to understand how your model works … the types, the validations, the relationships among entities. Your “Model” on the client parallels your “Model” on the service. The “Model” on the service consists of the types that your server exposes through its API. Those types can be EF entities – that is easiest to demo. Or they can be DTOs.

      You already know how easily we can generate metadata on the server from your server-side business model’s EF DbContext. But you aren’t exposing THAT model. So how do you get metadata for it?

      There are two basic approaches: write the metadata by hand or find something to generate it for you.

      The documentation explains how to write the metadata by hand. It’s a little clunky and I think could benefit from some DSL-love. It’s tedious either way (less so with a DSL) but it’s not hard and, unless your model is huge, it won’t take more than a few hours.

      Or you can find something to generate it for you. That’s what I like to do. And what better to help me out then … EF itself?

      “WAT?, Ward I just told you I don’t want to expose my business model to the net. I want to expose my DTO model!”

      I get that. But you can PRETEND that your DTO model is the real business model. You can use the same EF design techniques to create fake mappings and MetadataDbContext. You’ll never use it to access real data. You’re only using it to design.

      Does that make you feel cheap and dirty? Not me. IMO, I’m just using one feature of EF – it’s ability to describe a model – as my design-time-only tool.

      You might look into it. No one has to know you’re using EF. You can hide the MetadataDbContext and all references to EF if you want. I won’t tell.

  • Michael Durling

    John,

    How do you pass credentials when using breeze to connect to an authenticated service?

    I tried this:

    this.initializeBreeze = () => {
    this.BreezeManager = new breeze.EntityManager(this.apiUrl + ‘/breeze’);
    var ajaxAdapter = breeze.config.getAdapterInstance(“ajax”);
    ajaxAdapter.defaultSettings = {
    beforeSend: function (xhr, settings) {
    xhr.withCredentials = true;
    }
    };
    };

    This seems to work for IE, but not Chrome or FF to which te server returns 401 Unauhorized.

    For non-breeze ajax calls, I simply set the following $.ajax option and all is well:

    xhrFields: {
    withCredentials: true
    }

    There does not seem to be a simple means to tell breeze to send the authorization cookie with the request that works with all browsers.

    • http://www.breezejs.com Ward Bell

      @MichaelDuring – Try the following and let us know if it works (I’m writing where I am w/o easy access to a way to test it myself):

      var ajaxAdapter = breeze.config.getAdapterInstance(“ajax”);
      ajaxAdapter.defaultSettings = {
      xhrFields: {
      withCredentials: true
      }
      };

      This should work because Breeze builds the options object passed to `$.ajax` by mixing in your `defaultSettings` with its setting. Now the Breeze options will trump your defaults. But Breeze isn’t setting `withCredentials`on its own (I searched breeze.debug.js to confirm) so your default should shine through.

      If you’re still having trouble, please post to StackOverflow with the “breeze” tag: http://stackoverflow.com/questions/tagged/breeze?sort=newest

      • Michael Durling

        @ward,

        Thank you! That worked. I didn’t realize that breeze was passing the options directly to $.ajax.

        One minor complaint that I have is that breeze.config is not included in the breeze.d.ts file so TypeScript complains about any attempt to configure the ajax adapter.

        I added a config: any to the breeze.d.ts so that TypeScript would just generate the code verbatim, but it would be nice if breeze.config was fully defined for TypeScript.

        Thanks for your help and Breeze.js rocks.

    • http://www.breezejs.com Ward Bell

      @michaelDuring – Remember … you can completely replace the native AJAX adapter with your own. You are 100% in control of that. All you have to do is conform to how Breeze expects to use it. I admit that isn’t well documented. But maybe you don’t need to know. Maybe you just make sure your stuff is on the options parameter exactly as you want it and then just make sure to invoke the Breeze callbacks when the XHR method (e.g., jQuery.ajax) returns.

  • Kash

    Hi John. I did your intermediate course, and figured out I needed to do the beginner course first. I’m following it through but have been stuck at one point for the past two days in module 6 and 7. In model.js for sessions I keep on getting “Object doesn’t support property or method ‘tags'” when I do session.tags(); I’m finding it difficult to diagnose as in JS it seems functions are pass around rather than objects in C# that I’m more familiar with. Prior to this call, querySucceded has data.results which does contain an array of my results correctly. I’m glad I don’t have to spend 10 minutes with the captcha :)

  • Oscar Agreda

    Breeze is the best,is Entity Frameworks for javascrpit ;)

    Thanks John for putting together this amazing startup framework.. I saw both of your SPA courses,thanks

    one question, while expanding this application.

    For an invoice solution for example, we added the new database, used the unit of work pattern from your intermediate plural sight SPA video.. everything works awesome. Thanks again.

    what about if we need many controllers. We could use one for invoices, inside there we can add all the methods to get the invoice data, just the same way you do it for the one breeze Controller.. but if we want to have separate controllers for customer, employees, products, etc for example .

    how do we handle the “var remoteServiceName = ‘api/Breeze’” what about the datacontext.js , routes and config.js

    how do we do that, how we integrate many more controllers , with the same amazing /simply way you did

    • http://www.breezejs.com Ward Bell

      @Oscar. Writing a DataContext that talks to multiple controllers is often reasonable and super simple to do. Unfortunately, I can’t show you in a comment because it takes more than a few lines and words to explain them. Please re-post your question to StackOverflow with the tag “breeze”: http://stackoverflow.com/questions/tagged/breeze?sort=newest

  • Jannen Siahaan

    Hi John,
    I am very happy so far with SPA HotTowel
    I am in the middle of developing an SPA HotTowel project after watching your video tutorial from Pluralsight. It is a greate SPA template
    The following issue need to modify:
    1. There is a space on Web.Debug.config and Web.Release.config. ” ” at the first line. I just remove the space to resolve these.
    2. It can not publish to IIS when we want to browse like this: “http://localhost/myHotTowel”. This is coming from “Default Web Site/myHotTowel” when publish the project to IIS, it is fine when we publish using “Default Web Site/”. The problem is “App/main” unresolved becouse it called from “http:/localhost/myHotTowel/App/main.js”, but it need “http:/localhost/App/main.js” at “” of the Index.cshtml. This is also happend to some other .js from “Durandal/*” folder.
    Summary temporary solutions, are:
    – Publish this “myHotTowel” project by setting “site name” to “Default Web Site” not “Default Web Site/myHotTowel”
    – Remove the very beginning space from Web.Debug.config and Web.Release.config

    Note: I am not an expert on IIS, It may be my lack knowledge of IIS, but not the space on Web.Debug.config and Web.Release.config.

    Thanks a lot

  • Oscar Agreda

    @Ward
    thanks
    done http://bit.ly/14J2lyy

  • kougi tambo

    Hi John,

    i am trying to make calls with breeze and mongo hq without success maybe you can help me on that http://stackoverflow.com/questions/19159719/how-to-query-breeze-js-knockout-js-mongohq-curl

  • Lukasz

    Hi, I’ve just been watching your Building Apps with Angular and Breeze course on Pluralsight. I’m not familiar with Breeze and your examples are my first experience with it.

    I’m sure there is a lot of consumer apps you can use Breeze for, nevertheless the idea of sharing entities between server and client goes against patterns for Enterprise Applications and Domain-Driven Design.

    I really value quality of your training. I just thought – it would be really great to see a course like yours but with focus on Enterprise applications, i.e. without Breeze (seen in Enterprise world as an evil, insecure and destructive for architecture).

    Saying that Breeze saves us from writing 1.5KLOCs in Enterprise world does not have to mean a good thing. In Enterprise scenarios this additional code is needed to explicitly state that what lives at client end is just a model of one specific use case – just a view, an interpretation of something much bigger which lives and evolves at server end – application domain (where server entities are securely hidden).

    I would be really glad – and many my colleagues too – to see Angular in action with Services and Data Transfer Objects instead of Entities including scenarios in which you don’t save data but you issue a command to the domain model at server end.

    • johnpapa7

      Lukasz,

      You can use DTO’s and then you business object are not being sent to the client. there are examples on the breeze site for this.

      However, using the models on the server and sending them to the client is not “evil”. It is absolutely your choice, and you should do it however your team feels best. But many enterprises do not use DTO’s for every app. Using DTO’s adds a lot of maintenance and without proper value/benefit, I don;t bother.

      Saving 1500 LOC is a good thing. Those 1500 LOC don’t prevent nor help you with the model copying. If you want DTO’s, make them on the server and then expose them from a service. Breeze will pick those up then. Again, its your soup, make it how you want. Breeze won;t care either way.

      Anyway – you can choose either options and still use Breeze with Angular.

      Good questions … and good luck!

%d bloggers like this: