Ejemplo n.º 1
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env
                              , IResponseFormatter formatter)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware <WeatherMiddleware>();
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/middleware/function")
                {
                    await formatter.Format(context, "It is snowing in Toronto");
                }
                else
                {
                    await next();
                }
            });

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapGet("/endpoint/class", WeatherEndpoint.Endpoint);
                endpoints.MapWeather("/endpoint/class");
            });
            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Response From Terminal Middlware");
            });
        }
Ejemplo n.º 2
0
        protected IEnumerable <TOutput> ExecuteLoad <TOutput>(string loadQS, FormatType responseFormat, IDataSerializer <TOutput> serializer, IResponseFormatter <string> formatter)
        {
            Uri    loadUri           = MakeUri(SelectUri, loadQS);
            string response          = _httpHelper.Get(loadUri);
            string formattedResponse = formatter != null?formatter.Format(response) : response;

            return(serializer.DeSerialize(formattedResponse, responseFormat));
        }
Ejemplo n.º 3
0
        protected IEnumerable <TOutput> ExecuteLoad <TOutput>(string loadQS, FormatType responseFormat,
                                                              IDataSerializer <TOutput> serializer, IResponseFormatter <string> formatter, out long start, out long numFound)
        {
            var loadUri           = MakeUri(SelectUri, loadQS);
            var response          = _httpHelper.Get(loadUri);
            var formattedResponse = formatter != null?formatter.Format(response) : response;

            return(serializer.DeSerialize(formattedResponse, responseFormat, out start, out numFound));
        }
Ejemplo n.º 4
0
 public async Task Invoke(HttpContext context)
 {
     if (context.Request.Path == "/middleware/class")
     {
         await _formatter.Format(context, "It is sunny in LA");
     }
     else
     {
         await _next(context);
     }
 }
        public async Task Invoke(HttpContext context, IResponseFormatter formatter1, IResponseFormatter formatter2, IResponseFormatter formatter3)
        {
            if (context.Request.Path == "/middleware/class")
            {
                await formatter1.Format(context, string.Empty);

                await formatter2.Format(context, string.Empty);

                await formatter3.Format(context, string.Empty);
            }
            else
            {
                await next(context);
            }
        }
Ejemplo n.º 6
0
        public async Task Invoke(HttpContext context, IResponseFormatter formater1,
                                 IResponseFormatter formater2, IResponseFormatter formater3)
        {
            if (context.Request.Path == "/middleware/class")
            {
                await formater1.Format(context, "Middleware It is raining in London\n");

                await formater2.Format(context, "Middleware It is raining in London\n");

                await formater3.Format(context, "Middleware It is raining in London\n");
            }
            else
            {
                await next(context);
            }
        }
Ejemplo n.º 7
0
        public async Task Invoke(HttpContext context, IResponseFormatter formatter, IResponseFormatter formatter2, IResponseFormatter formatter3)
        {
            if (context.Request.Path == "/middleware/class")
            {
                //await context.Response.WriteAsync("WeatherMiddleware middleware class; it's raining in London");
                //await formatter.Format(context, "WeatherMiddleware middleware class USING formatter SERVICE through injected in WeatherMiddleware.Invoke() method; it's raining in London");
                await formatter.Format(context, "WeatherMiddleware middleware class with IResponseFormatter now... - 1");

                await formatter2.Format(context, "WeatherMiddleware middleware class - 2");

                await formatter3.Format(context, "WeatherMiddleware middleware class - 3");
            }
            else
            {
                await next(context);
            }
        }
        /// <summary>
        /// Recieves a DI response formatter on a "per call" basis
        /// </summary>
        /// <param name="context">HTTP context for Request and Response</param>
        /// <param name="formatter">DI'd implementation of IResponseFormatter</param>
        /// <returns>Task for async</returns>
        public async Task Invoke(HttpContext context,
                                 IResponseFormatter formatter1,
                                 IResponseFormatter formatter2,
                                 IResponseFormatter formatter3)
        {
            if (context.Request.Path == "/middleware/class")
            {
                // await context.Response.WriteAsync("Middleware Class: it is raining in London");
                // await formatter.Format(context, "Middleware Class: it is raining in London");
                await formatter1.Format(context, string.Empty);

                await formatter2.Format(context, string.Empty);

                await formatter3.Format(context, string.Empty);
            }
            else
            {
                await next(context);
            }
        }
        // method here is using Response Caching
        public async Task Endpoint_beforeP422(HttpContext context, IDistributedCache cache, IResponseFormatter formatter, LinkGenerator generator)
        {
            int  count = int.Parse((string)context.Request.RouteValues["count"]);
            long total = 0;

            for (int i = 1; i <= count; i++)
            {
                total += i;
            }
            string totalString = $"({DateTime.Now.ToLongTimeString()}) {total}";

            // adds header to response - this is the important bit to enable response caching
            // the middleware will only cache responses that have a Cache-Control header that contains a public directive. Note here the max-age sets response to be cached for 2minutes
            context.Response.Headers["Cache-Control"] = "public, max-age=120";

            string url = generator.GetPathByRouteValues(context, null, new { count = count });

            await formatter.Format(context, $"<div>({DateTime.Now.ToLongTimeString()}) Total for { count }"
                                   + $" values:</div><div>{totalString}</div>"
                                   + $" <a href={url}>RELOAD</a>"
                                   );
        }
Ejemplo n.º 10
0
        //private IResponseFormatter formatter;

        //public WeatherEndpoint(IResponseFormatter responseFormatter) {
        //    formatter = responseFormatter;
        //}

        public async Task Endpoint(HttpContext context,
                                   IResponseFormatter formatter)
        {
            await formatter.Format(context, "Endpoint Class: It is cloudy in Milan");
        }
 public static async Task Endpoint(HttpContext context, IResponseFormatter formatter)
 {
     await formatter.Format(context, "It is raining in Vancouver");
 }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              IResponseFormatter formatter)
        {
            // in chapter 14, this method is simplified.

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

            app.UseRouting();
            app.UseMiddleware <WeatherMiddleware>();

            app.Use(
                async(context, next) =>
            {
                if (context.Request.Path == "/middleware/function")
                {
                    //await formatter.Format(context, "Middleware Function: It is snowing in Chicago");
                    // singleton pattern for service use
                    // await TextResponseFormatter.Singleton
                    //                            .Format(context, "Middleware Function: It is snowing in Chicago");

                    //now we use the TypeBroker
                    // await TypeBroker.Formatter.Format(context, "Middleware Function: It is snowing in Chicago");

                    //and now, Dependency Injection
                    // IResponseFormatter formatter = app.ApplicationServices.GetService<IResponseFormatter>();
                    IResponseFormatter formatter = context.RequestServices.GetService <IResponseFormatter>();
                    await formatter.Format(context, "Middleware Function: It is snowing in Chicago");
                }
                else
                {
                    await next();
                }
            }
                );

            app.UseEndpoints(endpoints =>
            {
                // endpoints.MapGet("/endpoint/class", WeatherEndpoint.Endpoint);
                // endpoints.MapWeather("/endpoint/class");
                endpoints.MapEndpoint <WeatherEndpoint>("/endpoint/class");

                endpoints.MapGet("/endpoint/function",
                                 async context =>
                {
                    //await context.Response.WriteAsync("Endpoint Function: It is sunny in LA");
                    // use singleton
                    // await TextResponseFormatter.Singleton.Format(context, "Endpoint Function: It is sunny in LA");

                    //now we use the TypeBroker
                    // await TypeBroker.Formatter.Format(context, "Endpoint Function: It is sunny in LA");
                    // IResponseFormatter formatter = app.ApplicationServices.GetService<IResponseFormatter>();
                    IResponseFormatter formatter = context.RequestServices.GetService <IResponseFormatter>();
                    await formatter.Format(context, "Endpoint Function: It is sunny in LA");
                }
                                 );
            }
                             );

            app.Use(
                async(context, next) =>
            {
                await context.Response.WriteAsync("\nTerminal Middleware Reached");
            }
                );
        }
Ejemplo n.º 13
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseDefaultFiles();          // tells ASP.NETCore to search for index or default files
            app.UseStaticFiles();           // to pick up from wwwroot folder
            app.UseRouting();
            app.UseMiddleware <WeatherMiddleware>();

            app.Use(async(context, next) => {
                if (context.Request.Path == "/middleware/function")
                {
                    //await TextResponseFormatter.Singleton.Format(context, "Middleware FUNCTION: it's snowing in Chicago");
                    //await TypeBroker.Formatter.Format(context, "Middleware FUNCTION: it's snowing in Chicago");

                    //- page 333..the following two lines will give an exception for SCOPED services: ... so need to change to get service from the HttpContext object
                    //IResponseFormatter formatter = app.ApplicationServices.GetService<IResponseFormatter>();
                    //await formatter.Format(context, "Middleware FUNCTION USING IResponseFormatter SERVICE from app.ApplicationServices: it's snowing in Chicago");

                    IResponseFormatter formatter = context.RequestServices.GetService <IResponseFormatter>();
                    await formatter.Format(context, "Middleware FUNCTION USING IResponseFormatter SERVICE from context.RequestServices.GetService<IResponseFormatter>....needed to get from context as it's SCOPED lifecycle");
                }
                else
                {
                    await next();
                }
            });


            // **** Routes registered in the UseEndpoints() method
            app.UseEndpoints(endpoints => {
                // page 312
                //endpoints.MapGet("/endpoint/class", WeatherEndpoint.Endpoint);

                // page 322 using adapter function
                //endpoints.MapWeather("/endpoint/class");

                // page 324 using the activation utility class
                endpoints.MapEndpoint <WeatherEndpoint>("/endpoint/class");

                endpoints.MapGet("/endpoint/function", async context => {
                    //await TextResponseFormatter.Singleton.Format(context, "Endpoint function: it's sunny in LA");
                    //await TypeBroker.Formatter.Format(context, "Endpoint function: it's sunny in LA");

                    //IResponseFormatter formatter = app.ApplicationServices.GetService<IResponseFormatter>();        REPLACING THIS WITH BELOW PAGE 333
                    //await formatter.Format(context, "Endpoint function using transient IResponseFormatter service from app.ApplicationServices: it's sunny in LA");

                    IResponseFormatter formatter = context.RequestServices.GetService <IResponseFormatter>();
                    await formatter.Format(context, "Endpoint function using transient IResponseFormatter service from CONTEXT object: it's sunny in LA");
                });

                endpoints.MapGet("/single", async context => {
                    IResponseFormatter formatter = context.RequestServices.GetService <IResponseFormatter>();
                    await formatter.Format(context, "Single Service");
                });

                // here service consumer is aware there are multiple implementations of IResponseFormatter interface
                endpoints.MapGet("/multiple", async context => {
                    IResponseFormatter formatter = context.RequestServices.GetServices <IResponseFormatter>().First(f => f.RichOutput);
                    await formatter.Format(context, "Multiple Service");
                });

                // using unbound types in Services
                endpoints.MapGet("/string", async context => {
                    ICollection <string> collection = context.RequestServices.GetService <ICollection <string> >();
                    collection.Add($"Request: { DateTime.Now.ToLongTimeString() }");
                    foreach (string stringItem in collection)
                    {
                        await context.Response.WriteAsync($"String: {stringItem} \n");
                    }
                });

                endpoints.MapGet("/int", async context => {
                    ICollection <int> collection = context.RequestServices.GetService <ICollection <int> >();
                    collection.Add(collection.Count() + 1);
                    foreach (int intItem in collection)
                    {
                        await context.Response.WriteAsync($"Int: {intItem} \n");
                    }
                });
            });
        }
Ejemplo n.º 14
0
 public async Task Endpoint(HttpContext context)
 {
     //IResponseFormatter formater = context.RequestServices.GetRequiredService<IResponseFormatter>();
     await formater.Format(context, "Endpoint, it is cloudy in London");
 }
        // Commented out to move the dependency on IResponseFormatter FROM the constructor TO the EndPoint method  - so a new service object will be received for every request
        //private IResponseFormatter formatter;

        //public WeatherEndpoint(IResponseFormatter responseFormatter)
        //{
        //    formatter = responseFormatter;
        //}

        public async Task Endpoint(HttpContext httpContext, IResponseFormatter formatter)
        {
            Console.WriteLine(formatter.GetType().CustomAttributes.ToString());
            await formatter.Format(httpContext, "WeatherEndpoint class no longer static. \nDependency on IResponseFormatter service through WeatherEndpoint.Endpoint() method \n(not via constructor injection): it's cloudy in Milan");
        }
Ejemplo n.º 16
0
        // private IResponseFormatter formatter;

        // public WeatherEndpoint(IResponseFormatter responseFormatter)
        // {
        //     formatter = responseFormatter;
        // }

        public async Task Endpoint(HttpContext context, IResponseFormatter formatter)
        {
            // await context.Response.WriteAsync("Endpoint Class: It is cloudy in Milan");
            // change to DI - fetches the requisite service
            await formatter.Format(context, "Endpoint Class: It is cloudy in Milan");
        }