Exemplo n.º 1
0
        public void Setup()
        {
            var injections = new Injections();

            _userService = injections.userService;

            var userRepository = injections.userRepository;

            userRepository.Insert(new User()
            {
                Username  = "******",
                Email     = "*****@*****.**",
                Password  = Utilities.Crypt.CreateMD5("1"),
                IsAllowed = false
            });
            userRepository.Insert(new User()
            {
                Username  = "******",
                Email     = "*****@*****.**",
                Password  = Utilities.Crypt.CreateMD5("1"),
                IsAllowed = true
            });
            userRepository.Insert(new User()
            {
                ConfirmToken = "we-want-to-confirm-this"
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Inject and prepare GameObjects that reside in the scene
        /// that have not been previously bound using Bind&lt;T&gt;
        /// </summary>
        /// <param name="view"></param>
        public void InjectView(IViewBase view)
        {
            var injections = new Injections(this, view.GetType());

            injections.Inject(view);
            Prepare(view);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Marque,NumLot,DateInjection,DateRappel,TypeVaccin")] Injections injections)
        {
            if (id != injections.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(injections);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!InjectionsExists(injections.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(injections));
        }
Exemplo n.º 4
0
        public ActionResult Produtos()
        {
            var products = ConfigDB.Model.Produtos.ToList();

            ViewBag.Products = products;
            Injections.LayoutInjection(this);
            return(View());
        }
Exemplo n.º 5
0
        public ActionResult Produtos()
        {
            var products = MaisLifeModel.DatabaseContext.Model.produto.ToList();

            ViewBag.Products = products;
            Injections.LayoutInjection(this);
            return(View());
        }
Exemplo n.º 6
0
        public void RemoveInjectionOf(PropertyInfo property)
        {
            var injection = Injections
                            .SingleOrDefault(x => x.Property == property);

            if (injection != null)
            {
                injections.Remove(injection);
            }
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Create([Bind("Id,Marque,NumLot,DateInjection,DateRappel,TypeVaccin")] Injections injections)
        {
            if (ModelState.IsValid)
            {
                _context.Add(injections);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(injections));
        }
Exemplo n.º 8
0
        public ActionResult EnderecoEPagamento()
        {
            usuario user = (usuario)HttpContext.Session["user"];

            if (user != null)
            {
                Injections.LayoutInjection(this);
                return(View());
            }

            return(RedirectToAction("CadastroELogin", "Home"));
        }
        /// <summary>
        /// Gera um Centro de Custo com base na Model View
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static CentroDeCusto GetModel(CentroDeCustoModelView c)
        {
            UsuariosDAO   cDAO = Injections.UsuarioInject();
            CentroDeCusto cc   = new CentroDeCusto();

            cc.Aprovador          = cDAO.GetById(c.Aprovador);
            cc.Codigo             = c.Codigo;
            cc.Descricao          = c.Descricao;
            cc.DescricaoExtendida = c.Codigo + " - " + c.Descricao;
            cc.Id = c.Id;

            return(cc);
        }
        public TestScriptClassWithoutInterfaceTemplate(ITestApi testApi)
        {
            Usings.Add("System");
            Usings.Add("System.Linq");
            Usings.Add("System.Threading.Tasks");

            Members.AddRawContent("$$code$$");

            Injections.AddProperty("Api", () => testApi);

            Members.AddMethod("CallApi", "Api.DoSomething(\"Call\");");

            Members.AddProperty("TestText", "string", "return \"SomeText\";", "Api.DoSomething(value);");
        }
Exemplo n.º 11
0
        public ActionResult Produto(int id)
        {
            var products = ConfigDB.Model.Produtos;
            var product  = products.FirstOrDefault(f => f.Id == id);

            if (product != null)
            {
                ViewBag.Products = products.ToList();
                ViewBag.Product  = product;
                Injections.LayoutInjection(this);
                return(View());
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 12
0
        public ActionResult Produto(int id)
        {
            var products = MaisLifeModel.DatabaseContext.Model.produto;
            var product  = products.FirstOrDefault(f => f.id == id);

            if (product != null)
            {
                ViewBag.Products = products.ToList();
                ViewBag.Product  = product;
                Injections.LayoutInjection(this);
                return(View());
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 13
0
        public ActionResult Perfil()
        {
            Injections.LayoutInjection(this);

            usuario user = (usuario)HttpContext.Session["user"];

            if (user == null)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.User = user;
                return(View());
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Create service.
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="injections"></param>
        /// <param name="instance"></param>
        /// <returns>Service instace.</returns>
        public object CreateService(Type serviceType, Injections injections = null, object instance = null)
        {
            if (enableDebugMode)
            {
                Debug.WriteLine($"[{nameof(ServiceCreator)}] Creating service ...");
                Debug.WriteLine($"[{nameof(ServiceCreator)}] - ServiceType={serviceType}");
            }

            var objectInfo = objectInfoRegistry.GetObjectInfo(serviceType);

            object[] constructorArguments = null;

            try
            {
                constructorArguments = GetConstructorArguments(serviceType, objectInfo, injections, instance);
            }
            catch(Exception e)
            {
                throw new ServiceCreationException($"Couldn't get constructor arguments for service type {serviceType}.", e);
            }

            object serviceInstance;

            try
            {
                serviceInstance = Activator.CreateInstance(serviceType, constructorArguments);
            }
            catch (Exception e)
            {
                // Todo
                throw e;
            }

            // Set properties.
            SetPropertyInjections(objectInfo, serviceInstance);

            if (injections != null && injections.DecoratorInjection.HasValue)
            {
                serviceInstance = CreateService(
                    injections.DecoratorInjection.Value.ImplementationType.Value,
                    injections.DecoratorInjection.Value.Injections.ValueOrDefault,
                    serviceInstance);
            }

            return serviceInstance;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Process the resolution.
        /// </summary>
        /// <param name="resolution">Resolution to be processed.</param>
        /// <returns>Service instance.</returns>
        public object Process(Resolution resolution)
        {
            Argument.NotNull(nameof(resolution), resolution);

            if (enableDebugMode)
            {
                Debug.WriteLine($"[{nameof(ResolutionProcessor)}] Processing the following resolution:");
                Debug.WriteLine($"[{nameof(ResolutionProcessor)}] - InterfaceType = {resolution.InterfaceType.FullName}");
                Debug.WriteLine($"[{nameof(ResolutionProcessor)}] - Name = '{(resolution.Name.HasValue ? resolution.Name.Value : "")}'");
            }

            // Retrieve registration process.
            var registrationProcess = registrationProcessRegistry.GetProcess(
                resolution.InterfaceType,
                resolution.Name.HasValue ? resolution.Name.Value : "");

            // When the process has an instance, return it.
            // The instance is set, when the instance was given when
            // registrating the service or when 'CreateOnResolve' is false.
            if (registrationProcess.Instance.HasValue)
            {
                return(registrationProcess.Instance.Value);
            }

            Injections injections = null;

            // If the resolution defined
            if (resolution.Injections.HasValue)
            {
                injections = resolution.Injections.Value;
            }

            if (registrationProcess.Registration.Injections.HasValue)
            {
                injections = registrationProcess.Registration.Injections.Value;
            }

            return(serviceCreator.CreateService(
                       registrationProcess.Registration.ImplementationType.Value,
                       injections));
        }
Exemplo n.º 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Injections injections = new Injections(services);

            injections.LoadInjections();
            services.AddControllersWithViews();

            var signingKey = AppSettings.SymmetricKey();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.AllowAnyHeader().AllowAnyMethod().AllowCredentials();
                });
            });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = signingKey,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = false,
                    ValidateIssuerSigningKey = true
                };
            });

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Exemplo n.º 17
0
        public bool Bind <TInterface, TImpl>()
            where TInterface
        : TBase
            where TImpl
        : TInterface
        {
            var ity = typeof(TInterface);

            if (_bindings.ContainsKey(ity))
            {
                Debug.Log($"<color=red>Registry has already bound {ity} to {typeof(TImpl)}</color>");
                return(false);
            }

            // TODO: combine these to one lookup.
            // That is, put the TImpl into PrepareModel, and parameterise it.
            _bindings[ity]   = typeof(TImpl);
            _injections[ity] = new Injections(this, typeof(TImpl));

            return(true);
        }
Exemplo n.º 18
0
        public ActionScriptClassTemplate(IClassFactory classFactory)
        {
            Usings.Add("System");
            Usings.Add("System.Linq");
            Usings.Add("System.Threading.Tasks");
            Usings.Add("CreativeCoders.SmartHal.Kernel.Base.Items");
            Usings.Add("CreativeCoders.SmartHal.Kernel.Base.Items.DataTypes");
            Usings.Add("CreativeCoders.SmartHal.Scripting.ActionScripts");
            Usings.Add("CreativeCoders.SmartHal.Scripting.Base.Api");
            Usings.Add("CreativeCoders.SmartHal.Scripting.Base.ActionScripts.Triggers");
            Usings.Add("CreativeCoders.SmartHal.Scripting.Base.ActionScripts");

            ImplementsInterfaces.Add(nameof(IActionScriptObject));

            Members.AddRawContent("$$code$$");

            Injections.AddProperty("Items", classFactory.Create <IItemsScriptApi>);
            Injections.AddProperty("Trigger", classFactory.Create <ITriggerApi>);

            Members.AddRawContent("public IItemApi Item(string itemName) => Items.GetItem(itemName);");
        }
Exemplo n.º 19
0
        public virtual bool Bind <TInterface, TImpl>(TImpl impl, bool single = true)
            where TInterface : TBase
            where TImpl : TInterface
        {
            var ity = typeof(TInterface);

            if (single && _singles.ContainsKey(ity))
            {
                Warn($"Already have singleton value for {ity}");
                return(false);
            }

            var prep = new Injections(this, typeof(TImpl));
            var obj  = Prepare(prep.Inject(impl, ity, impl));

            if (single)
            {
                _singles[ity] = obj;
            }
            _injections[ity] = prep;

            return(true);
        }
Exemplo n.º 20
0
        private void CollapseInjections(string nextTagName)
        {
            if (Injections.Count > 0)
            {
                var lastInjection = Injections.Last();

                var openInjectionTags      = OpenTags.Take(lastInjection.Length).ToList();
                var openInjectionTagsCount = openInjectionTags.Count;

                if (!string.IsNullOrEmpty(nextTagName))
                {
                    openInjectionTags.Insert(0, nextTagName);
                }

                var isLastInjectionActiveOnStack = lastInjection.SequenceEqual(openInjectionTags);

                if (!isLastInjectionActiveOnStack)
                {
                    Injections.Pop();
                    CloseTagsInternal(openInjectionTagsCount);
                }
            }
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Injeção de dependencias
            Injections.Register(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //registrando a classe DomainProfile do AutoMapper
            Mapper.Initialize(m => {
                m.AddProfile <EntityToContractProfile>();
                m.AddProfile <ContractToEntityProfile>();
            });

            //Incluir Swagger
            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1",
                             new Info
                {
                    Title          = "Projeto Asp.Net Core WEB API",
                    Version        = "v1",
                    Description    = "Namtar - Deus Sumério do Destino",
                    TermsOfService = "None",
                    Contact        = new Contact
                    {
                        Name  = "Nelson Neto",
                        Email = "*****@*****.**" //,
                                                         //Url = "https://twitter.com/spboyer"
                    },
                    //License = new License
                    //{
                    //    Name = "Use under LICX",
                    //    Url = "https://example.com/license"
                    //}
                });
            });
        }
Exemplo n.º 22
0
        // GET: Home
        public ActionResult Index()
        {
            Injections.LayoutInjection(this);
            ViewBag.patners = MaisLifeModel.DatabaseContext.Model.parceiro.ToList();

            var products = MaisLifeModel.DatabaseContext.Model.produto.ToList();

            var slideProducts = new List <List <produto> >();
            var count         = 0;
            var total         = 0;

            var x = new List <produto>();

            foreach (var product in products)
            {
                if (count == 0)
                {
                    x = new List <produto>();
                }

                x.Add(product);

                count++;
                total++;

                if (count == 3 || total == products.Count())
                {
                    slideProducts.Add(x);
                    count = 0;
                }
            }

            ViewBag.SlideProducts = slideProducts;

            return(View());
        }
Exemplo n.º 23
0
        // GET: Home
        public ActionResult Index()
        {
            Injections.LayoutInjection(this);
            ViewBag.patners = ConfigDB.Model.Parceiros.ToList();

            var products = ConfigDB.Model.Produtos.ToList();

            var slideProducts = new List <List <Produto> >();
            var count         = 0;
            var total         = 0;

            var x = new List <Produto>();

            foreach (var product in products)
            {
                if (count == 0)
                {
                    x = new List <Produto>();
                }

                x.Add(product);

                count++;
                total++;

                if (count == 3 || total == products.Count)
                {
                    slideProducts.Add(x);
                    count = 0;
                }
            }

            ViewBag.SlideProducts = slideProducts;

            return(View());
        }
Exemplo n.º 24
0
 /// <summary>
 /// Build.
 /// </summary>
 /// <returns>Constructor injection.</returns>
 public ConstructorInjection Build()
 {
     return(new ConstructorInjection(
                Injections != null ? Injections.Concat(injections) : injections,
                InjectionBehaviour));
 }
Exemplo n.º 25
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddJsonOptions(opt =>
            {
                var serializerOptions = opt.JsonSerializerOptions;
                serializerOptions.IgnoreNullValues         = true;
                serializerOptions.IgnoreReadOnlyProperties = false;
                serializerOptions.WriteIndented            = true;
            })
            .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var result = new BadRequestObjectResult(context.ModelState);

                    result.ContentTypes.Add(MediaTypeNames.Application.Json);
                    //result.ContentTypes.Add(MediaTypeNames.Application.Xml);
                    return(result);
                };
            });
            //.AddNewtonsoftJson(options =>
            //{
            //    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            //    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            //});

            if (Environment.IsDevelopment())
            {
                services.AddControllers(opts =>
                {
                    opts.Filters.Add(new AllowAnonymousFilter());
                });
            }

            services.Configure <GzipCompressionProviderOptions>(
                options => options.Level = System.IO.Compression.CompressionLevel.Optimal);

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });

            services.AddDbContext <DbContext, AplicacaoContext>(opt => opt
                                                                .UseSqlServer(Configuration.GetConnectionString("Aplicacao"), options =>
            {
                options.EnableRetryOnFailure(
                    maxRetryCount: 10,
                    maxRetryDelay: TimeSpan.FromSeconds(30),
                    errorNumbersToAdd: null);
            }
                                                                              )
                                                                .EnableSensitiveDataLogging(Environment.IsDevelopment())
                                                                .UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll));


            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = Configuration.GetConnectionString("Redis");
                options.InstanceName  = "MITArq-";
            });

            //https://docs.microsoft.com/pt-br/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
            services.AddOptions();

            services.AddAutoMapper(typeof(Startup));

            // Extension
            services.AddSwaggerConfigAplicacao();

            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.ApiVersionReader  = new HeaderApiVersionReader("x-api-version");
                o.ApiVersionReader  = new HeaderApiVersionReader("x-api-aplicacao");
            });

            // Extension
            services.AddServiceCORSAplicacao();

            // Extension
            services.AddRegisterServicesAplicacao();

            Injections.SetSecurity(services, Configuration);

            services.AddApplicationInsightsTelemetry();

            services.ConfigureTelemetryModule <QuickPulseTelemetryModule>((module, o) =>
            {
                module.AuthenticationApiKey = Configuration.GetValue("ApplicationInsights:AuthenticationApiKey", string.Empty);
            });
        }
Exemplo n.º 26
0
        public ActionResult Carrinho(int id, int local)
        {
            // CHECAMOS DE FOI PASSADO ALGUM PRODUTO PARA A PÁGINA
            if (id > 0)
            {
                var product = ConfigDB.Model.Produtos.FirstOrDefault(f => f.Id == id);
                // CHECAMOS DE O PRODUTO PASSADO EXISTE
                if (product != null)
                {
                    Usuario user = (Usuario)HttpContext.Session["user"];
                    // CHECAMOS DE HÁ ALGUM USUÁRIO LOGADO
                    if (user != null)
                    {
                        Carrinho cart = user.Carrinhos.FirstOrDefault(f => f.Status == "Ativo");
                        // CHECAMOS SE HÁ ALGUM CARRINHO ATIVO
                        if (cart == null)
                        {
                            cart = new Carrinho()
                            {
                                Usuario1 = user,
                                Status   = "Ativo"
                            };

                            ConfigDB.Model.Add(cart);
                            if (ConfigDB.Model.HasChanges)
                            {
                                ConfigDB.Model.SaveChanges();
                            }
                        }

                        Carrinho_produto rel = cart.checkProduct(product);
                        // CHECAMOS SE O PRODUTO JÁ ESTÁ NO CARRINHO
                        if (rel == null)
                        {
                            rel = new Carrinho_produto()
                            {
                                Produto1   = product,
                                Carrinho1  = cart,
                                Quantidade = 1
                            };
                        }
                        else
                        {
                            rel.Quantidade++;
                        }

                        // SALVA/EDITA RELAÇÃO NO BANCO DE DADOS
                        ConfigDB.Model.Add(rel);
                        if (ConfigDB.Model.HasChanges)
                        {
                            ConfigDB.Model.SaveChanges();
                        }
                    }
                    else
                    {
                        Produto produto = new Produto()
                        {
                            Id = id
                        };

                        Sessions.AddProductInShoppingCart(produto);
                    }
                }
            }
            else
            {
                Usuario user = (Usuario)HttpContext.Session["user"];
                // CHECAMOS DE HÁ ALGUM USUÁRIO LOGADO
                if (user != null)
                {
                    Carrinho cart = user.Carrinhos.FirstOrDefault(f => f.Status == "Ativo");
                    if (cart == null)
                    {
                        cart = new Carrinho()
                        {
                            Usuario1 = user,
                            Status   = "Ativo"
                        };

                        ConfigDB.Model.Add(cart);
                        if (ConfigDB.Model.HasChanges)
                        {
                            ConfigDB.Model.SaveChanges();
                        }
                    }
                }
                else
                {
                    ViewBag.Cart = Sessions.FindShoppingCart();
                }
            }

            if (local != 0)
            {
                ViewBag.Local = ConfigDB.Model.Bairros.FirstOrDefault(f => f.Id == local);;
            }

            ViewBag.Locals = ConfigDB.Model.Bairros.ToList();

            Injections.LayoutInjection(this);
            return(View());
        }
 public TextFragments(Injections inject)
 {
     _inject = inject;
 }
Exemplo n.º 28
0
        public ActionResult Carrinho(int id, int local)
        {
            // CHECAMOS DE FOI PASSADO ALGUM PRODUTO PARA A PÁGINA
            if (id > 0)
            {
                var product = MaisLifeModel.DatabaseContext.Model.produto.FirstOrDefault(f => f.id == id);
                // CHECAMOS DE O PRODUTO PASSADO EXISTE
                if (product != null)
                {
                    usuario user = (usuario)HttpContext.Session["user"];
                    // CHECAMOS DE HÁ ALGUM USUÁRIO LOGADO
                    if (user != null)
                    {
                        carrinho cart = user.carrinho.FirstOrDefault(f => f.status == "Ativo");
                        // CHECAMOS SE HÁ ALGUM CARRINHO ATIVO
                        if (cart == null)
                        {
                            cart = new carrinho()
                            {
                                usuario1 = user,
                                status   = "Ativo"
                            };

                            MaisLifeModel.DatabaseContext.Model.carrinho.Add(cart);
                            //if (MaisLifeModel.DatabaseContext.Model.HasChanges)
                            MaisLifeModel.DatabaseContext.Model.SaveChanges();
                        }

                        carrinho_produto rel = cart.checkProduct(product);
                        // CHECAMOS SE O PRODUTO JÁ ESTÁ NO CARRINHO
                        if (rel == null)
                        {
                            rel = new carrinho_produto()
                            {
                                produto1   = product,
                                carrinho1  = cart,
                                quantidade = 1
                            };
                        }
                        else
                        {
                            rel.quantidade++;
                        }

                        // SALVA/EDITA RELAÇÃO NO BANCO DE DADOS
                        MaisLifeModel.DatabaseContext.Model.carrinho_produto.Add(rel);
                        //if (MaisLifeModel.DatabaseContext.Model.HasChanges)
                        MaisLifeModel.DatabaseContext.Model.SaveChanges();
                    }
                    else
                    {
                        produto produto = new produto()
                        {
                            id = id
                        };

                        Sessions.AddProductInShoppingCart(produto);
                    }
                }
            }
            else
            {
                usuario user = (usuario)HttpContext.Session["user"];
                // CHECAMOS DE HÁ ALGUM USUÁRIO LOGADO
                if (user != null)
                {
                    carrinho cart = user.carrinho.FirstOrDefault(f => f.status == "Ativo");
                    if (cart == null)
                    {
                        cart = new carrinho()
                        {
                            usuario1 = user,
                            status   = "Ativo"
                        };

                        MaisLifeModel.DatabaseContext.Model.carrinho.Add(cart);
                        //if (MaisLifeModel.DatabaseContext.Model.HasChanges)
                        MaisLifeModel.DatabaseContext.Model.SaveChanges();
                    }
                }
                else
                {
                    ViewBag.Cart = Sessions.FindShoppingCart();
                }
            }

            if (local != 0)
            {
                ViewBag.Local = MaisLifeModel.DatabaseContext.Model.bairro.FirstOrDefault(f => f.id == local);;
            }

            ViewBag.Locals = MaisLifeModel.DatabaseContext.Model.bairro.ToList();

            Injections.LayoutInjection(this);
            return(View());
        }
Exemplo n.º 29
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddControllers(opt =>
            {
                opt.Filters.Add <ExceptionFilter>();
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                options.SerializerSettings.Formatting            = Formatting.Indented;
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.WriteIndented = true;
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.IgnoreNullValues            = false;
                options.JsonSerializerOptions.IgnoreReadOnlyProperties    = false;
                options.JsonSerializerOptions.ReferenceHandler            = System.Text.Json.Serialization.ReferenceHandler.Preserve;
            })
            .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var result = new BadRequestObjectResult(context.ModelState);

                    result.ContentTypes.Add(MediaTypeNames.Application.Json);
                    result.ContentTypes.Add(MediaTypeNames.Application.Xml);

                    return(result);
                };
            });



            if (_environment.IsDevelopment())
            {
                services.AddControllers(opts =>
                {
                    opts.Filters.Add(new AllowAnonymousFilter());
                });
            }

            services
            .Configure <GzipCompressionProviderOptions>(options =>
                                                        options.Level = System.IO.Compression.CompressionLevel.Optimal)
            .AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });


            services
            .AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(_configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });

            services
            .AddDbContext <DbContext, AplicacaoContext>(opt => opt
                                                        .UseSqlServer(_configuration.GetConnectionString("AzureDatabase")
                                                                      , options =>
            {
                options
                .EnableRetryOnFailure(
                    maxRetryCount: 3,
                    maxRetryDelay: TimeSpan.FromSeconds(4),
                    errorNumbersToAdd: null)
                .MigrationsHistoryTable("MigracoesEFAplicacao", "dbo");
            }
                                                                      )
                                                        .EnableSensitiveDataLogging(_environment.IsDevelopment())
                                                        .UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll));


            services
            .AddStackExchangeRedisCache(options =>
            {
                options.Configuration = _configuration.GetConnectionString("Redis");
                options.InstanceName  = "Aplicacao-";
            });

            //https://docs.microsoft.com/pt-br/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
            services
            .AddOptions();

            services
            .AddAutoMapper(typeof(Startup));

            // Extension
            services
            .AddSwaggerConfigAplicacao(_environment);

            services
            .AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                //options.ApiVersionReader = new HeaderApiVersionReader("api-version");
                //options.ApiVersionReader = new HeaderApiVersionReader("x-api-gavea");
            })
            .AddVersionedApiExplorer(options =>
            {
                //The format of the version added to the route URL
                options.GroupNameFormat = "'v'VVV";
                //Tells swagger to replace the version in the controller route
                options.SubstituteApiVersionInUrl = true;
            });

            // Extension
            services
            .AddServiceCORSAplicacao();

            // Extension
            services
            .AddRegisterServicesAplicacao();

            Injections
            .SetSecurity(services, _configuration);

            services
            .AddApplicationInsightsTelemetry(opt =>
            {
                opt.InstrumentationKey = _configuration.GetValue("ApplicationInsights:InstrumentationKey", string.Empty);
            });

            services
            .AddHealthChecks();

            services
            .ConfigureTelemetryModule <QuickPulseTelemetryModule>((module, o) =>
            {
                module.AuthenticationApiKey = _configuration.GetValue("ApplicationInsights:AuthenticationApiKey", string.Empty);
            });

            services
            .ConfigureTelemetryModule <DependencyTrackingTelemetryModule>((module, o) =>
            {
                module.EnableSqlCommandTextInstrumentation = true;
            });
        }
Exemplo n.º 30
0
 public ActionResult CadastroELogin()
 {
     Injections.LayoutInjection(this);
     return(View());
 }