public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddInstance<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddInstance<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddInstance<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
        public void InitializeDoesNotThrowIfRequestTelemetryIsUnavailable()
        {
            var ac = new HttpContextAccessor() { HttpContext = new DefaultHttpContext() };

            var initializer = new OperationNameTelemetryInitializer(ac, new DiagnosticListener(TestListenerName));

            initializer.Initialize(new RequestTelemetry());
        }
        public void InitializeDoesNotThrowIfHttpContextIsUnavailable()
        {
            var ac = new HttpContextAccessor() { HttpContext = null };
            
            var initializer = new ClientIpHeaderTelemetryInitializer(ac);

            initializer.Initialize(new RequestTelemetry());
        }
        public void InitializeDoesNotThrowIfRequestTelemetryIsUnavailable()
        {
            var ac = new HttpContextAccessor() { HttpContext = new DefaultHttpContext() };

            var initializer = new WebUserTelemetryInitializer(ac);

            initializer.Initialize(new RequestTelemetry());
        }
        public void InitializeDoesNotThrowIfRequestTelemetryIsUnavailable()
        {
            var ac = new HttpContextAccessor() { HttpContext = new DefaultHttpContext() };

            var initializer = new OperationNameTelemetryInitializer(ac, new Notifier(new ProxyNotifierMethodAdapter()));

            initializer.Initialize(new RequestTelemetry());
        }
        public void GetServiceCheckNotNull()
        {
            var accessor     = new HttpContextAccessor();
            var mockProvider = new Mock <IServiceProvider>();

            mockProvider.Setup(p => p.GetService(typeof(IHttpContextAccessor))).Returns(accessor);
            var service = mockProvider.Object.GetServiceCheckNotNull <IHttpContextAccessor>();

            Assert.Equal(accessor, service);
        }
Ejemplo n.º 7
0
        public static ServiceCollection GetServiceCollectionWithContextAccessor()
        {
            var services = new ServiceCollection();
            IHttpContextAccessor contextAccessor = new HttpContextAccessor();

            services.AddSingleton <IHttpContextAccessor>(contextAccessor);
            services.AddSingleton <IHostingEnvironment>(new HostingEnvironment());
            services.AddSingleton <DiagnosticListener>(new DiagnosticListener("TestListener"));
            return(services);
        }
Ejemplo n.º 8
0
        public async Task GetImagesByProductIdAsyncShouldReturnImagesSuccessfully()
        {
            var options = new DbContextOptionsBuilder <MyCalisthenicAppDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new MyCalisthenicAppDbContext(options);

            IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();

            var usersService = new UsersService(httpContextAccessor, dbContext, null);

            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MyCalisthenicAppProfile());
            });

            var mapper = mockMapper.CreateMapper();

            var categoriesService = new CategoriesService(dbContext, mapper);

            var postsService = new PostsService(dbContext, mapper, usersService, categoriesService);

            var productsService = new ProductsService(dbContext, mapper, usersService, categoriesService);

            var programsService = new ProgramsService(dbContext, mapper, usersService, categoriesService);

            var exercisesService = new ExercisesService(dbContext, mapper, usersService, categoriesService);

            var imagesService = new ImagesService(dbContext, mapper, postsService, exercisesService, productsService, programsService);

            for (int i = 0; i < 4; i++)
            {
                var image = new Image
                {
                    Url       = ImageUrl,
                    ProductId = ProductId,
                };

                await dbContext.Images.AddAsync(image);

                await dbContext.SaveChangesAsync();
            }

            var expected = await imagesService.GetImagesByProductIdAsync(ProductId);

            var counter = 0;

            foreach (var img in expected)
            {
                counter++;
            }

            Assert.Equal(4, counter);
        }
