Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rodolfofadino/448d7f0583d5016a7bee1e6d86108ae9 to your computer and use it in GitHub Desktop.
Save rodolfofadino/448d7f0583d5016a7bee1e6d86108ae9 to your computer and use it in GitHub Desktop.
fiap-2018-02-aula-02

Aula 2

Middleware

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

ordenacao middleware

app.Use(async (context, next) =>
{
    await next.Invoke();
});

ordenacao middleware

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello from 2nd delegate.");
});
app.Use((context, next) =>
{
    //Do some work here
    context.Response.Headers.Add("X-Teste", "headerteste");
    return next();
});

app.Use(async (context, next) =>
{
   await next.Invoke();
});

app.Run(async context =>
{
    await context.Response.WriteAsync("Olá Fiap");
});

app.Map("/admin", mapApp =>
{
    mapApp.Run(async context =>
    {
        await context.Response.WriteAsync("Admin");
    });
});

app.MapWhen(context => context.Request.Query.ContainsKey("queryTeste"), mapApp =>
{
    mapApp.Run(async context =>
    {
        await context.Response.WriteAsync("Hello Fiap!");
    });
});

meu middleware

public class MeuMiddleware
{
    private readonly RequestDelegate _next;

    public MeuMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        await _next(httpContext);
    }
}
 app.UseMiddleware<MeuMiddleware>();
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseMeuMiddleware(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MeuMiddleware>();
    }

}
 app.UseMeuMiddleware();

##LogEntries

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Logentrie

##log

private static async Task<string> FormatRequest(HttpRequest request)
{
    var body = request.Body;
    request.EnableRewind();
    var buffer = new byte[Convert.ToInt32(request.ContentLength)];
    await request.Body.ReadAsync(buffer, 0, buffer.Length);
    var bodyAsText = Encoding.UTF8.GetString(buffer);
    request.Body = body;

    var messageObjToLog = new { scheme = request.Scheme, host = request.Host, path = request.Path, queryString = request.Query, requestBody = bodyAsText };

    return JsonConvert.SerializeObject(messageObjToLog);
}
context.Request.EnableRewind();

var request = await FormatRequest(context.Request);
var log = new LoggerConfiguration()
.WriteTo.Logentries("0ef490a4-fa9e-494a-980e-ecd1bd339e80")
.CreateLogger();
log.Information($"request {request}");

context.Request.Body.Position = 0;

await _next(context);

Model

public class Noticia
{
        public int Id { get; set; }
        public string Titulo { get; set; }
        public string Link { get; set; }

}

View Components

public class NoticiasViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(
        int total, bool noticiasUrgentes)
    {
        
    }

    private IEnumerable<Noticia> GetItems(int total)
    {
       
    }
}

View Components

public class NoticiasViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(
        int total, bool noticiasUrgentes)
    {
        string view = "noticias";

        if (total > 3 && noticiasUrgentes == true)
        {
            view = "noticiasurgentes";
        }

        var items = GetItems(total);
        return View(view, items);
    }

    private IEnumerable<Noticia> GetItems(int total)
    {
        for (int i = 0; i < total; i++)
        {
            yield return new Noticia() { Id = 1, Titulo = $"Noticia {i}", Link = $"http://{i}" };
        }
    }
}

View Components

@model IEnumerable<fp_web_aula_1.ViewComponents.Noticia>
<ul>
    @foreach (var item in Model)
    {
        <li>
            @item.Titulo
        </li>
    }
</ul>

View Components

@await Component.InvokeAsync("Noticias", new { total=3, noticiasUrgentes = false })

View Components

@addTagHelper *, fp_web_aula_1

View Components

<vc:noticias total="4" noticias-urgentes="true">
</vc:noticias>

Tag Helpers

public class Time
{
    public int Id { get; set; }
    public string Nome{ get; set; }
    public string Bandeira { get; set; }
    public bool Publicado { get; set; }
}

Tag Helpers

 public class TimeController : Controller
    {
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Time time)
        {
            //TODO: salvar
            return View();
        }
    }

_ViewImports

@using fp_web_aula_1
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Tag Helpers

<form asp-action="Create" asp-controller="Time" method="post">
    <input asp-for="Nome" />
    <input asp-for="Bandeira" />
    <input asp-for="Publicado" />

    <input type="submit" name="name" value="Salvar" />
</form>

Tag Helpers

public class EmailTagHelper : TagHelper
{
    private const string EmailDomain = "fiap.com";

   
    public string MailTo { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";    // Replaces <email> with <a> tag

        var address = MailTo + "@" + EmailDomain;
        output.Attributes.SetAttribute("href", "mailto:" + address);
        output.Content.SetContent(address);
    }
}

_ViewImports

@using fp_web_aula_1
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, fp_web_aula_1

Tag Helpers

<email mail-to="rodolfo"></email>

EF

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design


EF

public class Time
{
    public int TimeId { get; set; }
    public string Nome { get; set; }

    public List<Jogador> Jogadores { get; set; }
}

public class Jogador
{
    public int JogadorId { get; set; }
    public string Nome { get; set; }
    public string Posicao { get; set; }

}  

EF

public class CopaContext : DbContext
{
    public CopaContext(DbContextOptions<CopaContext> options)
        : base(options)
    { }
}

EF

public DbSet<Time> Times { get; set; }
public DbSet<Jogador> Jogadores { get; set; }

EF

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = 
    @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<CopaContext>(options => options.UseSqlServer(connection));
}

EF

Add-Migration InitialCreate

EF

Update-Database
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment