/// <summary>
 /// Возвращает базовую LCS для загрузки подписок.
 /// </summary>
 /// <returns><see cref="LoadingCustomizationStruct"/> с проставленным представлением и типом объектов..</returns>
 private static LoadingCustomizationStruct GetInitialLcs()
 {
     return(LoadingCustomizationStruct.GetSimpleStruct(typeof(Subscription), Subscription.Views.SendingByCallbackView));
 }
        /// <summary>
        /// Вызывается самым последним в Page_Load
        /// </summary>
        protected override void Postload()
        {
            if (PK == null)
            {
                return;
            }

            Function limitBySubject = _languageDef.GetFunction(_languageDef.funcEQ, new VariableDef(_languageDef.GuidType, "Subject"), this.PK);

            LoadingCustomizationStruct lcsOwnRolesAndUsers = new LoadingCustomizationStruct(null);

            lcsOwnRolesAndUsers.LoadingTypes  = new[] { typeof(Permition) };
            lcsOwnRolesAndUsers.LimitFunction = limitBySubject;
            View classesView = Information.GetView("Sec_PermitionE", typeof(Permition));

            lcsOwnRolesAndUsers.View = classesView;

            List <Permition> classOwnRolesAndUsers =
                BridgeToDS.GetDataService().LoadObjects(lcsOwnRolesAndUsers).Cast <Permition>().ToList();

            List <Permissions> rolesPermissions = new List <Permissions>();

            foreach (Agent role in _allRoles)
            {
                Permissions u2c = new Permissions();

                u2c.ObjectId   = role.__PrimaryKey.ToString();
                u2c.ObjectName = role.Name;

                Permition firstOrDefault =
                    classOwnRolesAndUsers.FirstOrDefault(c => c.Agent.__PrimaryKey.ToString().Equals(u2c.ObjectId));

                if (firstOrDefault != null && firstOrDefault.Access != null)
                {
                    for (int i = 0; i < firstOrDefault.Access.Count; i++)
                    {
                        Access access = firstOrDefault.Access[i];

                        switch (access.TypeAccess)
                        {
                        case tTypeAccess.Delete:
                            u2c.Delete = true;
                            break;

                        case tTypeAccess.Execute:
                            u2c.Execute = true;
                            break;

                        case tTypeAccess.Full:
                            u2c.Full = true;
                            break;

                        case tTypeAccess.Insert:
                            u2c.Insert = true;
                            break;

                        case tTypeAccess.Read:
                            u2c.Read = true;
                            break;

                        case tTypeAccess.Update:
                            u2c.Update = true;
                            break;
                        }
                    }
                }

                rolesPermissions.Add(u2c);
            }

            if (IsPostBack)
            {
                #region Save Class Permissions

                List <Permissions> list = new List <Permissions>();

                foreach (Agent role in _allRoles)
                {
                    string fullKey    = "Full" + role.__PrimaryKey;
                    string readKey    = "Read" + role.__PrimaryKey;
                    string insertKey  = "Insert" + role.__PrimaryKey;
                    string updateKey  = "Update" + role.__PrimaryKey;
                    string deleteKey  = "Delete" + role.__PrimaryKey;
                    string executeKey = "Execute" + role.__PrimaryKey;

                    bool isClassPermissionsSet = false;

                    Permissions permission = new Permissions();
                    permission.ObjectId   = role.__PrimaryKey.ToString();
                    permission.ObjectName = role.Name;

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(fullKey)))
                    {
                        permission.Full       = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(readKey)))
                    {
                        permission.Read       = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(insertKey)))
                    {
                        permission.Insert     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(updateKey)))
                    {
                        permission.Update     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(deleteKey)))
                    {
                        permission.Delete     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(executeKey)))
                    {
                        permission.Execute    = true;
                        isClassPermissionsSet = true;
                    }

                    if (isClassPermissionsSet)
                    {
                        list.Add(permission);
                    }
                }



                List <Permissions> updatedPermissions = new List <Permissions>();
                List <Permissions> deletedPermissions = new List <Permissions>();

                foreach (Permissions p in rolesPermissions)
                {
                    Permissions singleOrDefault = list.SingleOrDefault(c => c.ObjectId.Equals(p.ObjectId));

                    if (singleOrDefault != null)
                    {
                        updatedPermissions.Add(singleOrDefault);
                        list.Remove(singleOrDefault);
                    }
                    else
                    {
                        deletedPermissions.Add(p);
                    }
                }

                List <Permissions> addedPermissions = list.Union(updatedPermissions).ToList();



                List <DataObject> deletedObjects = new List <DataObject>();
                List <DataObject> addedObjects   = new List <DataObject>();

                foreach (Permition p in classOwnRolesAndUsers)
                {
                    string roleId = p.Agent.__PrimaryKey.ToString();

                    if (updatedPermissions.Any(x => x.ObjectId.Equals(roleId)) ||
                        deletedPermissions.Any(x => x.ObjectId.Equals(roleId)))
                    {
                        p.SetStatus(ObjectStatus.Deleted);
                        deletedObjects.Add(p);
                    }
                }

                foreach (Permissions p in addedPermissions)
                {
                    Permition permission = new Permition();

                    permission.Subject = DataObject;
                    permission.Agent   = new Agent();
                    permission.Agent.SetExistObjectPrimaryKey(p.ObjectId);

                    permission.Access = new DetailArrayOfAccess(permission);

                    if (p.Delete)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Delete
                        });
                    }

                    if (p.Execute)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Execute
                        });
                    }

                    if (p.Full)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Full
                        });
                    }

                    if (p.Insert)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Insert
                        });
                    }

                    if (p.Read)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Read
                        });
                    }

                    if (p.Update)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Update
                        });
                    }

                    addedObjects.Add(permission);
                }

                DataObject[] dataObjects = deletedObjects.Union(addedObjects).ToArray();

                if (dataObjects.Length > 0)
                {
                    BridgeToDS.GetDataService().UpdateObjects(ref dataObjects);
                }

                #endregion
            }

            GenerateClassesTable(rolesPermissions, tblClassRoles);



            List <Permissions> usersPermissions = new List <Permissions>();

            foreach (Agent user in _allUsers)
            {
                Permissions u2c = new Permissions();

                u2c.ObjectId   = user.__PrimaryKey.ToString();
                u2c.ObjectName = user.Name;

                Permition firstOrDefault =
                    classOwnRolesAndUsers.FirstOrDefault(c => c.Agent.__PrimaryKey.ToString().Equals(u2c.ObjectId));

                if (firstOrDefault != null && firstOrDefault.Access != null)
                {
                    for (int i = 0; i < firstOrDefault.Access.Count; i++)
                    {
                        Access access = firstOrDefault.Access[i];

                        switch (access.TypeAccess)
                        {
                        case tTypeAccess.Delete:
                            u2c.Delete = true;
                            break;

                        case tTypeAccess.Execute:
                            u2c.Execute = true;
                            break;

                        case tTypeAccess.Full:
                            u2c.Full = true;
                            break;

                        case tTypeAccess.Insert:
                            u2c.Insert = true;
                            break;

                        case tTypeAccess.Read:
                            u2c.Read = true;
                            break;

                        case tTypeAccess.Update:
                            u2c.Update = true;
                            break;
                        }
                    }
                }

                usersPermissions.Add(u2c);
            }

            if (IsPostBack)
            {
                #region Save Class Permissions

                List <Permissions> list = new List <Permissions>();

                foreach (Agent user in _allUsers)
                {
                    string fullKey    = "Full" + user.__PrimaryKey;
                    string readKey    = "Read" + user.__PrimaryKey;
                    string insertKey  = "Insert" + user.__PrimaryKey;
                    string updateKey  = "Update" + user.__PrimaryKey;
                    string deleteKey  = "Delete" + user.__PrimaryKey;
                    string executeKey = "Execute" + user.__PrimaryKey;

                    bool isClassPermissionsSet = false;

                    Permissions permission = new Permissions();
                    permission.ObjectId   = user.__PrimaryKey.ToString();
                    permission.ObjectName = user.Name;

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(fullKey)))
                    {
                        permission.Full       = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(readKey)))
                    {
                        permission.Read       = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(insertKey)))
                    {
                        permission.Insert     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(updateKey)))
                    {
                        permission.Update     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(deleteKey)))
                    {
                        permission.Delete     = true;
                        isClassPermissionsSet = true;
                    }

                    if (Request.Form.AllKeys.Any(fk => fk.Contains(executeKey)))
                    {
                        permission.Execute    = true;
                        isClassPermissionsSet = true;
                    }

                    if (isClassPermissionsSet)
                    {
                        list.Add(permission);
                    }
                }



                List <Permissions> updatedPermissions = new List <Permissions>();
                List <Permissions> deletedPermissions = new List <Permissions>();

                foreach (Permissions p in usersPermissions)
                {
                    Permissions singleOrDefault = list.SingleOrDefault(c => c.ObjectId.Equals(p.ObjectId));

                    if (singleOrDefault != null)
                    {
                        updatedPermissions.Add(singleOrDefault);
                        list.Remove(singleOrDefault);
                    }
                    else
                    {
                        deletedPermissions.Add(p);
                    }
                }

                List <Permissions> addedPermissions = list.Union(updatedPermissions).ToList();



                List <DataObject> deletedObjects = new List <DataObject>();
                List <DataObject> addedObjects   = new List <DataObject>();

                foreach (Permition p in classOwnRolesAndUsers)
                {
                    string userId = p.Agent.__PrimaryKey.ToString();

                    if (updatedPermissions.Any(x => x.ObjectId.Equals(userId)) ||
                        deletedPermissions.Any(x => x.ObjectId.Equals(userId)))
                    {
                        p.SetStatus(ObjectStatus.Deleted);
                        deletedObjects.Add(p);
                    }
                }

                foreach (Permissions p in addedPermissions)
                {
                    Permition permission = new Permition();

                    permission.Subject = DataObject;
                    permission.Agent   = new Agent();
                    permission.Agent.SetExistObjectPrimaryKey(p.ObjectId);

                    permission.Access = new DetailArrayOfAccess(permission);

                    if (p.Delete)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Delete
                        });
                    }

                    if (p.Execute)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Execute
                        });
                    }

                    if (p.Full)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Full
                        });
                    }

                    if (p.Insert)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Insert
                        });
                    }

                    if (p.Read)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Read
                        });
                    }

                    if (p.Update)
                    {
                        permission.Access.Add(new Access()
                        {
                            TypeAccess = tTypeAccess.Update
                        });
                    }

                    addedObjects.Add(permission);
                }

                DataObject[] dataObjects = deletedObjects.Union(addedObjects).ToArray();

                if (dataObjects.Length > 0)
                {
                    BridgeToDS.GetDataService().UpdateObjects(ref dataObjects);
                }

                #endregion
            }

            GenerateClassesTable(usersPermissions, tblClassUsers);
        }
        /// <summary>
        /// Подписать клиента на определенный тип сообщений или обновить подписку.
        /// </summary>
        /// <param name="clientId">Идентификатор клиента, подписку которого нужно обновить или создать.</param>
        /// <param name="messageTypeId">Тип сообщений подписки.</param>
        /// <param name="isCallback">Является ли подписка callback.</param>
        /// <param name="transportType">Способ передачи сообщений, если подписка callback, иначе можно передать null.</param>
        /// <param name="expiryDate">Дата прекращения подписки. Если не указана, вычисляется как сумма текущей даты и параметра конфигурации UpdateForATime.</param>
        /// <param name="subscriptionId">Идентификатор подписки, которую нужно обновить или создать.</param>
        public void SubscribeOrUpdate(string clientId, string messageTypeId, bool isCallback, TransportType?transportType, DateTime?expiryDate = null, string subscriptionId = null)
        {
            LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Subscription), Subscription.Views.SubscriptionsManagerView);

            Guid clientPk      = ServiceHelper.ConvertClientIdToPrimaryKey(clientId, _dataService, _statisticsService);
            Guid messageTypePk = ServiceHelper.ConvertMessageTypeIdToPrimaryKey(messageTypeId, _dataService, _statisticsService);

            lcs.LimitFunction = LangDef.GetFunction(
                LangDef.funcAND,
                LangDef.GetFunction(LangDef.funcEQ, new VariableDef(LangDef.GuidType, Information.ExtractPropertyPath <Subscription>(x => x.Client)), clientPk),
                LangDef.GetFunction(LangDef.funcEQ, new VariableDef(LangDef.GuidType, Information.ExtractPropertyPath <Subscription>(x => x.MessageType)), messageTypePk));

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            DataObject[] subscriptions = _dataService.LoadObjects(lcs);
            if (subscriptionId != null)
            {
                subscriptions = subscriptions.Where(s => Guid.Parse(s.__PrimaryKey.ToString()) == Guid.Parse(subscriptionId)).ToArray();
            }

            stopwatch.Stop();
            long time = stopwatch.ElapsedMilliseconds;

            _statisticsService.NotifyAvgTimeSql(null, (int)time, "DefaultSubscriptionsManager.SubscribeOrUpdate() load Subscription.");

            Subscription subscription;

            if (subscriptions.Length == 0)
            {
                subscription = new Subscription()
                {
                    Client      = ServiceHelper.GetClient(clientPk, _dataService, _statisticsService),
                    MessageType = ServiceHelper.GetMessageType(messageTypePk, _dataService, _statisticsService),
                    IsCallback  = isCallback
                };

                if (subscriptionId != null)
                {
                    subscription.__PrimaryKey = Guid.Parse(subscriptionId);
                }

                if (isCallback)
                {
                    if (transportType == null)
                    {
                        throw new ArgumentException("Не указан способ передачи при создании callback-подписки.");
                    }

                    subscription.TransportType = transportType.Value;
                }
            }
            else
            {
                subscription = (Subscription)subscriptions[0];

                stopwatch = new Stopwatch();
                stopwatch.Start();

                _dataService.LoadObject(subscription);

                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(null, (int)time, "DefaultSubscriptionsManager.SubscribeOrUpdate() load Subscription 2.");

                subscription.IsCallback = isCallback;

                if (isCallback && transportType != null)
                {
                    subscription.TransportType = transportType.Value;
                }
            }

            if (expiryDate != null)
            {
                subscription.ExpiryDate = expiryDate.Value;
            }
            else
            {
                ServiceHelper.UpdateStoppingDate(subscription);
            }

            stopwatch = new Stopwatch();
            stopwatch.Start();

            _dataService.UpdateObject(subscription);

            stopwatch.Stop();
            time = stopwatch.ElapsedMilliseconds;
            _statisticsService.NotifyAvgTimeSql(null, (int)time, "DefaultSubscriptionsManager.SubscribeOrUpdate() update Subscription.");
        }
        public void Test_funcExistDetails()
        {
            // TODO Удалить данную строчку, как исправят баг 94309.
            // IDataService dataService = DataServices[0];

            // TODO Вернуть данную строчку, как исправят баг 94309.
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                var ds = (SQLDataService)dataService;

                // Контрольные значене.
                const int controlInt = 1;

                // Сначала создаём структуру данных, требуемую для теста.
                var testMasterObject = new FullTypesMaster1();

                var testFullTypesMainAgregator = new FullTypesMainAgregator
                {
                    FullTypesMaster1 = testMasterObject
                };

                // Создание детейлов, которые не подходят под условие ограничения.
                testFullTypesMainAgregator.FullTypesDetail1.Add(new FullTypesDetail1 {
                    PoleInt = controlInt
                });
                testFullTypesMainAgregator.FullTypesDetail2.Add(new FullTypesDetail2 {
                    PoleInt = 2
                });

                var updateObjectsArray = new DataObject[] { testMasterObject, testFullTypesMainAgregator };

                // Сохранение данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Выбор представления.
                var view  = FullTypesMainAgregator.Views.FullViewWithDetail1;
                var view2 = FullTypesDetail1.Views.FullDetailView;
                var view3 = FullTypesDetail2.Views.FullTypesDetail2E;
                var lcs   = LoadingCustomizationStruct.GetSimpleStruct(typeof(FullTypesMainAgregator), view);

                string cmp   = Information.ExtractPropertyPath <FullTypesDetail1>(x => x.FullTypesMainAgregator);
                string name1 = Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.FullTypesDetail1);
                string name2 = Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.FullTypesDetail2);

                var detail  = new DetailVariableDef(_ldef.GetObjectType("Details"), name1, view2, cmp, new[] { SQLWhereLanguageDef.StormMainObjectKey });
                var detail2 = new DetailVariableDef(_ldef.GetObjectType("Details"), name2, view3, cmp, new[] { SQLWhereLanguageDef.StormMainObjectKey });
                // Проверка существования детейлов такого, что:
                lcs.LimitFunction = _ldef.GetFunction(_ldef.funcExistDetails,
                                                      detail,
                                                      detail2,
                                                      _ldef.GetFunction(
                                                          // Равны.
                                                          _ldef.funcEQ,
                                                          // Хотя бы одно значение в поле Int у первого детейла.
                                                          new VariableDef(_ldef.NumericType, Information.ExtractPropertyPath <FullTypesDetail1>(x => x.PoleInt)),
                                                          // И значение в поле Int у второго детейла.
                                                          new VariableDef(_ldef.NumericType, Information.ExtractPropertyPath <FullTypesDetail2>(x => x.PoleInt))));

                // Act.
                var dos = ds.LoadObjects(lcs);

                // Assert.
                Assert.Equal(dos.Length, 0);

                // Создание детейла, который подходит под условте ограничения.
                testFullTypesMainAgregator.FullTypesDetail2.Add(new FullTypesDetail2 {
                    PoleInt = controlInt
                });

                // Сохранение новых данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Act.
                var dos2 = ds.LoadObjects(lcs);

                // Assert.
                Assert.Equal(dos2.Length, 1);
            }
        }