Ejemplo n.º 9
0
    public void Customize(IFixture fixture)
    {
        fixture.Customize <BackOfficeIdentityUser>(
            u => u.FromFactory <string, string, string>(
                (a, b, c) => BackOfficeIdentityUser.CreateNew(new GlobalSettings(), a, b, c)));

        fixture
        .Customize(new ConstructorCustomization(typeof(UsersController), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(InstallController), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(PreviewController), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(MemberController), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(BackOfficeController), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(MemberManager), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(DatabaseSchemaCreatorFactory), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(BackOfficeServerVariables), new GreedyConstructorQuery()))
        .Customize(new ConstructorCustomization(typeof(InstallHelper), new GreedyConstructorQuery()));

        // When requesting an IUserStore ensure we actually uses a IUserLockoutStore
        fixture.Customize <IUserStore <BackOfficeIdentityUser> >(cc =>
                                                                 cc.FromFactory(Mock.Of <IUserLockoutStore <BackOfficeIdentityUser> >));

        fixture.Customize <IUmbracoVersion>(
            u => u.FromFactory(
                () => new UmbracoVersion()));

        fixture.Customize <HostingSettings>(x =>
                                            x.With(settings => settings.ApplicationVirtualPath, string.Empty));

        fixture.Customize <BackOfficeAreaRoutes>(u => u.FromFactory(
                                                     () => new BackOfficeAreaRoutes(
                                                         Options.Create(new GlobalSettings()),
                                                         Mock.Of <IHostingEnvironment>(x =>
                                                                                       x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                         Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run),
                                                         new UmbracoApiControllerTypeCollection(Enumerable.Empty <Type>))));

        fixture.Customize <PreviewRoutes>(u => u.FromFactory(
                                              () => new PreviewRoutes(
                                                  Options.Create(new GlobalSettings()),
                                                  Mock.Of <IHostingEnvironment>(x =>
                                                                                x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                                                  Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run))));

        var httpContextAccessor = new HttpContextAccessor {
            HttpContext = new DefaultHttpContext()
        };

        fixture.Customize <HttpContext>(x => x.FromFactory(() => httpContextAccessor.HttpContext));
        fixture.Customize <IHttpContextAccessor>(x => x.FromFactory(() => httpContextAccessor));

        fixture.Customize <WebRoutingSettings>(x =>
                                               x.With(settings => settings.UmbracoApplicationUrl, "http://localhost:5000"));
    }
Ejemplo n.º 10
0
        public string getUsername()
        {
            HttpContextAccessor accessor = new HttpContextAccessor();
            var username = accessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Username")?.Value;

            if (username == null)
            {
                username = "******";
            }
            return(username);
        }
Ejemplo n.º 11
0
        public async Task EditCommentAsyncShouldEditCommentSuccessfully()
        {
            var options = new DbContextOptionsBuilder <MyCalisthenicAppDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new MyCalisthenicAppDbContext(options);

            IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();

            var usersService = new UsersService(httpContextAccessor, dbContext, null);

            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MyCalisthenicAppProfile());
            });

            var mapper = mockMapper.CreateMapper();

            var commentsService = new CommentsService(dbContext, mapper, usersService);

            var user = new ApplicationUser
            {
                FirstName = UserFirstName,
                LastName  = UserLastName,
            };

            await dbContext.Users.AddAsync(user);

            await dbContext.SaveChangesAsync();

            var comment = new Comment
            {
                Id       = CommentId,
                Text     = CommentText,
                AuthorId = user.Id,
            };

            await dbContext.Comments.AddAsync(comment);

            await dbContext.SaveChangesAsync();

            var commentModel = new CommentAdminEditViewModel
            {
                Id       = CommentId,
                Text     = CommentText,
                AuthorId = user.Id,
                Rating   = CommentRating,
            };

            await commentsService.EditCommentAsync(commentModel);

            Assert.Equal(comment.Rating, commentModel.Rating);
        }
Ejemplo n.º 12
0
        public JsonApiDeserializerBenchmarks()
        {
            var            options             = new JsonApiOptions();
            IResourceGraph resourceGraph       = DependencyFactory.CreateResourceGraph(options);
            var            targetedFields      = new TargetedFields();
            var            request             = new JsonApiRequest();
            var            resourceFactory     = new ResourceFactory(new ServiceContainer());
            var            httpContextAccessor = new HttpContextAccessor();

            _jsonApiDeserializer = new RequestDeserializer(resourceGraph, resourceFactory, targetedFields, httpContextAccessor, request, options);
        }
        public List <MenuRes> GetMenuSession()
        {
            var httpContextAccessor = new HttpContextAccessor();
            var result = httpContextAccessor.HttpContext.Session.GetString("menuList");

            if (result != null)
            {
                return(Newtonsoft.Json.JsonConvert.DeserializeObject <List <MenuRes> >(result));
            }
            return(null);
        }
        public async void GetsAllOrdersForCustomer()
        {
            //Arrange
            var options = InMemoryDb("GetsCustomersOrders");

            //Act
            using (var context = new MSDbContext(options))
            {
                var customer = new Customer
                {
                    Id        = 4,
                    FirstName = "Conan",
                    LastName  = "perse",
                    Email     = "*****@*****.**"
                };
                context.Add(customer);
                context.SaveChanges();
                CreateTwoproducts(context);

                var store = new Store
                {
                    Id   = 7,
                    Name = "SomeLocation"
                };
                context.Add(store);
                context.SaveChanges();

                var order = new Order
                {
                    CustomerId = 2,
                    OrderDate  = DateTime.Now,
                    StoreId    = 3,
                };
                context.Add(order);
                order = new Order
                {
                    CustomerId = 6,
                    OrderDate  = DateTime.Now,
                    StoreId    = 5,
                };
                context.Add(order);
                context.SaveChanges();
            }
            //Assert
            using (var context = new MSDbContext(options))
            {
                IHttpContextAccessor contextAccessor = new HttpContextAccessor();
                var shoppingCartRepo = new ShoppingCart(context);
                var orderRepo        = new OrderService(context, shoppingCartRepo, contextAccessor);
                var orders           = await orderRepo.FindAsync(o => o.CustomerId == 1);

                Assert.Empty(orders);
            }
        }
Ejemplo n.º 15
0
        public void Initialize()
        {
            var userStoreMock = new Mock <IUserStore <ApplicationUser> >();
            var context       = new HttpContextAccessor {
                HttpContext = new Mock <HttpContext>().Object
            };
            var claims = new Mock <IUserClaimsPrincipalFactory <ApplicationUser> >().Object;

            userContext = new Mock <UserManager <ApplicationUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);
            signContext = new Mock <SignInManager <ApplicationUser> >(userContext.Object, context, claims, null, null, null);
        }
Ejemplo n.º 16
0
        public virtual string GetUserName()
        {
            IHttpContextAccessor _accessor = new HttpContextAccessor();

            if (_accessor.HttpContext == null)
            {
                return(string.Empty);
            }

            return(_accessor.HttpContext?.User?.Identity?.Name);
        }
        public void InitializeDoesNotThrowIfHttpContextIsUnavailable()
        {
            var ac = new HttpContextAccessor()
            {
                HttpContext = null
            };

            var initializer = new OperationNameTelemetryInitializer(ac, new DiagnosticListener(TestListenerName));

            initializer.Initialize(new RequestTelemetry());
        }
Ejemplo n.º 18
0
        private Stream GetReportContent(ReportGenerationResult reportGenerationResult)
        {
            var reportName         = HttpUtility.UrlPathEncode(reportGenerationResult.ReportName);
            var reportContent      = reportGenerationResult.ReportStream;
            var contentLength      = reportContent.Length;
            var contentDisposition = $"attachment; filename*=UTF-8''{reportName}";

            _responseProcessor.AssignFileResponseContent(
                HttpContextAccessor.GetInstance(), ContentType, contentLength, contentDisposition);
            return(reportContent);
        }
Ejemplo n.º 19
0
        public void InitializeDoesNotThrowIfRequestTelemetryIsUnavailable()
        {
            var ac = new HttpContextAccessor()
            {
                HttpContext = new DefaultHttpContext()
            };

            var initializer = new OperationNameTelemetryInitializer(ac);

            initializer.Initialize(new RequestTelemetry());
        }
Ejemplo n.º 20
0
        public static Uri GetDomin()
        {
            var        _contextAccessor = new HttpContextAccessor();
            var        request          = _contextAccessor.HttpContext.Request;
            UriBuilder uriBuilder       = new UriBuilder();

            uriBuilder.Host = request.Host.Host;
            uriBuilder.Port = request.Host.Port.Value;

            return(uriBuilder.Uri);
        }
        private Mock <SignInManager <ApplicationUser> > GetMockSignInManager()
        {
            var mockUserStore   = new Mock <IUserStore <ApplicationUser> >();
            var mockUsrMgr      = new UserManager <ApplicationUser>(mockUserStore.Object, null, null, null, null, null, null, null, null);
            var contextAccessor = new HttpContextAccessor();
            var mockUserClaimsPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <ApplicationUser> >();
            var mockOptions = new Mock <IOptions <IdentityOptions> >();
            var mockLogger  = new Mock <ILogger <SignInManager <ApplicationUser> > >();

            return(new Mock <SignInManager <ApplicationUser> >(mockUsrMgr, contextAccessor, mockUserClaimsPrincipalFactory.Object, mockOptions.Object, mockLogger.Object, null, null));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 获得IP地址
        /// </summary>
        /// <returns>字符串数组</returns>
        public static string GetIp()
        {
            HttpContextAccessor _context = new HttpContextAccessor();
            var ip = _context.HttpContext.Request.Headers["X-Forwarded-For"].ToString();

            if (string.IsNullOrEmpty(ip))
            {
                ip = _context.HttpContext.Connection.RemoteIpAddress.ToString();
            }
            return(ip);
        }
Ejemplo n.º 23
0
        public static long GetCurrentUserId()
        {
            HttpContextAccessor hca = new HttpContextAccessor();
            long?userId             = hca.HttpContext?.User?.GetUserId();

            if (userId == null)
            {
                return(0);
            }
            return(userId.Value);
        }
Ejemplo n.º 24
0
        public void InitializeDoesNotThrowIfHttpContextIsUnavailable()
        {
            var ac = new HttpContextAccessor()
            {
                HttpContext = null
            };

            var initializer = new WebSessionTelemetryInitializer(ac);

            initializer.Initialize(new RequestTelemetry());
        }
Ejemplo n.º 25
0
        public void InitializeDoesNotThrowIfHttpContextIsUnavailable()
        {
            var ac = new HttpContextAccessor()
            {
                HttpContext = null
            };

            var initializer = new DomainNameRoleInstanceTelemetryInitializer(ac);

            initializer.Initialize(new RequestTelemetry());
        }
Ejemplo n.º 26
0
        public static string IsActive(this string item, string activeClass = "active")
        {
            var routeData = new HttpContextAccessor().HttpContext.GetRouteData();

            if (routeData == null || routeData.Values["file"]?.ToString() != item)
            {
                return("");
            }

            return(activeClass);
        }
Ejemplo n.º 27
0
        public Stream DownloadReportTemplate(string templateId)
        {
            var    reportTemplateId     = new Guid(templateId);
            string templateString       = GetReportTemplate(reportTemplateId);
            var    reportCaption        = GetReportCaption(reportTemplateId);
            string contentDisposition   = $"attachment; filename*=UTF-8''{HttpUtility.UrlPathEncode(reportCaption)}.frx";
            var    reportTemplateStream = templateString.ToStream();

            WebResponseProcessor.AssignFileResponseContent(HttpContextAccessor.GetInstance(), "application/xml",
                                                           reportTemplateStream.Length, contentDisposition);
            return(reportTemplateStream);
        }
        public void TestMethod1()
        {
            IHttpContextAccessor contextAccessor = new HttpContextAccessor {
                HttpContext = new DefaultHttpContext()
            };

            string  hashPass = this.GenerateDomainPass();
            Licence _licence = new Licence(type, contextAccessor, domain, hashPass);
            bool    result   = _licence.Verify(type, contextAccessor, domain, hashPass);

            Assert.AreEqual(result, true);
        }
Ejemplo n.º 29
0
        public UserControllerTests() : base(false)
        {
            var environment         = new EnvironmentBuilder("LocationServicesClient:Username", "LocationServicesClient:Password", "LocationServicesClient:Url");
            var httpContextAccessor = new HttpContextAccessor {
                HttpContext = HttpResponseTest.SetupHttpContext()
            };

            _controller = new SheriffController(new SheriffService(Db, httpContextAccessor), new UserService(Db), environment.Configuration, Db)
            {
                ControllerContext = HttpResponseTest.SetupMockControllerContext()
            };
        }
Ejemplo n.º 30
0
        public int getUserID()
        {
            try
            {
                HttpContextAccessor accessor = new HttpContextAccessor();
                var userid = Int32.Parse(accessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "UserID")?.Value);

                return(userid);
            } catch {
                return(-1);
            }
        }
        /// <summary>
        /// Creates an <see cref="IUmbracoBuilder"/> and registers basic Umbraco services
        /// </summary>
        public static IUmbracoBuilder AddUmbraco(
            this IServiceCollection services,
            IWebHostEnvironment webHostEnvironment,
            IConfiguration config)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (config is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            IHostingEnvironment tempHostingEnvironment = GetTemporaryHostingEnvironment(webHostEnvironment, config);

            var loggingDir    = tempHostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.LogFiles);
            var loggingConfig = new LoggingConfiguration(loggingDir);

            services.AddLogger(tempHostingEnvironment, loggingConfig, config);

            // The DataDirectory is used to resolve database file paths (directly supported by SQL CE and manually replaced for LocalDB)
            AppDomain.CurrentDomain.SetData("DataDirectory", tempHostingEnvironment?.MapPathContentRoot(Constants.SystemDirectories.Data));

            // Manually create and register the HttpContextAccessor. In theory this should not be registered
            // again by the user but if that is the case it's not the end of the world since HttpContextAccessor
            // is just based on AsyncLocal, see https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/HttpContextAccessor.cs
            IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();

            services.AddSingleton(httpContextAccessor);

            var requestCache = new HttpContextRequestAppCache(httpContextAccessor);
            var appCaches    = AppCaches.Create(requestCache);

            services.ConfigureOptions <ConfigureKestrelServerOptions>();
            services.ConfigureOptions <ConfigureIISServerOptions>();
            services.ConfigureOptions <ConfigureFormOptions>();

            IProfiler profiler = GetWebProfiler(config);

            ILoggerFactory loggerFactory = LoggerFactory.Create(cfg => cfg.AddSerilog(Log.Logger, false));

            TypeLoader typeLoader = services.AddTypeLoader(
                Assembly.GetEntryAssembly(),
                tempHostingEnvironment,
                loggerFactory,
                appCaches,
                config,
                profiler);

            return(new UmbracoBuilder(services, config, typeLoader, loggerFactory, profiler, appCaches, tempHostingEnvironment));
        }
Ejemplo n.º 32
0
        private static string GetDynamicUrl(IHtmlHelper helper)
        {
            String DynamicUrl = string.Empty;
            HttpContextAccessor httpContextObj = new HttpContextAccessor();

            DynamicUrl = helper.ViewContext.HttpContext.Request.Path;
            if (DynamicUrl.IndexOf("/") == 0)
            {
                DynamicUrl = DynamicUrl.Substring(1, DynamicUrl.Length - 1);
            }
            return(DynamicUrl.Replace("Razor", "razor").Replace("razor/", ""));
        }
Ejemplo n.º 33
0
        public static void Report(this Exception ex)
        {
            HttpContext ctx = null;

            try
            {
                ctx = new HttpContextAccessor().HttpContext;
            }
            catch { }

            LogModule.OnError(ctx, ex);
        }
Ejemplo n.º 34
0
        public ConsultasEventoTeste()
        {
            repositorioEvento = new Mock<IRepositorioEvento>();
            repositorioEventoTipo = new Mock<IRepositorioEventoTipo>();
            var context = new DefaultHttpContext();
            var httpContextAcessorObj = new HttpContextAccessor();
            httpContextAcessorObj.HttpContext = context;
            servicoUsuario = new Mock<IServicoUsuario>();
            repositorioEventoTipo = new Mock<IRepositorioEventoTipo>();

            consultaEventos = new ConsultasEvento(repositorioEvento.Object, new ContextoHttp(httpContextAcessorObj), servicoUsuario.Object, repositorioEventoTipo.Object);
        }
Ejemplo n.º 35
0
        public string GetPathImage(string imageName)
        {
            if (imageName == null)
            {
                imageName = "no_image.jpg";
            }
            HttpContextAccessor httpContext = new HttpContextAccessor();
            var Current = httpContext.HttpContext;
            var path    = $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}" + "/UserImages/" + imageName;

            return(path);
        }