EzDevInfo.com

Breeze

[WE'VE MOVED] Breeze.js is a JavaScript library for managing data in data rich-client HTML/JS applications. Rich data for Javascript Apps is a breeze

How to properly send action parameter along with query in BreezeJs

Currently I am calling all data queries as showed on BreezeJs docs / examples:

getEntityList = function (predicate) {
  var query = new entityModel.EntityQuery().from("EntityList");
  if (predicate)
    query = query.where(predicate);
  return manager.executeQuery(query);
}

But I want to pass additional parameter to controller action before any queryable result is returned:

[AcceptVerbs("GET")]
public IQueryable<Entity> EntityList(string actionParam) {
  //here goes logic that depends on actionParam
  //and returns IQueryable<Entity>
}

As we know from documentation:

Breeze converts the query into an OData query string such as this one:

?$filter=IsArchived%20eq%20false&$orderby=CreatedAt

This is where the problem starts. How should I build query to pass param to controller action?

getEntityList = function (predicate, actionParam) {
  var query = new entityModel.EntityQuery().from("EntityList");
  if (predicate)
    query = query.where(predicate);
  if(actionParam)
    // ???
  return manager.executeQuery(query);
}

I already tried setting route to:

routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{actionParam}",
            defaults: new { query = RouteParameter.Optional }
        );

and sending actionParam by applying it in a from section,

var query = new entityModel.EntityQuery()
  .from("EntityList/" + encodeURIComponent(actionParam));

but encoding fails on some special chars and bad request is being thrown.

How can I properly send actionParam in such scenario? Please help.


Source: (StackOverflow)

breezejs: date is not set to the right time

I've noticed that if a date property comes back from the server with the value "2013-07-11T17:11:04.700", then breeze changes the value to Thu Jul 11 19:11:04 UTC+0200 2013.

Notice the time is now 2 hours ahead !

I had already come across this issue when saving entities, so I had to explicitly convert my date properties using momentjs :

 date.hours(date.hours() - moment().zone() / 60);

But now it seems the problem occurs also when doing read operations.

What's the best way to make sure breeze does not alter values of my date properties ?


Source: (StackOverflow)

Advertisements

Any Grid suggestions for Breeze? [closed]

We decided to use Web API, EF + ASP.NET MVC 4 + Knockout + Breeze for our project after a long research. But we can not find any working grid for Breeze. We want to bind breeze entities to grid and be able to edit data on grid for some scenarios.

We try new grids almost everyday but still no luck, for example, we tried jqxGrid (from jqWidgets) but it throws an exception while binding data (possibly because of circular references between entities). If we don't use breeze entity and select an anonymous type it works ok.

Do you have any suggestion?

Thanks in advance.


Source: (StackOverflow)

Breeze: How can I create a GUID key for new entities on the client?

Using Breeze, what is the simplest way to populate a GUID key when an entity is created?


Source: (StackOverflow)

Breeze and the EdmBuilder for OData v4

I was able to create an OData (v3) service with WebApiOdata and EntityFramework at server side and Breeze at client side thanks to this document.

Now I'd like to do the same with the version 4 of OData spec. but there is a problem. The EdmBuilder class provided by Breeze depends on the 'Microsoft.Data.Edm' wich is related to the version 3.

In the EdmBuilder these 2 lines prevent the project from building:

using Microsoft.Data.Edm.Csdl;
using Microsoft.Data.Edm.Validation;

wich is normal, because my project has a reference to 'Microsoft.OData.Edm'(for v4) instead of 'Microsoft.Data.Edm'(for v3).

So I replaced the 2 using statements, by this:

using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
using Microsoft.OData.Edm.Validation;

Now the project can build, but at runtime it throws this exception "Encountered the following errors when parsing the EDMX document: UnexpectedXmlElement : The element 'Edmx' was unexpected for the root element. The root element should be Edmx. : (1, 40)" from the EdmBuilder class at this point:

using (var reader = XmlReader.Create(stream))
            {
                return EdmxReader.Parse(reader);
            }

Is there any way to solve this problem ??? like a new EdmBuilder class that I can download somewhere ? :)

Thanks.

P.S. : im using code first migration and this code to configure OData route in the 'WebApiConfig' :

config.MapODataServiceRoute(
            routeName: "ODataRoute",
            routePrefix: "OData",
            model: EdmBuilder.GetEdm<MyDbContext>(),
            batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));

Source: (StackOverflow)

How can I detect a change to an entity's EntityState?

I want to put a "Delete" button and a "Cancel" button on each row of a list of Customers. The "Cancel" button is disabled when a customer is "Unchanged". But when a customer transitions to a changed state ("Added", "Modified", "Deleted"), I want to enable the "Cancel" button so the user can reverse the changes -- whatever they are -- before saving.

I can almost do this by subscribing to customer.entityAspect.propertyChanged. A property change signals a potential change in the EntityState. I can subscribe to that event and have my handler update an isChanged observable that I've added to my Customer entities. Then I bind the "Cancel" button enable to the isChanged and I'm good to go.

But the propertyChanged event is only raised when a data property changes, e.g., customer.Name("New Co.");. It isn't raised when the user clicks the "Delete" button. "Delete" triggers customer.entityAspect.setDelete(); which doesn't touch a data property; it simply changes the customer's EntityState.

(1) Why doesn't a change to the customer's EntityState raise propertyChanged and (2) how can I listen for a change to the EntityState so I can control the "Cancel" button?

P.S.: I'm using Knockout.

P.P.S: This question was inspired by a previous SO question "entityAspect.setDeleted doesn't fire the subscribed propertyChanged event".


Source: (StackOverflow)

Getting an Enum to display on client side

I'm having hard time understanding how to convert an Enum value to it's corresponding name. My model is as follows:

public class CatalogRule
{
  public int ID { get; set; }
  [Display(Name = "Catalog"), Required]
  public int CatalogID { get; set; }
  [Display(Name = "Item Rule"), Required]
  public ItemType ItemRule { get; set; }
  public string Items { get; set; }
  [Display(Name = "Price Rule"), Required]
  public PriceType PriceRule { get; set; }
  [Display(Name = "Value"), Column(TypeName = "MONEY")]
  public decimal PriceValue { get; set; }
  [Display(Name = "Exclusive?")]
  public bool Exclude { get; set; }
}

public enum ItemType
{
  Catalog,
  Category,
  Group,
  Item
}

public enum PriceType
{
  Catalog,
  Price_A,
  Price_B,
  Price_C
}

A sample result from .net API:

[
  {
    $id: "1",
    $type: "XYZ.CMgr.Models.CatalogRule, XYZ.CMgr",
    ID: 1,
    CatalogID: 501981,
    ItemRule: 0,
    Items: "198",
    PriceRule: 1,
    PriceValue: 0.5,
    Exclude: false
  },
  {
    $id: "2",
    $type: "XYZ.CMgr.Models.CatalogRule, XYZ.CMgr",
    ID: 2,
    CatalogID: 501981,
    ItemRule: 2,
    Items: "9899",
    PriceRule: 2,
    PriceValue: 10.45,
    Exclude: false
  }
]

So in this example, I need to get Catalog for results[0].ItemRule & Price A for results[0].PriceRule. How can I accomplish this in BreezeJS??


Source: (StackOverflow)

How we survive using a local time zone with Breeze

I'm writing this to gather comments on our approaches and hopefully help someone else (and my memory).

Scenario

  • All of our databases use DateTime data types with no time zone information.
  • Internally we know that all of the dates/times in our databases are in local (New Zealand) time, not UTC. For a web application this is not ideal but we don't control the design of all of these databases as they support other systems (accounting, payroll, etc).
  • We are using Entity Framework (model first) for data access.

Our problem

  • Without specific time zone information the Breeze / Web Api / Entity Framework stack seems to favour the assumption that times are UTC, not local, which is probably for the best but doesn't suit our application(s).
  • Breeze likes to pass dates back to the server in standard UTC format, particularly in query strings (eg where clauses). Imagine a Breeze controller that directly exposes a table from the database as an IQueryable. The Breeze client will pass any date filter (where) clauses to the server in UTC format. Entity Framework will faithfully use those dates to create a SQL query, completely unaware that the database table dates are in our local time zone. For us that means that the results are somewhere between 12 to 13 hours offset from the ones we want (depending on daylight savings).