Example #5
0
        public void TestDeleteClient()
        {
            foreach (var dataService in DataServices)
            {
                // Arrange.
                const string client1Id      = "FDF33DF1-5DCA-41F9-A2E4-3B5C7E103452";
                const string client2Id      = "31D12F7D-2D0E-43FB-8092-E6D34A9AB87D";
                const string messageType1Id = "EB6EC229-5E93-4B76-9993-5A1589787421";
                const string messageType2Id = "C8802C67-AC1B-497C-A707-5FF4191E0083";
                const string messageType3Id = "BC3F54C6-4E2F-43DA-B124-A0771F8F200C";
                var          service        = new DefaultSubscriptionsManager(dataService, GetMockStatisticsService());
                var          clientLcs      = LoadingCustomizationStruct.GetSimpleStruct(typeof(Client), Client.Views.ListView);
                var          messageLcs     = LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageLightView);
                service.CreateClient(client1Id, "TestClient1");
                service.CreateClient(client2Id, "TestClient2");
                service.CreateMessageType(new NameCommentStruct
                {
                    Id      = messageType1Id,
                    Name    = "TestMessageType1",
                    Comment = "ForTest"
                });
                service.CreateMessageType(new NameCommentStruct
                {
                    Id      = messageType2Id,
                    Name    = "TestMessageType2",
                    Comment = "ForTest"
                });
                service.CreateMessageType(new NameCommentStruct
                {
                    Id      = messageType3Id,
                    Name    = "TestMessageType3",
                    Comment = "ForTest"
                });
                service.Prepare();
                service.SubscribeOrUpdate(client1Id, messageType1Id, true, TransportType.WCF);
                service.SubscribeOrUpdate(client1Id, messageType3Id, true, TransportType.WCF);
                service.SubscribeOrUpdate(client1Id, messageType2Id, true, TransportType.WCF);
                service.SubscribeOrUpdate(client2Id, messageType2Id, true, TransportType.WCF);
                Guid client1Pk      = ServiceHelper.ConvertClientIdToPrimaryKey(client1Id, dataService, GetMockStatisticsService());
                Guid messageType1Pk = ServiceHelper.ConvertMessageTypeIdToPrimaryKey(messageType1Id, dataService, GetMockStatisticsService());
                var  client         = new Client();
                client.SetExistObjectPrimaryKey(client1Pk);
                var messageType = new MessageType();
                messageType.SetExistObjectPrimaryKey(messageType1Pk);
                DataObject message = new Message()
                {
                    Recipient = client, MessageType = messageType, ReceivingTime = DateTime.Now
                };
                dataService.UpdateObject(message);

                // Act && Assert.
                var clients = dataService.LoadObjects(clientLcs);
                Assert.Equal(clients.Length, 2);
                var messages = dataService.LoadObjects(messageLcs);
                Assert.Equal(messages.Length, 1);
                var subs = service.GetSubscriptions(false);
                Assert.Equal(subs.Count(), 4);

                service.DeleteClient(client1Id);
                clients = dataService.LoadObjects(clientLcs);
                Assert.Equal(clients.Length, 1);
                Assert.True(clients.Cast <Client>().All(cl => Guid.Parse(cl.ID) == Guid.Parse(client2Id) || Guid.Parse(cl.__PrimaryKey.ToString()) == Guid.Parse(client2Id)));
                messages = dataService.LoadObjects(messageLcs);
                Assert.Equal(messages.Length, 0);
                subs = service.GetSubscriptions(false);
                Assert.Equal(subs.Count(), 1);
                Assert.True(subs.All(sub => Guid.Parse(sub.Client.ID) == Guid.Parse(client2Id) || Guid.Parse(sub.Client.__PrimaryKey.ToString()) == Guid.Parse(client2Id)));
                Assert.True(subs.All(sub => Guid.Parse(sub.MessageType.ID) == Guid.Parse(messageType2Id) || Guid.Parse(sub.MessageType.__PrimaryKey.ToString()) == Guid.Parse(messageType2Id)));
            }
        }
        public void Test_paramYearDIFF()
        {
            // TODO Удалить данную строчку, как исправят баг 94309.
            // IDataService dataService = DataServices[0];

            // TODO Вернуть данную строчку, как исправят баг 94309.
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                var ds = (SQLDataService)dataService;

                // Контрольные значене.
                DateTime  controlDate  = new DateTime(2016, 2, 2);
                const int firstDate    = 1;
                const int secondDate   = 3;
                var       controlValue = new List <int>()
                {
                    firstDate, secondDate
                };

                // Сначала создаём структуру данных, требуемую для теста.
                var testMasterObject = new FullTypesMaster1();

                // Дата, которая будет подходить под условия ограничения.
                var firstDateTrue = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2015, 2, 1),
                    PoleInt          = firstDate,
                    FullTypesMaster1 = testMasterObject
                };

                // Дата, которая не будет подходить под условия ограничения.
                var firstDateFalse = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2016, 2, 2),
                    PoleInt          = 2,
                    FullTypesMaster1 = testMasterObject,
                };

                // Дата, которая будет подходить под условия ограничения.
                var secondDateTrue = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2014, 2, 2),
                    PoleInt          = secondDate,
                    FullTypesMaster1 = testMasterObject
                };

                // Дата, которая не будет подходить под условия ограничения.
                var secondDateFalse = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2015, 2, 2),
                    PoleInt          = 4,
                    FullTypesMaster1 = testMasterObject
                };

                var updateObjectsArray = new DataObject[] { testMasterObject, firstDateTrue, firstDateFalse, secondDateTrue, secondDateFalse };

                // Сохранение данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Выбор представления.
                var view = FullTypesMainAgregator.Views.FullView;
                var lcs  = LoadingCustomizationStruct.GetSimpleStruct(typeof(FullTypesMainAgregator), view);

                lcs.LimitFunction = _ldef.GetFunction(
                    _ldef.funcL,
                    _ldef.GetFunction(
                        _ldef.funcDateAdd,
                        _ldef.GetFunction(_ldef.paramYearDIFF),
                        1,
                        new VariableDef(_ldef.DateTimeType, Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.PoleDateTime))),
                    _ldef.GetFunction(_ldef.funcOnlyDate, controlDate));

                // Act.
                // Получение, массива значений поля PoleInt.
                var poleIntValue = ds.LoadObjects(lcs).Cast <FullTypesMainAgregator>().Select(x => x.PoleInt).ToList();

                // Получение массивов Объединения и Пересечения обьектов(controlValue и PoleInt)
                var unionValue     = poleIntValue.Union(controlValue).ToList();
                var intersectValue = poleIntValue.Intersect(controlValue).ToList();

                // Assert.
                Assert.Equal(controlValue.Count, unionValue.Count);
                Assert.Equal(controlValue.Count, intersectValue.Count);
            }
        }
        public void Test_funcExistAll()
        {
            // TODO Удалить данную строчку, как исправят баг 94309.
            // IDataService dataService = DataServices[0];

            // TODO Вернуть данную строчку, как исправят баг 94309.
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                var ds = (SQLDataService)dataService;

                // Контрольные значене.
                const int  controlInt  = 1;
                const bool controlBool = true;

                // Сначала создаём структуру данных, требуемую для теста.
                var testMasterObject = new FullTypesMaster1();

                var testFullTypesMainAgregator = new FullTypesMainAgregator
                {
                    FullTypesMaster1 = testMasterObject
                };

                // Создание детейла, который не подходит под условие ограничения.
                testFullTypesMainAgregator.FullTypesDetail1.Add(new FullTypesDetail1 {
                    PoleInt = 2, PoleBool = false
                });

                var updateObjectsArray = new DataObject[] { testMasterObject, testFullTypesMainAgregator };

                // Сохранение данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Выбор представления.
                var view  = FullTypesMainAgregator.Views.FullViewWithDetail1;
                var view2 = FullTypesDetail1.Views.FullDetailView;
                var lcs   = LoadingCustomizationStruct.GetSimpleStruct(typeof(FullTypesMainAgregator), view);

                string cmp  = Information.ExtractPropertyPath <FullTypesDetail1>(x => x.FullTypesMainAgregator);
                string name = Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.FullTypesDetail1);

                var detail = new DetailVariableDef(_ldef.GetObjectType("Details"), name, view2, cmp, new[] { SQLWhereLanguageDef.StormMainObjectKey });
                // Проверка существования детейла такого, что:
                lcs.LimitFunction = _ldef.GetFunction(_ldef.funcExistAll,
                                                      detail,
                                                      // Поле int в детейле равно контрольному значению(controlInt = 1).
                                                      _ldef.GetFunction(_ldef.funcEQ,
                                                                        new VariableDef(_ldef.NumericType,
                                                                                        Information.ExtractPropertyPath <FullTypesDetail1>(x => x.PoleInt)),
                                                                        controlInt),
                                                      // Или поле bool в детейле равно контрольному значению (controlBool=true).
                                                      _ldef.GetFunction(_ldef.funcEQ,
                                                                        new VariableDef(_ldef.BoolType,
                                                                                        Information.ExtractPropertyPath <FullTypesDetail1>(x => x.PoleBool)),
                                                                        controlBool));

                // Act.
                var dos = ds.LoadObjects(lcs);

                // Assert.
                Assert.Equal(dos.Length, 0);

                // Создание детейла, который подходит под условие ограничения.
                testFullTypesMainAgregator.FullTypesDetail1.Add(new FullTypesDetail1 {
                    PoleInt = controlInt, PoleBool = controlBool
                });

                // Сохранение новых данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Act.
                var dos2 = ds.LoadObjects(lcs);

                // Assert.
                Assert.Equal(dos2.Length, 1);
            }
        }
        /// <summary>
        /// Normalize statistics records for saving.
        /// </summary>
        /// <param name="stats">Raw statistics records.</param>
        /// <returns>Normalized statistics records.</returns>
        protected DataObject[] PrepareStatsForSaving(IEnumerable <StatisticsRecord> stats)
        {
            var allRecords = new List <DataObject>();

            if (stats.Count() > 0)
            {
#if DEBUG
                if (stats.Any(i => i.StatisticsInterval != stats.First().StatisticsInterval))
                {
                    throw new ArgumentException("Stat records for saving must be with the same interval type.");
                }
#endif

                var ldef = ExternalLangDef.LanguageDef;
                foreach (var statGroup in stats.GroupBy(x => x.StatisticsSetting.__PrimaryKey))
                {
                    var statRecords = statGroup.OrderBy(x => x.Since).ToList();
                    var firstRecord = statRecords.First();

                    if (firstRecord.StatisticsSetting.Subscription != null)
                    {
                        if (firstRecord.StatisticsSetting.Subscription.MessageType != null &&
                            firstRecord.StatisticsSetting.Subscription.Client != null)
                        {
                            Stopwatch stopwatch = new Stopwatch();
                            stopwatch.Start();

                            var queueLength = _dataService.Query <Message>(Message.Views.MessageEditView)
                                              .Count(x => x.MessageType.__PrimaryKey == firstRecord.StatisticsSetting.Subscription.MessageType.__PrimaryKey &&
                                                     x.Recipient.__PrimaryKey == firstRecord.StatisticsSetting.Subscription.Client.__PrimaryKey);

                            stopwatch.Stop();
                            long time = stopwatch.ElapsedMilliseconds;
                            _statisticsService.NotifyAvgTimeSql(firstRecord.StatisticsSetting.Subscription, (int)time, "DefaultStatisticsSaveService.PrepareStatsForSaving() load count messages.");


                            stopwatch = new Stopwatch();
                            stopwatch.Start();

                            var errorLenth = _dataService.Query <Message>(Message.Views.MessageEditView)
                                             .Count(x => x.MessageType.__PrimaryKey == firstRecord.StatisticsSetting.Subscription.MessageType.__PrimaryKey &&
                                                    x.Recipient.__PrimaryKey == firstRecord.StatisticsSetting.Subscription.Client.__PrimaryKey &&
                                                    x.ErrorCount > 0);

                            stopwatch.Stop();
                            time = stopwatch.ElapsedMilliseconds;
                            _statisticsService.NotifyAvgTimeSql(firstRecord.StatisticsSetting.Subscription, (int)time, "DefaultStatisticsSaveService.PrepareStatsForSaving() load count messages with error.");


                            foreach (var rec in statRecords)
                            {
                                rec.UniqueErrorsCount = errorLenth;
                                rec.QueueLength       = queueLength;
                            }

                            var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(StatisticsRecord), _statRecordView);
                            lcs.ReturnTop     = 1;
                            lcs.LimitFunction = ldef.GetFunction(
                                ldef.funcAND,
                                ldef.GetFunction(ldef.funcEQ, new VariableDef(ldef.DateTimeType, Information.ExtractPropertyPath <StatisticsRecord>(x => x.Since)), firstRecord.Since),
                                ldef.GetFunction(ldef.funcEQ, new VariableDef(ldef.GuidType, Information.ExtractPropertyPath <StatisticsRecord>(x => x.StatisticsSetting)), firstRecord.StatisticsSetting.__PrimaryKey));

                            DataObject[] existedStatRecords = null;
                            try
                            {
                                stopwatch = new Stopwatch();
                                stopwatch.Start();
                                existedStatRecords = _dataService.LoadObjects(lcs);
                                stopwatch.Stop();
                                time = stopwatch.ElapsedMilliseconds;
                                _statisticsService.NotifyAvgTimeSql(firstRecord.StatisticsSetting.Subscription, (int)time, "DefaultStatisticsSaveService.PrepareStatsForSaving() load existed stat record.");
                            }
                            catch (Exception exception)
                            {
                                _logger.LogError("Load statistics error. Service Bus may write double statistics record.", exception.ToString());
                            }

                            if (existedStatRecords != null && existedStatRecords.Length > 0)
                            {
                                var esr = (StatisticsRecord)existedStatRecords[0];

                                var oldSentCount     = esr.SentCount;
                                var oldReceivedCount = esr.ReceivedCount;

                                // TODO: other properties
                                esr.SentCount     += firstRecord.SentCount;
                                esr.ReceivedCount += firstRecord.ReceivedCount;

                                statRecords[0] = esr;

                                var logMessage = $"Existed stat record from {esr.Since} to {esr.To} (statistics setting: '{firstRecord.StatisticsSetting.__PrimaryKey}') has been updated. "
                                                 + $"Old values: sent: {oldSentCount}, received: {oldReceivedCount}. "
                                                 + $"New values: sent: {esr.SentCount}, received: {esr.ReceivedCount}.";
                                _logger.LogInformation($"Updating existed stat record ({esr.Since})", logMessage);
                            }
                        }
                    }
                    else
                    {
                        statRecords = statRecords.Where(x => x.SentCount > 0 || x.ReceivedCount > 0 || x.ErrorsCount > 0 || x.UniqueErrorsCount > 0 || x.QueueLength > 0).ToList();
                        if (statRecords.Count > 0)
                        {
                            Stopwatch stopwatch = new Stopwatch();
                            stopwatch.Start();

                            var queueLength = _dataService.Query <Message>(Message.Views.MessageEditView).Count();

                            stopwatch.Stop();
                            long time = stopwatch.ElapsedMilliseconds;
                            _statisticsService.NotifyAvgTimeSql(firstRecord.StatisticsSetting.Subscription, (int)time, "DefaultStatisticsSaveService.PrepareStatsForSaving() load count messages for summary.");

                            stopwatch = new Stopwatch();
                            stopwatch.Start();

                            var errorLenth = _dataService.Query <Message>(Message.Views.MessageEditView).Count(x => x.ErrorCount > 0);

                            stopwatch.Stop();
                            time = stopwatch.ElapsedMilliseconds;
                            _statisticsService.NotifyAvgTimeSql(firstRecord.StatisticsSetting.Subscription, (int)time, "DefaultStatisticsSaveService.PrepareStatsForSaving() load count messages wirh errors for summary.");

                            foreach (var rec in statRecords)
                            {
                                rec.UniqueErrorsCount = errorLenth;
                                rec.QueueLength       = queueLength;
                            }
                        }
                    }

                    allRecords.AddRange(statRecords);
                }
            }

            return(allRecords.ToArray());
        }
        public void Test_funcDayOfWeek()
        {
            // TODO Удалить данную строчку, как исправят баг 94309.
            // IDataService dataService = DataServices[0];

            // TODO Вернуть данную строчку, как исправят баг 94309.
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                var ds = (SQLDataService)dataService;

                // Контрольные значене.
                const int firstMonday  = 1;
                const int secondMonday = 3;
                var       controlValue = new List <int>()
                {
                    firstMonday, secondMonday
                };

                // Сначала создаём структуру данных, требуемую для теста.
                var testMasterObject = new FullTypesMaster1();

                // Понедельник.
                var monday1 = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2016, 1, 11, 10, 37, 44),
                    PoleInt          = firstMonday,
                    FullTypesMaster1 = testMasterObject
                };

                // Пятница.
                var friday1 = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2016, 1, 22, 10, 37, 44),
                    PoleInt          = 2,
                    FullTypesMaster1 = testMasterObject,
                };

                // Понедельник.
                var monday2 = new FullTypesMainAgregator
                {
                    PoleDateTime     = new DateTime(2015, 12, 28, 10, 37, 44),
                    PoleInt          = secondMonday,
                    FullTypesMaster1 = testMasterObject
                };

                var updateObjectsArray = new DataObject[] { testMasterObject, monday1, friday1, monday2 };

                // Сохранение данных.
                ds.UpdateObjects(ref updateObjectsArray);

                // Выбор представления.
                var view = FullTypesMainAgregator.Views.FullView;
                var lcs  = LoadingCustomizationStruct.GetSimpleStruct(typeof(FullTypesMainAgregator), view);

                // Функция ограничения.
                // Применение функции ограничения.
                lcs.LimitFunction = _ldef.GetFunction(
                    _ldef.funcEQ,
                    _ldef.GetFunction(
                        _ldef.funcDayOfWeek,
                        new VariableDef(_ldef.DateTimeType,
                                        Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.PoleDateTime))),
                    1);
                // Act.
                // Получение, массива значений поля PoleInt.
                var poleIntValue = ds.LoadObjects(lcs).Cast <FullTypesMainAgregator>().Select(x => x.PoleInt).ToList();

                // Получение массивов Объединения и Пересечения обьектов(controlValue и PoleInt)
                var unionValue     = poleIntValue.Union(controlValue).ToList();
                var intersectValue = poleIntValue.Intersect(controlValue).ToList();

                // Assert.
                Assert.Equal(controlValue.Count, unionValue.Count);
                Assert.Equal(controlValue.Count, intersectValue.Count);
            }
        }
        /// <summary>
        /// Метод отправки сообщений из БД, выполняющийся по таймеру.
        /// </summary>
        /// <param name="state">Состояние, передаваемое при вызове метода таймером.</param>
        private void ScanMessages(object state)
        {
            try
            {
                if (_sendingTasksCount >= MaxTasks)
                {
                    return;
                }

                IEnumerable <Subscription> subscriptions = _subscriptionsManager.GetCallbackSubscriptions().ToList();
                if (!subscriptions.Any())
                {
                    return;
                }

                // Условие, ограничивающее получателя и тип сообщения загружаемых сообщений в соответствии с имеющимися подписками.
                Function[] conditionsList = subscriptions
                                            .Select(
                    s =>
                    _langDef.GetFunction(
                        _langDef.funcAND,
                        _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.Recipient)), s.Client.__PrimaryKey),
                        _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.MessageType)), s.MessageType.__PrimaryKey)))
                                            .ToArray();
                Function subscriptionsCondition = _langDef.GetFunction(_langDef.funcOR, conditionsList);

                Function messagesLf = _langDef.GetFunction(
                    _langDef.funcAND,
                    subscriptionsCondition,
                    _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.BoolType, Information.ExtractPropertyPath <Message>(x => x.IsSending)), false),
                    _langDef.GetFunction(_langDef.funcLEQ, new VariableDef(_langDef.DateTimeType, Information.ExtractPropertyPath <Message>(x => x.SendingTime)), DateTime.Now));

                LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageEditView);
                lcs.LimitFunction = messagesLf;
                lcs.ReturnTop     = MaxTasks - _sendingTasksCount;
                lcs.ColumnsSort   = new[]
                {
                    new ColumnsSortDef(Information.ExtractPropertyPath <Message>(x => x.Priority), SortOrder.Asc),
                    new ColumnsSortDef(Information.ExtractPropertyPath <Message>(x => x.SendingTime), SortOrder.Asc)
                };

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                DataObject[] messages = _dataService.LoadObjects(lcs);

                stopwatch.Stop();
                long time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(null, (int)time, "OptimizedSendingManager.ScanMessages() load messages.");

                int index = 0;
                while (index < messages.Length && TryEnqueue((Message)messages[index]))
                {
                    index++;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError("Send message error", exception.ToString());
            }
        }
Example #11
0
        public void BSTest()
        {
            // Объекты для тестирования создания.
            Медведь медв = new Медведь {
                Вес = 48
            };
            Лес лес1 = new Лес {
                Название = "Бор"
            };
            Лес лес2 = new Лес {
                Название = "Березовая роща"
            };

            медв.ЛесОбитания = лес1;
            var берлога1 = new Берлога {
                Наименование = "Для хорошего настроения", ЛесРасположения = лес1
            };
            var берлога2 = new Берлога {
                Наименование = "Для плохого настроения", ЛесРасположения = лес2
            };

            медв.Берлога.Add(берлога1);
            медв.Берлога.Add(берлога2);

            // Объекты для тестирования создания с обновлением.
            Медведь медвежонок = new Медведь {
                Вес = 12
            };
            var берлога3 = new Берлога {
                Наименование = "Для хорошего настроения", ЛесРасположения = лес1
            };

            медвежонок.Берлога.Add(берлога3);

            ActODataService(args =>
            {
                // ------------------ Только создания объектов ------------------
                // Подготовка тестовых данных в формате OData.
                var controller = new Controllers.DataObjectController(args.DataService, args.Token.Model, args.Token.Events, args.Token.Functions);
                System.Web.OData.EdmEntityObject edmObj = controller.GetEdmObject(args.Token.Model.GetEdmEntityType(typeof(Медведь)), медв, 1, null);
                var edmЛес1 = controller.GetEdmObject(args.Token.Model.GetEdmEntityType(typeof(Лес)), лес1, 1, null);
                var edmЛес2 = controller.GetEdmObject(args.Token.Model.GetEdmEntityType(typeof(Лес)), лес2, 1, null);
                edmObj.TrySetPropertyValue("ЛесОбитания", edmЛес1);
                var coll = controller.GetEdmCollection(медв.Берлога, typeof(Берлога), 1, null);
                edmObj.TrySetPropertyValue("Берлога", coll);
                System.Web.OData.EdmEntityObject edmБерлога1 = (System.Web.OData.EdmEntityObject)coll[0];
                System.Web.OData.EdmEntityObject edmБерлога2 = (System.Web.OData.EdmEntityObject)coll[1];
                edmБерлога1.TrySetPropertyValue("ЛесРасположения", edmЛес1);
                edmБерлога2.TrySetPropertyValue("ЛесРасположения", edmЛес2);

                // Формируем URL запроса к OData-сервису.
                string requestUrl = string.Format("http://localhost/odata/{0}", args.Token.Model.GetEdmEntitySet(typeof(Медведь)).Name);

                // Обращаемся к OData-сервису и обрабатываем ответ, в теле запроса передаем создаваемый объект в формате JSON.
                HttpResponseMessage response = args.HttpClient.PostAsJsonAsync(requestUrl, edmObj).Result;

                // Убедимся, что запрос завершился успешно.
                Assert.Equal(HttpStatusCode.Created, response.StatusCode);

                // Получим строку с ответом.
                string receivedJsonObjs = response.Content.ReadAsStringAsync().Result.Beautify();

                // В ответе приходит объект с созданной сущностью.
                // Преобразуем полученный объект в словарь.
                Dictionary <string, object> receivedObjs = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(receivedJsonObjs);
                Assert.Equal("Object created.", receivedObjs["ПолеБС"]);

                // Проверяем что созданы зависимые объекты, вычитав с помощью args.DataService
                var lcs          = LoadingCustomizationStruct.GetSimpleStruct(typeof(Берлога), "БерлогаE");
                lcs.LoadingTypes = new[] { typeof(Берлога) };

                var dobjs = args.DataService.LoadObjects(lcs);
                Assert.Equal(2, dobjs.Length);

                foreach (var obj in dobjs)
                {
                    var berloga = (Берлога)obj;
                    Assert.Equal("Object created.", berloga.ПолеБС);
                }
            });
        }
Example #12
0
        /// <summary>
        /// Подписать клиента на определенный тип сообщений или обновить подписку.
        /// </summary>
        /// <param name="clientId">Идентификатор клиента, подписку которого нужно обновить или создать.</param>
        /// <param name="messageTypeId">Тип сообщений подписки.</param><param name="isCallback">Является ли подписка callback.</param>
        /// <param name="transportType">Способ передачи сообщений, если подписка callback, иначе можно передать null.</param>
        /// <param name="expiryDate">Дата прекращения подписки. Если не указана, вычисляется как сумма текущей даты и параметра конфигурации UpdateForATime.</param>
        /// <param name="subscriptionId">Идентификатор подписки, которую нужно обновить или создать.</param>
        public void SubscribeOrUpdate(string clientId, string messageTypeId, bool isCallback, TransportType?transportType, DateTime?expiryDate = null, string subscriptionId = null)
        {
            Subscription[] subscriptions = GetSubscriptions(clientId, false).Where(x => x.MessageType.ID == messageTypeId || CompareGuid2Str(((KeyGuid)x.MessageType.__PrimaryKey).Guid, messageTypeId)).ToArray();
            Subscription   subscription  = subscriptionId == null?subscriptions.FirstOrDefault() : subscriptions.FirstOrDefault(s => CompareGuid2Str(((KeyGuid)s.__PrimaryKey).Guid, subscriptionId));

            Stopwatch stopwatch;
            long      time;

            if (subscription == null)
            {
                var langDef = ExternalLangDef.LanguageDef;

                LoadingCustomizationStruct clientLcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Client), Client.Views.EditView);
                clientLcs.LimitFunction = langDef.GetFunction(langDef.funcEQ, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <Client>(x => x.ID)), clientId);

                stopwatch = new Stopwatch();
                stopwatch.Start();

                var client = _dataService.LoadObjects(clientLcs).Cast <Client>().FirstOrDefault();

                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(null, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load Client.");

                if (client == null)
                {
                    throw new ArgumentException("clientId");
                }

                LoadingCustomizationStruct messageTypeLcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(MessageType), MessageType.Views.EditView);
                messageTypeLcs.LimitFunction = langDef.GetFunction(langDef.funcEQ, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <MessageType>(x => x.ID)), messageTypeId);

                stopwatch = new Stopwatch();
                stopwatch.Start();

                var messageType = _dataService.LoadObjects(messageTypeLcs).Cast <MessageType>().FirstOrDefault();

                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(null, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load TypeMessage.");

                if (messageType == null)
                {
                    throw new ArgumentException("messageTypeId");
                }

                subscription = new Subscription()
                {
                    Client = client, MessageType = messageType
                };
                if (subscriptionId != null)
                {
                    subscription.__PrimaryKey = Guid.Parse(subscriptionId);
                }
            }

            subscription.IsCallback = isCallback;

            if (transportType != null)
            {
                subscription.TransportType = transportType.Value;
            }
            else if (isCallback)
            {
                throw new ArgumentNullException(nameof(transportType));
            }

            if (expiryDate != null)
            {
                subscription.ExpiryDate = expiryDate.Value;
            }
            else
            {
                ServiceHelper.UpdateStoppingDate(subscription);
            }

            if (subscription.GetStatus() == ObjectStatus.Created)
            {
                lock (SubscriptionsLockObject)
                {
                    Subscriptions.Add(subscription);
                }
            }

            stopwatch = new Stopwatch();
            stopwatch.Start();

            _dataService.UpdateObject(subscription);

            stopwatch.Stop();
            time = stopwatch.ElapsedMilliseconds;
            _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load Client.");
        }
Example #13
0
        /// <summary>
        /// Уведомить о событии.
        /// </summary>
        /// <param name="clientId">Идентификатор клиента.</param>
        /// <param name="eventTypeId">Идентификатор типа события.</param>
        public override void RaiseEvent(string clientId, string eventTypeId)
        {
            if (!_objectRepository.GetRestrictionsForClient(clientId).Any(x => x.MessageType.ID == eventTypeId))
            {
                _logger.LogInformation("Отправка запрещена.", $"Клиент {clientId} не имеет прав на отправку сообщения типа {eventTypeId}.");
                return;
            }

            IEnumerable <Subscription> subscriptions = _subscriptionsManager.GetSubscriptionsForMsgType(eventTypeId, clientId);

            if (!subscriptions.Any())
            {
                _logger.LogInformation("Для сообщения нет ни одной подписки.", $"Было получено сообщение, для которого нет ни одной активной подписки (ID типа сообщения: {eventTypeId}).");
                return;
            }

            foreach (var subscription in subscriptions)
            {
                // Получение существующих событий по загруженным подпискам.
                LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageLightView);

                lcs.LimitFunction = _langDef.GetFunction(
                    _langDef.funcAND,
                    _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.Recipient)), ((KeyGuid)subscription.Client.__PrimaryKey).Guid),
                    _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.MessageType)), ((KeyGuid)subscription.MessageType.__PrimaryKey).Guid));

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                DataObject[] events = _dataService.LoadObjects(lcs);

                stopwatch.Stop();
                long time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.RaiseEvent() load messages.");


                if (events.Length != 0)
                {
                    continue;
                }

                // Создание нового уведомления о событии в случае, если оно еще не существует.
                var newEvent = new Message()
                {
                    ReceivingTime = DateTime.Now,
                    MessageType   = subscription.MessageType,
                    Recipient     = subscription.Client
                };

                stopwatch = new Stopwatch();
                stopwatch.Start();

                _dataService.UpdateObject(newEvent);

                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
                _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.RaiseEvent() update messages.");

                _statisticsService.NotifyMessageReceived(subscription);
            }
        }
Example #14
0
        /// <summary>
        /// Принять сообщение с именем группы.
        /// </summary>
        /// <param name="message">Принимаемое сообщение.</param>
        /// <param name="groupName">Имя группы.</param>
        public override void AcceptMessage(MessageForESB message, string groupName)
        {
            _logger.LogIncomingMessage(message);
            try
            {
                if (!_objectRepository.GetRestrictionsForClient(message.ClientID).Any(x => x.MessageType.ID == message.MessageTypeID))
                {
                    _logger.LogInformation("Отправка запрещена.", $"Клиент {message.ClientID} не имеет прав на отправку сообщения типа {message.MessageTypeID}.");
                    return;
                }

                IEnumerable <Subscription> subscriptions = _subscriptionsManager.GetSubscriptionsForMsgType(message.MessageTypeID, message.ClientID);

                if (!subscriptions.Any())
                {
                    _logger.LogInformation("Для сообщения нет ни одной подписки.", $"Было получено сообщение, для которого нет ни одной активной подписки (ID типа сообщения: {message.MessageTypeID}).");
                    return;
                }

                foreach (var subscription in subscriptions)
                {
                    // Ищем аналогичные сообщения с этой группой.
                    var messageWithGroupView = Message.Views.MessageLightView;

                    LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), messageWithGroupView);
                    lcs.LimitFunction = _langDef.GetFunction(
                        _langDef.funcAND,
                        _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.Recipient)), ((KeyGuid)subscription.Client.__PrimaryKey).Guid),
                        _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.GuidType, Information.ExtractPropertyPath <Message>(x => x.MessageType)), ((KeyGuid)subscription.MessageType.__PrimaryKey).Guid),
                        _langDef.GetFunction(_langDef.funcEQ, new VariableDef(_langDef.StringType, Information.ExtractPropertyPath <Message>(x => x.Group)), groupName));

                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();

                    DataObject[] messagesWithGroup = _dataService.LoadObjects(lcs);

                    stopwatch.Stop();
                    long time = stopwatch.ElapsedMilliseconds;
                    _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.AcceptMessage(MessageForESB message, string groupName) load Сообщения.");

                    if (messagesWithGroup.Length == 0)
                    {
                        var msgWithGroup = new Message();
                        ServiceHelper.SetMessageWithGroupValues(message, subscription, msgWithGroup, groupName, _dataService, _logger, _statisticsService);
                        msgWithGroup.SendingTime = DateTime.Now;

                        stopwatch = new Stopwatch();
                        stopwatch.Start();

                        _dataService.UpdateObject(msgWithGroup);

                        stopwatch.Stop();
                        time = stopwatch.ElapsedMilliseconds;
                        _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.AcceptMessage(MessageForESB message, string groupName) update Сообщения.");
                    }
                    else
                    {
                        var msgWithGroup = new Message {
                            __PrimaryKey = messagesWithGroup[0].__PrimaryKey
                        };
                        View msgWithGroupView = Message.Views.MessageEditView;

                        stopwatch = new Stopwatch();
                        stopwatch.Start();

                        _dataService.LoadObject(msgWithGroupView, msgWithGroup);

                        stopwatch.Stop();
                        time = stopwatch.ElapsedMilliseconds;
                        _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.AcceptMessage(MessageForESB message, string groupName) load group messages.");

                        ServiceHelper.SetMessageWithGroupValues(message, subscription, msgWithGroup, groupName, _dataService, _logger, _statisticsService);
                        msgWithGroup.SendingTime = DateTime.Now;

                        stopwatch = new Stopwatch();
                        stopwatch.Start();

                        _dataService.UpdateObject(msgWithGroup);

                        stopwatch.Stop();
                        time = stopwatch.ElapsedMilliseconds;
                        _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "DefaultReceivingManager.AcceptMessage(MessageForESB message, string groupName) update group messages.");
                    }

                    _statisticsService.NotifyMessageReceived(subscription);
                }
            }
            catch (Exception e)
            {
                _logger.LogUnhandledException(e);
                throw;
            }
        }