Paul
Paul

Reputation: 75

Example ASP.Net Core Breeze server with angular/breeze client code?

Is there example code of a breeze/angular client app using ASP.Net Core Breeze server?

It looks like there are the following Nuget packages:- Breeze.AspNetCore.NetCore and Breeze.Composite.AspNetCore.EF6

It would be really helpful to have the TempHire example using this technology.

Can you point me in the right direction? re. frontend/backend code example

Any help appreciated.

Upvotes: 0

Views: 630

Answers (2)

Steve Schmitt
Steve Schmitt

Reputation: 3209

Please see this example: https://github.com/Breeze/northwind-demo

It is a full working example with a .NET Core 2.2 backend and Angular 8 front end, and includes TypeScript class generation so that the client-side TypeScript model matches the server-side C# model and database.

The example repo includes steps to create the entire app from scratch.

Upvotes: 0

Piotr Stulinski
Piotr Stulinski

Reputation: 9471

This is a bit of a journey because right now there are a lot of moving parts. I have had some success in getting this to work but there are some limitations for example i cannot use .expand('entityName') on the client.

I am using .NET CORE 3.0 preview with Entity Framework Core. I have attached an image of all the dependencies i have installed. Not all of them are required but probably used in a API project.

The most important parts of the below code snippet are to setup the NewtonsoftJson settings.

public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers().AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

            //THE BELOW LINE IS IMPORTANT OTHERWISE IT WILL CAMELCASE TO THE SERVER
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();

            //THE BELOW LINE PREVENTS LOOPING ENTITY REFs
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });






        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        var connection = @"Server=tcp:XXXXX.database.windows.net,1433;Initial Catalog=DBNAME;Persist Security Info=False;User ID=XXX;Password=XXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

        //THIS IS WHERE YOU ARE GOING TO MAKE YOUR CONTEXT INJECTABLE
        services.AddDbContext<YOURCONTEXTContext>(options => options.UseSqlServer(connection, x => x.UseNetTopologySuite()));

        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Token);
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();



        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

}

Then you need to setup your breeze controller:

using Microsoft.AspNetCore.Authorization;
using System.Linq;
using HB.Data.Models;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using System;
using Microsoft.AspNetCore.Mvc;
using Breeze.AspNetCore;
using HB.API.Manager;
using HB.BusinessFacade.Business;

using GeoAPI.Geometries;

using NetTopologySuite.Geometries;
using Breeze.Persistence;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace HB.API.Controllers
{


[BreezeQueryFilter]
[Route("api/[controller]/[action]")]
public class BreezeController : ControllerBase
{

    private YOURCONTEXTContext _context;
    private hbPersistenceManager PersistenceManager;
    string UserID;


    public BreezeController(YOURCONTEXTContext context, IHttpContextAccessor httpContextAccessor)
    {
        this._context = context;
        PersistenceManager = new hbPersistenceManager(context);
        //this.UserID = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    }


    [HttpGet]
    public string Metadata()
    {
        return PersistenceManager.Metadata();
    }
}

And then just a little helper that i use for the PersistenceManager

using HB.Data.Models;
using Breeze.Persistence.EFCore;
namespace HB.API.Manager
{
    public class hbPersistenceManager : EFPersistenceManager<YOURCONTEXTContext>
    { 
       public hbPersistenceManager(YOURCONTEXTContext dbContext) : base(dbContext) { }
    }
}

enter image description here

Upvotes: 0

Related Questions