Our objective is to ensure that our server side code (and the database) consistently uses dates in our local time zone, and that all queries return the desired results.


Source: (StackOverflow)

Breeze and RESTful WebAPI

Question:

What value does breeze provide when I need to implement my own POST/PUT/GET endpoints per entity in WebAPI?

Background:

This seems to be a common implementation of a serverside Breeze controller:

[BreezeController]
public class TodosController : ApiController {

    readonly EFContextProvider<TodosContext> _contextProvider =
        new EFContextProvider<TodosContext>();

    // ~/breeze/todos/Metadata
    [HttpGet]
    public string Metadata() {
        return _contextProvider.Metadata();
    }

    // ~/breeze/todos/Todos
    // ~/breeze/todos/Todos?$filter=IsArchived eq false&$orderby=CreatedAt
    [HttpGet]
    public IQueryable<TodoItem> Todos() {
        return _contextProvider.Context.Todos;
    }

    // ~/breeze/todos/SaveChanges
    [HttpPost]
    public SaveResult SaveChanges(JObject saveBundle) {
        return _contextProvider.SaveChanges(saveBundle);
    }

    // other miscellaneous actions of no interest to us here
}

I'm in the middle of building a RESTish API that, up to this point, has endpoints like:

GET /api/todo/1
PUT /api/todo
POST /api/todo

It seems like Breeze requires the endpoints to be much simpler (for better or worse) - just a bunch of GETS and a SaveChanges POST endpoint.

This leads me to think that Breeze makes rapid development with a single web client, well, a breeze... but as soon as you have anonymous clients, you have to force them into whatever breeze interface conventions you've created in your client, which seems to defeat the purpose of RESTful API design. Is this the case?


Source: (StackOverflow)

Testing breeze application

I am doing an application with durandal, breeze, and knockout. I have started to implement some test. The first problem that I have had is to decide what I should test and what not. I know that I should test everything, but it is not always possible in a little company.

My second problem is how I can test my calls to the server. I have seen some information in the breeze page about testing. Also I have seen the DocCode example. But I would like to know more opinions about how I can do that.

My questions are:

  1. What do I should test in the breeze calls?
  2. I would like to test this, emulating the backend. Is it possible? Any example?
  3. Any advice or comment would be great

Source: (StackOverflow)

Using Breeze.js without Entity Framework

We are trying to develop a SPA using similar techniques and technologies as John Papa's Pluralsight courses (e.g., Web API, knockout, jquery, etc.). However, as a company, we decided to not use Entity Framework. We want to write our server-side data layer(s) using standard ADO.NET.

Now, we're trying to possibly integrate Breeze into our solution. However, even though the Breeze web site says they are not tied to Microsoft, it appears that if you don't use EF, you're going to be in for a long and painful journey with Breeze.

We tried evaluating the NoDB Breeze example, but that thing is very convoluted and difficult to understand (as well as figure out how to implement it in a standard layered arch on the server-side - everything seems to be tightly coupled and is just put in the Models folder of a MVC/Web API project).

So, my question(s) are:

-- Is Breeze the wrong choice for a client-side data library if you're not using EF?

-- If Breeze can be easily made to not use EF and using just straight ADO.NET on the server-side, is there a better example or documentation showing how to do this?

-- Given that our SPA implementation closely resembles John Papa's SPA arch with durandal, knockout, Web API, etc., except (again) we're not using EF, is there a better choice for us than Breeze?

-- And then there's SignalR... We plan on implementing SignalR later, does Breeze even work with SignalR?

Thanks!


Source: (StackOverflow)

A data persistence library for AngularJs [closed]

There is an alpha for Ember Js and also Persistence. Is there something similar for AngularJs (or it is in plan)? Maybe there is something that is framework independent?

What I need is actual library which enables these:

  1. To define my object model
  2. To define relations between models (hasMeny, foreignKey)
  3. To enable REST calls and caching of models on client

UPDATE

I found these (credits go to Miroslav)


Source: (StackOverflow)

Why does HotTowel include Breeze?

This may sound like a dumb question on the surface, but why does the Hot Towel SPA Template include Breeze at all?

I've been spending the last few days learning Hot Towel and its dependencies, and as far as I can tell, nothing in the template actually uses Breeze. Perhaps that is going to change with some future release?

Sure, Breeze is a good library. But it's bound to CRUD methodology and requires you design your ApiControllers a particular way. (Metadata, SaveChanges, etc.) see here

It also guides you to Entity Framework. While this is more of a soft-dependency, since Breeze also shows a sample without it, it still guides you down a similar pattern of implementation using a modified repository pattern.

If you are using a NoSQL datastore, or CQRS patterns instead of CRUD, then Breeze becomes very difficult to use. There are alternative libraries for data access that work well in this style, such as AmplifyJS.

But the rest of Hot Towel is excellent! I especially like Durandal. So the question begs, if the template isn't actually doing any data access - why include any data access component at all? It would be better to ship it without Breeze, and if the end-user wants to use Breeze, or Amplify, or whatever - then so be it. The rest of Hot Towel would continue to shine as a great SPA implementation.


Source: (StackOverflow)

Breeze Sharp - Expand not working with lambda

When I attempt to expand a navigation property via lambda like so:

query = query.Expand(x => x.Dealers);

My query fails with

This is a failure message

Inner Exception

Inner Exception

Inner Exception Message:

The expression 'x => x.Dealers' is not a valid expression for navigation path. The only supported operations inside the lambda expression body are MemberAccess and TypeAs. The expression must contain at least one MemberAccess and it cannot end with TypeAs.

Yet when I attempt to expand via a string parameter:

query = query.Expand("Dealers");

Everything appears to work correctly.

My "Region" Breeze Client Entity:

public class Region : BaseEntity
{
    public Region();

    public NavigationSet<Dealership> Dealers { get; set; }
    public string Name { get; set; }
    public Region Parent { get; set; }
    public int? ParentId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int RegionId { get; set; }
    public string ShortName { get; set; }
    public RegionType Type { get; set; }
}

My Dealership navigation entity:

public class Dealership : BaseEntity
{
    public Dealership();

    public DateTime ActiveFrom { get; set; }
    public DateTime? ActiveTo { get; set; }
    public Brand Brand { get; set; }
    [ForeignKey("Brand")]
    public int BrandId { get; set; }
    public string DealerCode { get; set; }
    public DealerGroup DealerGroup { get; set; }
    [ForeignKey("DealerGroup")]
    public int? DealerGroupId { get; set; }
    public virtual NavigationSet<DealerIR> DealerIRs { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int DealershipId { get; set; }
    public bool IsActive { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string Line3 { get; set; }
    public string Line4 { get; set; }
    public string Line5 { get; set; }
    public string Name { get; set; }
    public string PostCode { get; set; }
    public Region Region { get; set; }
    [ForeignKey("Region")]
    public int RegionId { get; set; }
}

My latest attempt was to make the foreign key relationship explicit via the "ForeignKey" data annotation, but the resulting error is still the same.

I'm using breeze sharp v0.6.0.3.

UPDATE 1: It's not the exact same query as above, but same result. Just a screenshot from the Breeze.Sharp source code I've been stepping through. Larger image here

enter image description here


Source: (StackOverflow)

Breeze error: Illegal construction - use 'or' to combine checks

I met this Breeze error

[Illegal construction - use 'or' to combine checks]

on Chrome when loading the edit page of an entity. When I refresh the page, the error message no longer appears. This error happens randomly, irregularly on my site. I could not reproduce it using a specified scenario, just met it by random.

I see this error message inside Breeze code

if (curContext.prevContext === null) {
    curContext.prevContext = context;
    // just update the prevContext but don't change the curContext.
    return that;
} else if (context.prevContext === null) {
    context.prevContext = that._context;
} else {
    throw new Error("Illegal construction - use 'or' to combine checks");
}

Could you please tell me: based on above block of code, in which cases this error is thrown?

Thanks a lot.


Source: (StackOverflow)