public List <SceneItemDto> GetAllByStatus(string userID, string deviceID, string sceneID, ItemStatus status,
                                                  int pageSize, DateTime time, out int count)
        {
            if (string.IsNullOrEmpty(sceneID))
            {
                throw new ArgumentNullException("sceneID");
            }

            using (var db = new BCEnterpriseContext())
            {
                var iSsync =
                    db.SyncStates.Any(
                        n =>
                        n.UserID == userID && n.DeviceID == deviceID &&
                        n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData);
                if (!iSsync)
                {
                    var syncSceneData = new SyncState()
                    {
                        UserID     = userID,
                        DeviceID   = deviceID,
                        ActionType = (int)TypeEnum.SceneData,
                        SyncTime   = DBTimeHelper.DBNowTime(db)
                    };

                    db.SyncStates.Add(syncSceneData);
                    if (!(0 < db.SaveChanges()))
                    {
                        var logger = log4net.LogManager.GetLogger(typeof(SceneItemManagementService));
                        logger.Error("第一次写入同步现场数据的状态失败!");
                    }
                }
            }

            var mgdb  = new MongoDbProvider <SceneItem>();
            var query = ItemStatus.All == status
                ? mgdb.GetAll(o => (o.SceneID == sceneID) && (o.UpdateTime < time))
                : mgdb.GetAll(o => (o.SceneID == sceneID) && (o.Status == status) && (o.UpdateTime < time));

            count = query.Count();
            if (pageSize < 1)
            {
                pageSize = 10;
            }
            var sceneItems = query
                             .OrderByDescending(obj => obj.CreateTime)
                             .Take(pageSize)
                             .ToList();

            using (var db = new BCEnterpriseContext())
            {
                if (0 == sceneItems.Count)
                {
                    return(new List <SceneItemDto>());
                }
                var userIds    = sceneItems.Select(o => o.UserID).ToList();
                var reUserInfo = db.FrontUsers.Where(obj => userIds.Contains(obj.UserID)).Select(o => new
                {
                    uid     = o.UserID,
                    name    = o.Name,
                    picture = o.Picture
                }).ToList();

                var re = (from item in sceneItems
                          join r in reUserInfo on item.UserID equals r.uid into tempSU
                          from t in tempSU.DefaultIfEmpty()
                          select new SceneItemDto
                {
                    Id = item.Id,
                    SceneID = item.SceneID,
                    PictureGuid = item.PictureGuid,
                    Count = item.Count,
                    Status = item.Status,
                    UserID = item.UserID,
                    CreateTime = item.CreateTime,
                    UpdateTime = item.UpdateTime,
                    Address = item.Address,
                    GPS = item.GPS,
                    Description = item.Description,
                    Images = item.Images,
                    Examines = item.Examines,
                    Comments = item.Comments,
                    Relation = item.Relation,
                    IsExamine = item.IsExamine,
                    Type = item.Type,
                    UserName = t == null ? string.Empty : t.name,
                    UserPicture = t == null ? string.Empty : UriExtensions.GetFullUrl(t.picture)
                })
                         .ToList();
                foreach (var r in re)
                {
                    r.Images = MakeUrlWithPictureName(r.Images);
                }
                return(re);
            }
        }
示例#2
0
        public void When_Authentication_Fails_AuthenticationException_Or_ConnectionUnavailableException_Is_Thrown()
        {
            var authenticator = new CramMd5Mechanism(_ioService, "authenticated", "secretw", new DefaultTranscoder());

            _ioService.SaslMechanism = authenticator;

            //The first two iterations will throw auth exceptions and then a CUE;
            //you will never find yourself in an infinite loop waiting for connections that don't exist.
            int count = 0;

            while (count < 3)
            {
                count++;
                try
                {
                    var config = new Config(new DefaultTranscoder(), OperationLifespan, UriExtensions.GetEndPoint(Address));
                    var result = _ioService.Execute(config);
                    Console.WriteLine(result.Success);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    var type = e.GetType();
                    if (type == typeof(AuthenticationException) || type == typeof(ConnectionUnavailableException))
                    {
                        continue;
                    }
                    Assert.Fail();
                }
            }
            Assert.Pass();
        }
        public void When_GetBaseViewUri_Is_Called_With_EncryptTraffic_True_Uri_Is_SSL_URI()
        {
            var configuration = new ClientConfiguration
            {
                UseSsl = true
            };

            configuration.Initialize();

            var connectionPool = new ConnectionPool <Connection>(new PoolConfiguration(), UriExtensions.GetEndPoint(_address));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            using (var server = new Server(ioStrategy, new NodeAdapter(new Node(), new NodeExt()), configuration, new BucketConfig {
                Name = "default"
            }))
            {
                var uri = server.GetBaseViewUri("default");
                Assert.AreEqual("https://localhost:18092/default", uri);
            }
        }
示例#4
0
        public IController CreateController(RequestContext requestContext, string moduleName)
        {
            requestContext.HttpContext.Items["TimeController"] = DateTime.Now;

            var        isAjax = false;
            ModuleCore module = null;

            // Проверка на авторизацию. Ловим случаи, когда авторизация не сработала в HttpApplication.
            var context = AppCore.GetUserContextManager().GetCurrentUserContext();

            if (context.IsGuest)
            {
                var moduleAuth = AppCore.Get <Plugins.Auth.ModuleAuth>();
                context = moduleAuth.RestoreUserContextFromRequest();
                if (context != null && !context.IsGuest)
                {
                    moduleAuth.RegisterEvent(EventType.CriticalError, "Нарушение процесса авторизации", null);
                    AppCore.GetUserContextManager().SetCurrentUserContext(context);
                }
            }

            try
            {
                /*
                 * Определение языка и темы
                 */
                {
                    var lang = string.Format("{0}", requestContext.RouteData.Values["language"]);

                    using (var db = this.CreateUnitOfWork())
                    {
                        var query = from Language in db.Language
                                    where Language.IsDefault != 0 || Language.ShortAlias == lang
                                    orderby(Language.ShortAlias == lang? 1 : 0) descending
                                    select Language;

                        var data = query.ToList();
                        //var sql = DB.DataContext.ExecuteQuery<DB.Language>(@"
                        //    SELECT TOP(1) *
                        //    FROM Language
                        //    WHERE IsDefault <> 0 OR ShortAlias = '" + DataManager.prepare(lang) + @"'
                        //    ORDER BY CASE WHEN ShortAlias = '" + DataManager.prepare(lang) + @"' THEN 1 ELSE 0 END DESC
                        //");
                        if (data.Count > 0)
                        {
                            var res = data.First();
                            requestContext.RouteData.Values["language"] = res.ShortAlias;
                        }
                    }
                }

                /*
                 * Ищем модуль, к которому обращаются запросом.
                 * */
                if (int.TryParse(moduleName, out int moduleId) && moduleId.ToString() == moduleName)
                {
                    module = AppCore.Get <ModulesManager <ApplicationCore> >().GetModule(moduleId);
                }
                else
                {
                    module = AppCore.Get <ModulesManager <ApplicationCore> >().GetModule(moduleName);
                }

                if (module == null)
                {
                    throw new Core.Exceptions.ErrorCodeException(HttpStatusCode.NotFound, $"Адрес '{moduleName}' не найден.");
                }

                /*
                 * Ищем контроллер, который относится к модулю.
                 * */
                var controllerType = ControllerTypeFactory.RoutingPrepareURL(requestContext.HttpContext.Request, UriExtensions.MakeRelativeFromUrl(requestContext.HttpContext.Request.Url.PathAndQuery));

                if (requestContext.RouteData.Route is Route)
                {
                    /*
                     * Анализируем адрес и устанавливаем признак, если это вызов в панель управления. Пришлось пойти на такой хак.
                     * */
                    var route = requestContext.RouteData.Route as Route;
                    if (route.Url.StartsWith("admin/madmin"))
                    {
                        isAjax = true;
                    }

                    if (isAjax)
                    {
                        HttpContext.Current.Items["isAjax"] = true;
                    }
                }

                var controller = CreateController(controllerType, module, requestContext.RouteData.Values);
                HttpContext.Current.Items["RequestContextController"] = controller;
                return(controller);
            }
            catch (Exception ex)
            {
                try
                {
                    if (module == null)
                    {
                        module = new Modules.Internal.ModuleInternalErrors();
                        module.Start(AppCore);
                    }

                    var type       = typeof(Modules.Internal.ModuleControllerInternalErrors <>).MakeGenericType(module.GetType());
                    var controller = CreateController(module, type, requestContext.RouteData.Values);
                    (controller as Modules.Internal.IModuleControllerInternalErrors).SetException(ex);
                    // todo (controller as Modules.ModuleController).IsAdminController = isErrorAdmin;

                    HttpContext.Current.Items["RequestContextController"] = controller;
                    return(controller);
                }
                catch (Exception ex2)
                {
                    Debug.WriteLine("Throw: {0}", ex2.ToString());
                    throw ex;
                }
            }
        }
        internal static IOStrategy CreateIOStrategy(INodeAdapter node)
        {
            var server         = node.Hostname.Replace("8091", node.KeyValue.ToString(CultureInfo.InvariantCulture));
            var connectionPool = new ConnectionPool <Connection>(new PoolConfiguration(), UriExtensions.GetEndPoint(server));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            return(ioStrategy);
        }
示例#6
0
 public void AssertThatNonHttpAndHttpsSchemasThrow()
 {
     Assert.Throws <ArgumentException>(() => UriExtensions.AssertUriIsHttpOrHttpsSchema(new Uri("file://somehost.com")));
     Assert.Throws <ArgumentException>(() => UriExtensions.AssertUriIsHttpOrHttpsSchema(new Uri("ftp://somehost.com")));
 }
示例#7
0
 public void AssertThatNonFileSchemasThrow()
 {
     Assert.Throws <ArgumentException>(() => UriExtensions.AssertUriIsFileSchema(new Uri("http://somehost.com")));
     Assert.Throws <ArgumentException>(() => UriExtensions.AssertUriIsFileSchema(new Uri("ftp://somehost.com")));
 }
示例#8
0
        public void TestStripApiSuffixBaseString(string input, string suffix, string expectedResult)
        {
            string result = UriExtensions.StripApiSuffixBase(input, suffix);

            Assert.Equal(result, expectedResult);
        }
        protected override IDictionary <string, string> GetUserData(string accessToken)
        {
            MicrosoftClientUserDataWithEmail graph;
            WebRequest request = WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + UriExtensions.EscapeUriDataStringRfc3986(accessToken));

            using (WebResponse response = request.GetResponse()) {
                using (Stream responseStream = response.GetResponseStream()) {
                    string json = new StreamReader(responseStream).ReadToEnd();
                    graph = JsonConvert.DeserializeObject <MicrosoftClientUserDataWithEmail>(json);
                }
            }

            var userData = new Dictionary <string, string>();

            userData.AddItemIfNotEmpty("id", graph.Id);
            userData.AddItemIfNotEmpty("username", graph.Name);
            userData.AddItemIfNotEmpty("name", graph.Name);
            userData.AddItemIfNotEmpty("link", graph.Link == null ? null : graph.Link.AbsoluteUri);
            userData.AddItemIfNotEmpty("gender", graph.Gender);
            userData.AddItemIfNotEmpty("firstname", graph.FirstName);
            userData.AddItemIfNotEmpty("lastname", graph.LastName);
            userData.AddItemIfNotEmpty("preferred_email", graph.Emails.Preferred);
            userData.AddItemIfNotEmpty("account_email", graph.Emails.Account);
            userData.AddItemIfNotEmpty("personal_email", graph.Emails.Personal);
            userData.AddItemIfNotEmpty("business_email", graph.Emails.Business);
            return(userData);
        }
示例#10
0
        public void UriHelper_CombineTests_Simple(string parent, string relative, string result)
        {
            string actual = UriExtensions.Combine(new Uri(parent), relative).ToString();

            Assert.Equal(result, actual);
        }
示例#11
0
 public void UriHelper_CombineTests_WDhtml40_970917(string parent, string relative, string result)
 {
     //https://www.w3.org/TR/WD-html40-970917/htmlweb.html
     Assert.Equal(result, UriExtensions.Combine(new Uri(parent), relative).ToString());
 }
 public void SetUp()
 {
     _endPoint       = UriExtensions.GetEndPoint(_address);
     _clientConfig   = new ClientConfiguration((CouchbaseClientSection)ConfigurationManager.GetSection("couchbaseClients/couchbase"));
     _clusterManager = new ClusterController(_clientConfig);
 }
示例#13
0
        /// <summary>
        /// Send an HTTP request to the Live endpoint, handling the case when a token refresh is required.
        /// </summary>
        /// <remarks>
        /// The caller must provide the request to send. The authentication header will be set by this method. Any error
        /// returned by the call (including failure to refresh the token) will result in an exception being thrown.
        /// </remarks>
        private async Task <HttpResponseMessage> SendLiveRequest(HttpRequestMessage request)
        {
            var qsParams = request.RequestUri.GetQueryParameters();

            qsParams["access_token"] = this.CurrentToken.AccessToken;

            var uriParts = request.RequestUri.ToString().Split(new [] { '?' }, 2);

            request.RequestUri = new Uri(uriParts[0] + UriExtensions.CombineQueryString(qsParams));

            LogRequest(request, this.liveHttpClient.BaseAddress);
            HttpResponseMessage response = await this.liveHttpClient.SendAsync(request).ConfigureAwait(false);

            LogResponse(response);

            // Check for token refresh
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                bool refreshToken = false;

                try
                {
                    JObject jObject = JObject.Parse(responseContent);
                    refreshToken = Convert.ToString(jObject["error"]["code"]) == "request_token_expired";
                }
                catch
                {
                    // There was an error parsing the response from the server.
                }

                if (refreshToken)
                {
                    // Refresh the current token
                    await this.RefreshToken().ConfigureAwait(false);

                    var newRequest = await request.Clone().ConfigureAwait(false);

                    // Resend the request using the new token
                    qsParams = newRequest.RequestUri.GetQueryParameters();
                    qsParams["access_token"] = this.CurrentToken.AccessToken;

                    uriParts = newRequest.RequestUri.ToString().Split(new[] { '?' }, 2);
                    newRequest.RequestUri = new Uri(uriParts[0] + UriExtensions.CombineQueryString(qsParams));
                    LogRequest(request, this.liveHttpClient.BaseAddress);
                    response = await this.liveHttpClient.SendAsync(newRequest).ConfigureAwait(false);

                    LogResponse(response);
                }
            }

            // Any failures (including those from re-issuing after a refresh) will be handled here
            if (!response.IsSuccessStatusCode)
            {
                var exception = new OneDriveHttpException("Live exception", response.StatusCode);
                exception.Data["Content"] = response.Content.ReadAsStringAsync().Result;
                throw exception;
            }

            return(response);
        }
        public List <SceneItemDto> GetSceneItemForSync(string userId, string device)
        {
            lock (GETSCENEITEMFORSYNCLOCK)
            {
                using (var db = new BCEnterpriseContext())
                {
                    List <string> sceneIDs = new List <string>();

                    #region get sceneIDs

                    var userDepartmentID = db.FrontUsers.Where(o => o.UserID == userId).Select(o => o.DepartmentID).FirstOrDefault().ToString();
                    if (!string.IsNullOrEmpty(userDepartmentID))
                    {
                        sceneIDs = (from scene in db.Scenes
                                    join project in db.Projects on scene.ProjectID equals project.ProjectID into tPrj
                                    from prj in tPrj.DefaultIfEmpty()
                                    where prj.Departments.Contains(userDepartmentID)
                                    select scene.SceneID
                                    ).Distinct()
                                   .ToList();
                    }

                    if (!(db.SyncStates.Any(n => n.UserID == userId && n.DeviceID == device && n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData)))
                    {
                        var syncSceneData = new SyncState()
                        {
                            UserID     = userId,
                            DeviceID   = device,
                            ActionType = (int)TypeEnum.SceneData,
                            SyncTime   = DBTimeHelper.DBNowTime(db)
                        };
                        db.SyncStates.Add(syncSceneData);
                        if (0 < db.SaveChanges())
                        {
                            return(new List <SceneItemDto>());
                        }
                        else
                        {
                            var logger = log4net.LogManager.GetLogger(typeof(SceneItemManagementService));
                            logger.Error("第一次写入同步现场数据的状态失败!");
                            return(new List <SceneItemDto>());
                        }
                    }

                    var lastSyncTime = (db.SyncStates.FirstOrDefault(
                                            n =>
                                            n.UserID == userId && n.DeviceID == device &&
                                            n.ActionType == (int)ML.BC.Infrastructure.MsmqHelper.TypeEnum.SceneData)
                                        ?? new SyncState {
                        SyncTime = DateTime.MinValue
                    }).SyncTime;

                    #endregion

                    var mgdb       = new MongoDbProvider <SceneItem>();
                    var sceneItems = mgdb.GetAll(n => (sceneIDs.Contains(n.SceneID)) && (n.UpdateTime >= lastSyncTime));

                    var userIds     = sceneItems.Select(n => n.UserID).ToList();
                    var relateUsers = db.FrontUsers.Where(obj => userIds.Contains(obj.UserID)).Select(o => new
                    {
                        uid     = o.UserID,
                        name    = o.Name,
                        picture = o.Picture
                    }).ToList();

                    var resultList = (from item in sceneItems
                                      join r in relateUsers on item.UserID equals r.uid into tempSU
                                      from t in tempSU.DefaultIfEmpty()
                                      select new SceneItemDto
                    {
                        Id = item.Id,
                        SceneID = item.SceneID,
                        PictureGuid = item.PictureGuid,
                        Count = item.Count,
                        Status = item.Status,
                        UserID = item.UserID,
                        CreateTime = item.CreateTime,
                        UpdateTime = item.UpdateTime,
                        Address = item.Address,
                        GPS = item.GPS,
                        Description = item.Description,
                        Images = item.Images,
                        Relation = item.Relation,
                        IsExamine = item.IsExamine,
                        Comments = item.Comments,
                        Type = item.Type,
                        UserName = t == null ? string.Empty : t.name,
                        UserPicture = t == null ? string.Empty : UriExtensions.GetFullUrl(t.picture)
                    })
                                     .OrderByDescending(o => o.UpdateTime)
                                     .ToList();
                    foreach (var r in resultList)
                    {
                        r.Images = MakeUrlWithPictureName(r.Images);
                    }
                    return(resultList);
                }
            }
        }
示例#15
0
 public void SetUp()
 {
     _endPoint       = UriExtensions.GetEndPoint(Address);
     _clientConfig   = new ClientConfiguration();
     _clusterManager = new ClusterController(_clientConfig);
 }
示例#16
0
 public void ShouldThrowExceptionWhenUriIsNull()
 {
     Assert.That(() => UriExtensions.GetDomain(null), Throws.ArgumentNullException);
 }
示例#17
0
 public void AssertThatUriSchemaAssertionWorksForHttpAndHttps()
 {
     UriExtensions.AssertUriIsHttpOrHttpsSchema(new Uri("http://somehost.com:23/"));
     UriExtensions.AssertUriIsHttpOrHttpsSchema(new Uri("https://someotherhost.com"));
 }
        public Account.Dtos.SessionUserDto GetSessionUser(string userId, string device)
        {
            try
            {
                if (string.IsNullOrEmpty(userId))
                {
                    throw new KnownException("用户名称不能为空!");
                }
                using (var db = new BCEnterpriseContext())
                {
                    ClearUserLoginState(db);

                    var user = (from u in db.FrontUsers
                                where u.UserID == userId
                                join ls in db.UserLoginStates on u.UserID equals ls.UserID
                                where ls.Device == device
                                join ep in db.Enterprises on u.EnterpiseID equals ep.EnterpriseID into tempEP
                                join ur in db.UserRoles on u.UserID equals ur.UserID into tempUR
                                select new
                    {
                        u,
                        ls,
                        ep = tempEP.DefaultIfEmpty().FirstOrDefault(),
                        roles = tempUR.DefaultIfEmpty().Where(n => !n.Deleted).Select(n => n.RoleID),
                        functions = (from tur in tempUR.DefaultIfEmpty()
                                     where tur.Deleted == false
                                     join r in db.RFARoles on tur.RoleID equals r.RoleID
                                     where r.Available
                                     join rf in db.RFAAuthorizations on tur.RoleID equals rf.RoleID into tempRF
                                     from trf in tempRF.DefaultIfEmpty()
                                     where !trf.Deleted
                                     select trf.FunctionID)
                    }).FirstOrDefault();

                    if (user == null)
                    {
                        throw new KnownException("用户名不存在或用户当前登录状态丢失请重新登录。");
                    }

                    #region get functionIds
                    //TODO:get it from the cache
                    var functions   = db.RFAFunctions.ToList();
                    var functionIds = new List <string>();

                    Action <string> recursionFunctions = null;
                    recursionFunctions = (functionId) =>
                    {
                        if (functionIds.Contains(functionId))
                        {
                            return;
                        }
                        functionIds.Add(functionId);

                        var tempParent = (from fun in functions
                                          where fun.FunctionID == functionId
                                          join tfun in functions on fun.ParentID equals tfun.FunctionID
                                          select tfun).FirstOrDefault();
                        if (tempParent != null)
                        {
                            recursionFunctions(tempParent.FunctionID);
                        }
                    };
                    user.functions.ToList().ForEach(recursionFunctions);
                    #endregion

                    var sessionUserDto = new Account.Dtos.SessionUserDto
                    {
                        UserID         = user.u.UserID,
                        UserName       = user.u.Name,
                        LastLoginTime  = user.u.LastDate ?? DateTime.Now,
                        LastIP         = user.u.LastIP,
                        Picture        = UriExtensions.GetFullUrl(user.u.Picture),
                        Device         = user.ls.Device,
                        Token          = user.ls.LoginToken,
                        EnterpriseID   = user.u.EnterpiseID,
                        EnterpriseName = user.ep == null ? string.Empty : user.ep.Name,
                        DepartmentID   = user.u.DepartmentID,
                        RoleIDs        = user.roles.ToArray(),
                        FunctionIDs    = functionIds.ToArray()
                    };
                    return(sessionUserDto);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#19
0
 public void AssertThatUriSchemaAssertionWorksForFile()
 {
     UriExtensions.AssertUriIsFileSchema(new Uri("file://localhost/etc/fstab"));
     UriExtensions.AssertUriIsFileSchema(new Uri("file:///c:/WINDOWS/clock.avi"));
 }
示例#20
0
 public FakeConnectionPool()
 {
     EndPoint = UriExtensions.GetEndPoint("127.0.01:8091");
 }
示例#21
0
        public IController CreateController(RequestContext requestContext, string moduleName)
        {
            requestContext.HttpContext.Items["TimeController"] = DateTime.Now;

            var isAjax = false;

            // Проверка на авторизацию. Ловим случаи, когда авторизация не сработала в HttpApplication.
            var context = AppCore.GetUserContextManager().GetCurrentUserContext();

            if (context.IsGuest)
            {
                var sessionBinder = AppCore.Get <SessionBinder>();
                context = sessionBinder.RestoreUserContextFromRequest();
                if (context != null && !context.IsGuest)
                {
                    AppCore.GetUserContextManager().SetCurrentUserContext(context);
                }
            }

            IModuleCore module = null;

            var lambda = new Func <Exception, IController>(ex =>
            {
                try
                {
                    if (module == null)
                    {
                        var moduleTmp = new ModuleInternalErrors();
                        ((IComponentStartable)moduleTmp).Start(AppCore);
                        module = moduleTmp;
                    }

                    var type       = typeof(ModuleControllerInternalErrors <>).MakeGenericType(module.QueryType);
                    var controller = CreateController(module, type, requestContext.RouteData.Values);
                    (controller as IModuleControllerInternalErrors).SetException(ex);
                    // todo (controller as Modules.ModuleController).IsAdminController = isErrorAdmin;

                    HttpContext.Current.Items["RequestContextController"] = controller;
                    return(controller);
                }
                catch (Exception ex2)
                {
                    Debug.WriteLine("Throw: {0}", ex2.ToString());
                    throw ex;
                }
            });

            try
            {
                /*
                 * Определение языка и темы
                 */
                {
                    var lang = string.Format("{0}", requestContext.RouteData.Values["language"]);

                    using (var db = new Languages.DB.DataContext())
                    {
                        var query = from Language in db.Language
                                    where Language.IsDefault != 0 || Language.ShortAlias == lang
                                    orderby(Language.ShortAlias == lang? 1 : 0) descending
                                    select Language;

                        var data = query.ToList();
                        if (data.Count > 0)
                        {
                            var res = data.First();
                            requestContext.RouteData.Values["language"] = res.ShortAlias;
                        }
                    }
                }

                if (moduleName == _routingModuleNotFound.ToString())
                {
                    var error = requestContext.HttpContext.Items[_routingModuleNotFound.ToString() + "_RoutingError"] as string;
                    return(lambda(new ErrorCodeException(HttpStatusCode.NotFound, error)));
                }
                else
                {
                    /*
                     * Ищем модуль, к которому обращаются запросом.
                     * */
                    if (int.TryParse(moduleName, out int moduleId) && moduleId.ToString() == moduleName)
                    {
                        module = (IModuleCore)AppCore.GetModulesManager().GetModule(moduleId);
                    }
                    else if (Guid.TryParse(moduleName, out Guid uniqueName) && uniqueName.ToString() == moduleName)
                    {
                        module = (IModuleCore)AppCore.GetModulesManager().GetModule(uniqueName);
                    }
                    else
                    {
                        module = (IModuleCore)AppCore.GetModulesManager().GetModule(moduleName);
                    }

                    if (module == null)
                    {
                        return(lambda(new ErrorCodeException(HttpStatusCode.NotFound, $"Адрес '{moduleName}' не найден.")));
                    }
                }

                /*
                 * Ищем контроллер, который относится к модулю.
                 * */
                var controllerType = ControllerTypeFactory.RoutingPrepareURL(requestContext.HttpContext.Request, UriExtensions.MakeRelativeFromUrl(requestContext.HttpContext.Request.Url.PathAndQuery));

                if (requestContext.RouteData.Route is Route)
                {
                    /*
                     * Анализируем адрес и устанавливаем признак, если это вызов в панель управления. Пришлось пойти на такой хак.
                     * */
                    var route = requestContext.RouteData.Route as Route;
                    if (route.Url.StartsWith("admin/madmin"))
                    {
                        isAjax = true;
                    }

                    if (isAjax)
                    {
                        HttpContext.Current.Items["isAjax"] = true;
                    }
                }

                var controller = CreateController(controllerType, module, requestContext.RouteData.Values);
                HttpContext.Current.Items["RequestContextController"] = controller;
                return(controller);
            }
            catch (Exception ex)
            {
                return(lambda(ex));
            }
        }
示例#22
0
        /// <summary>
        ///     Prepare and send the http(s) request
        /// </summary>
        /// <returns></returns>
        internal async Task SendRequest(bool enable100ContinueBehaviour, bool isTransparent, CancellationToken cancellationToken)
        {
            var upstreamProxy = Connection.UpStreamProxy;

            bool useUpstreamProxy = upstreamProxy != null && upstreamProxy.ProxyType == ExternalProxyType.Http &&
                                    !Connection.IsHttps;

            var serverStream = Connection.Stream;

            string?upstreamProxyUserName = null;
            string?upstreamProxyPassword = null;

            string url;

            if (isTransparent)
            {
                url = Request.RequestUriString;
            }
            else if (!useUpstreamProxy)
            {
                if (UriExtensions.GetScheme(Request.RequestUriString8).Length == 0)
                {
                    url = Request.RequestUriString;
                }
                else
                {
                    url = Request.RequestUri.GetOriginalPathAndQuery();
                }
            }
            else
            {
                url = Request.RequestUri.ToString();

                // Send Authentication to Upstream proxy if needed
                if (!string.IsNullOrEmpty(upstreamProxy !.UserName) && upstreamProxy.Password != null)
                {
                    upstreamProxyUserName = upstreamProxy.UserName;
                    upstreamProxyPassword = upstreamProxy.Password;
                }
            }

            if (url == string.Empty)
            {
                url = "/";
            }

            // prepare the request & headers
            var headerBuilder = new HeaderBuilder();

            headerBuilder.WriteRequestLine(Request.Method, url, Request.HttpVersion);
            headerBuilder.WriteHeaders(Request.Headers, !isTransparent, upstreamProxyUserName, upstreamProxyPassword);

            // write request headers
            await serverStream.WriteHeadersAsync(headerBuilder, cancellationToken);

            if (enable100ContinueBehaviour && Request.ExpectContinue)
            {
                // wait for expectation response from server
                await ReceiveResponse(cancellationToken);

                if (Response.StatusCode == (int)HttpStatusCode.Continue)
                {
                    Request.ExpectationSucceeded = true;
                }
                else
                {
                    Request.ExpectationFailed = true;
                }
            }
        }
        internal static IOStrategy CreateIOStrategy(string server)
        {
            var connectionPool = new ConnectionPool <Connection>(new PoolConfiguration(), UriExtensions.GetEndPoint(server));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            return(ioStrategy);
        }
示例#24
0
        public void TestFixtureSetup()
        {
            var configuration  = new ClientConfiguration();
            var connectionPool = new ConnectionPool <EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(Address));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            _server = new Server(ioStrategy, new Node(), configuration);
        }
示例#25
0
 public EntityElementBuilder Name(string name)
 {
     _entityId = UriExtensions.AsUri(name);
     return(this);
 }
示例#26
0
        public void When_GetBaseViewUri_Is_Called_With_EncryptTraffic_False_Uri_Is_Not_SSL_URI()
        {
            var configuration = new ClientConfiguration
            {
                UseSsl = false
            };

            configuration.Initialize();

            var connectionPool = new ConnectionPool <EapConnection>(new PoolConfiguration(), UriExtensions.GetEndPoint(Address));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            using (var server = new Server(ioStrategy, new Node(), configuration))
            {
                var uri = server.GetBaseViewUri("default");
                Assert.AreEqual("http://localhost:8092/default", uri);
            }
        }
示例#27
0
        public void TestFixtureSetup()
        {
            _endPoint = UriExtensions.GetEndPoint(_address);
            var configuration  = new ClientConfiguration();
            var connectionPool = new ConnectionPool <Connection>(new PoolConfiguration(), UriExtensions.GetEndPoint(_address));
            var ioStrategy     = new DefaultIOStrategy(connectionPool);

            _server = new Server(ioStrategy, new NodeAdapter(new Node(), new NodeExt()), configuration, new BucketConfig {
                Name = "default"
            });
        }
        /// <summary>
        /// Reads the data related to the provided <see cref="CDP4Common.DTO.Thing"/> from the data-source
        /// </summary>
        /// <typeparam name="T">
        /// an type of <see cref="CDP4Common.DTO.Thing"/>
        /// </typeparam>
        /// <param name="thing">
        /// An instance of <see cref="CDP4Common.DTO.Thing"/> that needs to be read from the data-source
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation Token.
        /// </param>
        /// <param name="attributes">
        /// An instance of <see cref="IQueryAttributes"/> to be passed along with the uri
        /// </param>
        /// <returns>
        /// a list of <see cref="CDP4Common.DTO.Thing"/> that are contained by the provided <see cref="CDP4Common.DTO.Thing"/> including the <see cref="CDP4Common.DTO.Thing"/> itself
        /// </returns>
        /// <exception cref="NotSupportedException">
        /// Throws a <see cref="NotSupportedException"/> if the supplied T thing is not an <see cref="CDP4Common.DTO.Iteration"/>.
        /// </exception>
        public override async Task <IEnumerable <Thing> > Read <T>(T thing, CancellationToken cancellationToken, IQueryAttributes attributes = null)
        {
            // only read Iterations,  domains or site reference data libraries in a file Dal
            if (!(thing is CDP4Common.DTO.Iteration) && !(thing is CDP4Common.DTO.SiteReferenceDataLibrary) && !(thing is CDP4Common.DTO.DomainOfExpertise))
            {
                throw new NotSupportedException("The JSONFileDal only supports Read on Iteration, SiteReferenceDataLibrary and DomainOfExpertise instances.");
            }

            if (this.Credentials.Uri == null)
            {
                throw new ArgumentNullException(nameof(this.Credentials.Uri), $"The Credentials URI may not be null");
            }

            // make sure that the uri is of the correct format
            UriExtensions.AssertUriIsFileSchema(this.Credentials.Uri);

            var filePath = this.Credentials.Uri.LocalPath;

            if (!System.IO.File.Exists(filePath))
            {
                throw new FileNotFoundException($"The specified filepath does not exist or you do not have access to it: {filePath}");
            }

            try
            {
                // re-read the to extract the reference data libraries that have not yet been fully dereferenced
                // and that are part of the required RDL's
                var siteDirectoryData = this.ReadSiteDirectoryJson(filePath, this.Credentials).ToList();

                // read file, SiteDirectory first.
                using (var zip = ZipFile.Read(filePath))
                {
                    // get all relevant info from the selected iteration
                    var siteDir = this.Session.RetrieveSiteDirectory();

                    var returned = new List <Thing>();

                    switch (thing.ClassKind)
                    {
                    case ClassKind.Iteration:
                        returned = this.RetrieveIterationThings(thing as CDP4Common.DTO.Iteration, siteDirectoryData, zip, siteDir);
                        break;

                    case ClassKind.SiteReferenceDataLibrary:
                        returned = this.RetrieveSRDLThings(thing as CDP4Common.DTO.SiteReferenceDataLibrary, siteDirectoryData, zip, siteDir);
                        break;

                    case ClassKind.DomainOfExpertise:
                        returned = this.RetrieveDomainOfExpertiseThings(thing as CDP4Common.DTO.DomainOfExpertise, siteDirectoryData, siteDir);
                        break;
                    }

                    return(returned);
                }
            }
            catch (Exception ex)
            {
                var msg = $"Failed to load file. Error: {ex.Message}";
                Logger.Error(msg);

                if (this.Credentials != null)
                {
                    this.Close();
                }

                throw new FileLoadException(msg);
            }
        }
        /// <summary>
        /// Opens a connection to a data source <see cref="Uri"/> speci1fied by the provided <see cref="Credentials"/>
        /// </summary>
        /// <param name="credentials">
        /// The <see cref="Credentials"/> that are used to connect to the data source such as username, password and <see cref="Uri"/>
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation Token.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{T}"/> of returned <see cref="Thing"/> DTOs.
        /// </returns>
        public override async Task <IEnumerable <Thing> > Open(Credentials credentials, CancellationToken cancellationToken)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials), $"The {nameof(credentials)} may not be null");
            }

            if (credentials.Uri == null)
            {
                throw new ArgumentNullException(nameof(credentials.Uri), $"The Credentials URI may not be null");
            }

            UriExtensions.AssertUriIsHttpOrHttpsSchema(credentials.Uri);

            var queryAttributes = new QueryAttributes
            {
                Extent = ExtentQueryAttribute.deep,
                IncludeReferenceData = false
            };

            var resourcePath = $"SiteDirectory{queryAttributes}";

            var openToken = CDP4Common.Helpers.TokenGenerator.GenerateRandomToken();

            this.httpClient = this.CreateHttpClient(credentials);

            var watch = Stopwatch.StartNew();

            var uriBuilder = this.GetUriBuilder(credentials.Uri, ref resourcePath);

            Logger.Debug("Resource Path {0}: {1}", openToken, resourcePath);
            Logger.Debug("WSP Open {0}: {1}", openToken, uriBuilder);

            var requestsw = Stopwatch.StartNew();

            using (var httpResponseMessage = await this.httpClient.GetAsync(resourcePath, HttpCompletionOption.ResponseHeadersRead, cancellationToken: cancellationToken))
            {
                Logger.Info("The ECSS-E-TM-10-25A Annex C Services responded in {0} [ms] to Open {1}", requestsw.ElapsedMilliseconds, openToken);
                requestsw.Stop();

                if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
                {
                    var msg = $"The data-source replied with code {httpResponseMessage.StatusCode}: {httpResponseMessage.ReasonPhrase}";
                    Logger.Error(msg);
                    throw new DalReadException(msg);
                }

                watch.Stop();
                Logger.Info("WSP DAL Open {0} completed in {1} [ms]", openToken, watch.ElapsedMilliseconds);

                watch = Stopwatch.StartNew();

                using (var resultStream = await httpResponseMessage.Content.ReadAsStreamAsync())
                {
                    var returned = this.Serializer.Deserialize(resultStream);

                    watch.Stop();
                    Logger.Info("JSON Deserializer completed in {0} [ms]", watch.ElapsedMilliseconds);

                    var returnedPerson = returned.OfType <CDP4Common.DTO.Person>().SingleOrDefault(x => x.ShortName == credentials.UserName);
                    if (returnedPerson == null)
                    {
                        throw new InvalidOperationException("User not found.");
                    }

                    this.Credentials = credentials;

                    return(returned);
                }
            }
        }
        public List <SceneItemDto> GetAllByStatus(string sceneID, ItemStatus status, int pageSize, int pageIndex,
                                                  out int count)
        {
            try
            {
                if (string.IsNullOrEmpty(sceneID))
                {
                    throw new ArgumentNullException("sceneID");
                }
                var mgdb = new MongoDbProvider <SceneItem>();

                var query = ItemStatus.All == status
                    ? mgdb.GetAll(o => (o.SceneID == sceneID))
                    : mgdb.GetAll(o => (o.SceneID == sceneID) && (o.Status == status));

                count = query.Count();
                int pageTotal;

                if (pageSize > 0)
                {
                    pageTotal = (count + pageSize - 1) / pageSize;
                }
                else
                {
                    pageSize  = 10;
                    pageTotal = (count + pageSize - 1) / pageSize;
                }

                if (pageIndex > pageTotal)
                {
                    pageIndex = pageTotal;
                }
                if (pageIndex < 1)
                {
                    pageIndex = 1;
                }

                var sceneItems = query
                                 .OrderByDescending(obj => obj.CreateTime)
                                 .Skip(pageSize * (pageIndex - 1))
                                 .Take(pageSize)
                                 .ToList();

                using (var db = new BCEnterpriseContext())
                {
                    if (0 == sceneItems.Count)
                    {
                        return(new List <SceneItemDto>());
                    }
                    var userIds    = sceneItems.Select(o => o.UserID).ToList();
                    var reUserInfo = db.FrontUsers.Where(obj => userIds.Contains(obj.UserID)).Select(o => new
                    {
                        uid     = o.UserID,
                        name    = o.Name,
                        picture = o.Picture
                    }).ToList();

                    var re = (from item in sceneItems
                              join r in reUserInfo on item.UserID equals r.uid into tempSU
                              from t in tempSU.DefaultIfEmpty()
                              select new SceneItemDto
                    {
                        Id = item.Id,
                        SceneID = item.SceneID,
                        PictureGuid = item.PictureGuid,
                        Count = item.Count,
                        Status = item.Status,
                        UserID = item.UserID,
                        CreateTime = item.CreateTime,
                        UpdateTime = item.UpdateTime,
                        Address = item.Address,
                        GPS = item.GPS,
                        Relation = item.Relation,
                        Description = item.Description,
                        Images = item.Images,
                        IsExamine = item.IsExamine,
                        Comments = item.Comments,
                        Type = item.Type,
                        Examines = item.Examines,
                        UserName = t == null ? string.Empty : t.name,
                        UserPicture = t == null ? string.Empty : UriExtensions.GetFullUrl(t.picture)
                    })
                             .ToList();
                    foreach (var r in re)
                    {
                        r.Images = MakeUrlWithPictureName(r.Images);
                    }
                    return(re);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }