public override Invalidnost Map(Disability source, Invalidnost dest)
        {
            if (dest.GetStatus() == ObjectStatus.Created)
            {
                dest.__PrimaryKey = source.Guid;
            }

            dest.Gruppa =
                (tGruppaInvalidnosti)EnumCaption.GetValueFor(source.Group.ToString(), typeof(tGruppaInvalidnosti));
            dest.NomerSpravkiVTEK      = source.ReferenceNumberVTEK;
            dest.DataVydSpravVTEK      = (NullableDateTime)source.IssueDateVTEK;
            dest.OrganVydSprav         = source.OrgName;
            dest.StepenOgranichTrudosp =
                (tGruppaInvalidnosti)EnumCaption.GetValueFor(source.DisabilityDegree.ToString(),
                                                             typeof(tGruppaInvalidnosti));
            dest.KemVydSprMSE = source.ReferenceIssuedBy == null
                ? null
                : PKHelper.CreateDataObject <OrganVydDok>(source.ReferenceIssuedBy?.Guid);
            dest.LgKatLeechnosti = source.BeneficiaryPreferentialCategory == null
                ? null
                : PKHelper.CreateDataObject <LgKatLeechnosti>(source.BeneficiaryPreferentialCategory?.Guid);
            dest.CreateTime = source.CreateTime;
            dest.Creator    = source.Creator;
            dest.EditTime   = source.EditTime;
            dest.Editor     = source.Editor;
            return(dest);
        }
        public void TestEnumLinqToLcsWithVariable()
        {
            // Arrange.
            var      testProvider = new TestLcsQueryProvider <FullTypesMainAgregator>();
            PoleEnum poleEnum     = PoleEnum.Attribute1;
            var      predicate1   = (Expression <Func <FullTypesMainAgregator, bool> >)(o => o.PoleEnum == poleEnum);

            new Query <FullTypesMainAgregator>(testProvider).Where(predicate1).ToArray();

            Expression queryExpression = testProvider.InnerExpression;
            var        expected        = new LoadingCustomizationStruct(null)
            {
                LimitFunction =
                    ldef.GetFunction(
                        ldef.funcEQ,
                        new VariableDef(ldef.StringType, Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.PoleEnum)),
                        EnumCaption.GetCaptionFor(PoleEnum.Attribute1))
            };

            // Act.
            LoadingCustomizationStruct actual = LinqToLcs.GetLcs(queryExpression, FullTypesMainAgregator.Views.FullView);

            // Assert.
            Assert.True(Equals(expected, actual));
        }
        public override IzmenenieNaznachVypl Map(ChangeAppointmentPayment source, IzmenenieNaznachVypl dest)
        {
            if (dest.GetStatus() == ObjectStatus.Created)
            {
                dest.__PrimaryKey = source.Guid;
            }

            dest.DataNaznacheniia = (NullableDateTime)source.AppointmentDate;
            dest.DataOtmeny       = (NullableDateTime)source.CancellationDate;
            dest.TipVypl          = (tTipVyplaty)EnumCaption.GetValueFor(source.PaymentType.ToString(), typeof(tTipVyplaty));
            dest.PeriodPredost    =
                (tTipPerioda)EnumCaption.GetValueFor(EnumCaption.GetCaptionFor(source.Period), typeof(tTipPerioda));
            dest.Summa       = (NullableDecimal)source.Amount;
            dest.Primechanie = source.Note;
            dest.OrganSZ     = source.SocialProtectionAuthority == null
                ? null
                : PKHelper.CreateDataObject <OrganSZ>(source.SocialProtectionAuthority.Guid);
            dest.LgKatLeechnosti = source.BeneficiaryPreferentialCategory == null
                ? null
                : PKHelper.CreateDataObject <LgKatLeechnosti>(source.BeneficiaryPreferentialCategory.Guid);
            dest.Poluchatel = source.Recipient == null
                ? null
                : PKHelper.CreateDataObject <Leechnost>(source.Recipient.Guid);
            dest.Naznachenie = source.PaymentAppointment == null
                ? null
                : PKHelper.CreateDataObject <NaznachenieVyplaty>(source.PaymentAppointment.Guid);

            dest.CreateTime = source.CreateTime;
            dest.Creator    = source.Creator;
            dest.EditTime   = source.EditTime;
            dest.Editor     = source.Editor;

            return(dest);
        }
        public void TestEnumLinqToLcsWithoutVariable()
        {
            var exception = Xunit.Record.Exception(() =>
            {
                // Arrange.
                var testProvider = new TestLcsQueryProvider <FullTypesMainAgregator>();
                var predicate1   = (Expression <Func <FullTypesMainAgregator, bool> >)(o => o.PoleEnum == PoleEnum.Attribute1);
                new Query <FullTypesMainAgregator>(testProvider).Where(predicate1).ToArray();

                Expression queryExpression = testProvider.InnerExpression;
                var expected = new LoadingCustomizationStruct(null)
                {
                    LimitFunction =
                        ldef.GetFunction(
                            ldef.funcEQ,
                            new VariableDef(ldef.StringType, Information.ExtractPropertyPath <FullTypesMainAgregator>(x => x.PoleEnum)),
                            EnumCaption.GetCaptionFor(PoleEnum.Attribute1))
                };

                // Act.
                // При компиляции в VS2013 или VS2015 ServicePack 1 данная строка вызовет NotSupportedException.
                LoadingCustomizationStruct actual = LinqToLcs.GetLcs(queryExpression, FullTypesMainAgregator.Views.FullView);

                // Assert.
                Assert.True(Equals(expected, actual));
            });

            Assert.IsType(typeof(NotSupportedException), exception);
        }
Exemple #5
0
        /// <summary>
        /// Создать подписку в шине.
        /// </summary>
        /// <param name="subscription">Подписка.</param>
        void IServiceBusManager.CreateSubscription(ServiceBusSubscription subscription)
        {
            TransportType transportType;

            EnumCaption.TryGetValueFor(subscription.SendBy, out transportType);
            bool callback = subscription.Callback ?? false;

            _subscriptionsManager.SubscribeOrUpdate(subscription.ClientID, subscription.MessageTypeID, callback, transportType, subscription.ExpiryDate, subscription.ID);
        }
Exemple #6
0
 public void BuildEqualsTest40()
 {
     Assert.Equal(
         LangDef.GetFunction(
             LangDef.funcEQ,
             StringVarDef,
             EnumCaption.GetCaptionFor(tDayOfWeek.Day0)),
         FunctionBuilder.BuildEquals(StringVarDef, tDayOfWeek.Day0));
 }
        /// <summary>
        /// Преобразовать значение.
        /// </summary>
        /// <param name="value">Значение для преобразования.</param>
        /// <param name="toType">Тип, в который надо преобразовать.</param>
        /// <returns>Преобразованное значение.</returns>
        public static object Convert(object value, Type toType)
        {
            lock (TypeToTypeMethods)
            {
                Type fromType = value.GetType();

                if (fromType == toType)
                {
                    return(value);
                }

                if (fromType == typeof(string) && toType.IsEnum)
                {
                    return(EnumCaption.GetValueFor((string)value, toType));
                }

                if (fromType.IsEnum && toType == typeof(string))
                {
                    return(EnumCaption.GetCaptionFor(value));
                }

                if (fromType == typeof(int) && toType.IsEnum)
                {
                    return(Enum.Parse(toType, Enum.GetName(toType, value)));
                }

                if (fromType.IsEnum && toType == typeof(int))
                {
                    return((int)value);
                }

                TypeTypePair key = new TypeTypePair(fromType, toType);
                if (!ParsedTypes.Contains(fromType))
                {
                    AddTypeOperator(fromType);
                }

                if (!ParsedTypes.Contains(toType))
                {
                    AddTypeOperator(toType);
                }

                if (TypeToTypeMethods.ContainsKey(key))
                {
                    MethodInfo mi = TypeToTypeMethods[key];
                    return(mi.Invoke(null, new[] { value }));
                }

                if (toType == typeof(string))
                {
                    return(value.ToString());
                }

                return(System.Convert.ChangeType(value, toType));
            }
        }
Exemple #8
0
        public void EnumCaptionGetCaptionForWithoutCaptionTest()
        {
            // Arrange.

            // Act.
            string actual = EnumCaption.GetCaptionFor(CaseSensitiveEnum.CASEINSENSITIVEVAL);

            // Assert.
            Assert.Equal("CASEINSENSITIVEVAL", actual);
        }
Exemple #9
0
        public void EnumCaptionGetCaptionForTest()
        {
            // Arrange.

            // Act.
            string actual = EnumCaption.GetCaptionFor(NumberedYear.Year2012);

            // Assert.
            Assert.Equal("2012", actual);
        }
Exemple #10
0
        public void EnumCaptionGetCaptionForEmptyStringTest()
        {
            // Arrange.

            // Act.
            string actual = EnumCaption.GetCaptionFor(NumberedYear.Year2014);

            // Assert.
            Assert.Equal(string.Empty, actual);
        }
Exemple #11
0
        public void EnumCaptionGetValueForValueCaseInsensitiveTest()
        {
            // Arrange.
            Type enumType = typeof(NumberedYear);

            // Act.
            object actual = EnumCaption.GetValueFor("YeAr2012", enumType);

            // Assert.
            Assert.Equal(NumberedYear.Year2012, actual);
        }
Exemple #12
0
        public void EnumCaptionGetValueForNotEnumTest()
        {
            // Arrange.
            Type enumType = typeof(DateTime);

            // Act.
            object actual = EnumCaption.GetValueFor("Now", enumType);

            // Assert.
            Assert.Null(actual);
        }
Exemple #13
0
        public void EnumCaptionGetValueForNullTest()
        {
            // Arrange.
            Type enumType = typeof(NumberedYear);

            // Act.
            object actual = EnumCaption.GetValueFor(null, enumType);

            // Assert.
            Assert.Equal(NumberedYear.Year2014, actual);
        }
Exemple #14
0
        public void EnumCaptionGetValueForCaseInsensitive4Test()
        {
            // Arrange.
            Type enumType = typeof(CaseSensitiveEnum);

            // Act.
            // Входные параметры:  заголовок элемента перечисления "CaseINSENSITIVEVAL", тип элемента перечисления.
            object actual = EnumCaption.GetValueFor("CASEINSENSITIVEVAL", enumType);

            // Assert.
            Assert.Equal(CaseSensitiveEnum.CASEINSENSITIVEVAL, actual);
        }
Exemple #15
0
        public void EnumCaptionGetValueForCaseInsensitiveTest()
        {
            // Arrange.
            Type enumType = typeof(CaseSensitiveEnum);

            // Act.
            // Входные параметры:  заголовок элемента перечисления "Last day", тип элемента перечисления.
            object actual = EnumCaption.GetValueFor("Last day", enumType);

            // Assert.
            Assert.Equal(CaseSensitiveEnum.Year9999, actual);
        }
Exemple #16
0
        public void EnumCaptionTryGetValueForTestNegative()
        {
            // Arrange.
            NumberedYear actual;

            // Act.
            bool result = EnumCaption.TryGetValueFor("20-13", out actual);

            // Assert.
            Assert.False(result);
            Assert.Equal(default(NumberedYear), actual);
        }
Exemple #17
0
        public void EnumCaptionTryGetValueForTestPositive()
        {
            // Arrange.
            NumberedYear actual;

            // Act.
            bool result = EnumCaption.TryGetValueFor("2013", out actual);

            // Assert.
            Assert.True(result);
            Assert.Equal(NumberedYear.Year2013, actual);
        }
Exemple #18
0
        public void EnumCaptionGetValueForNumberTest()
        {
            // Arrange.
            Type enumType = typeof(NumberedYear);

            // Act.
            // Входные параметры:  заголовок элемента перечисления "2013", тип элемента перечисления.
            object actual = EnumCaption.GetValueFor("2013", enumType);

            // Assert.
            Assert.Equal(NumberedYear.Year2013, actual);
        }
Exemple #19
0
        public void EnumCaptionGetValueForEmptyTest()
        {
            // Arrange.
            Type enumType = typeof(NumberedYear);

            // Act.
            // Входные параметры: пустая строка, тип данных NumberedYear.
            object actual = EnumCaption.GetValueFor(string.Empty, enumType);

            // Assert.
            Assert.Equal(NumberedYear.Year2014, actual);
        }
Exemple #20
0
        public void EnumCaptionGetValueForSwappedCaptionTest()
        {
            // Arrange.
            Type enumType = typeof(SwappedEnum);

            // Act.
            // Входные параметры: заголовок элемента перечисления "SwappedVal", тип элемента перечисления.
            object actual = EnumCaption.GetValueFor("SwappedVal", enumType);

            // Assert.
            Assert.Equal(SwappedEnum.Val, actual);
        }
Exemple #21
0
        public override NaznachenieVyplaty Map(PaymentAppointment source, NaznachenieVyplaty dest, List <string> attrs)
        {
            if (dest.GetStatus() == ObjectStatus.Created || attrs == null)
            {
                return(Map(source, dest));
            }

            if (attrs.Contains(PaymentAppointment.ConstConfirmed))
            {
                dest.Podtverzhdeno =
                    (tLogicheskii)EnumCaption.GetValueFor(source.Confirmed.ToString(), typeof(tLogicheskii));
            }

            if (attrs.Contains(PaymentAppointment.ConstBenefit))
            {
                dest.Lgota = source.Benefit == null ? null : PKHelper.CreateDataObject <Lgota>(source.Benefit.Guid);
            }

            if (attrs.Contains(PaymentAppointment.ConstMedium))
            {
                dest.Nositel = source.Medium == null ? null : PKHelper.CreateDataObject <Leechnost>(source.Medium.Guid);
            }

            if (attrs.Contains(PaymentAppointment.ConstDependent))
            {
                dest.Izhdivenetc = source.Dependent == null
                    ? null
                    : PKHelper.CreateDataObject <Leechnost>(source.Dependent.Guid);
            }

            if (attrs.Contains(SyncXMLDataObject.ConstCreateTime))
            {
                dest.CreateTime = source.CreateTime;
            }

            if (attrs.Contains(SyncXMLDataObject.ConstCreator))
            {
                dest.Creator = source.Creator;
            }

            if (attrs.Contains(SyncXMLDataObject.ConstEditTime))
            {
                dest.EditTime = source.EditTime;
            }

            if (attrs.Contains(SyncXMLDataObject.ConstEditor))
            {
                dest.Editor = source.Editor;
            }

            return(dest);
        }
Exemple #22
0
        /// <summary>
        ///     Проверить и преобразовать аргумент в соответствии с типом.
        /// </summary>
        /// <param name="type">Тип.</param>
        /// <param name="value">Значение.</param>
        /// <exception cref="ArgumentException">Аргумент не содержит ключевой структуры.</exception>
        /// <exception cref="InvalidCastException">Не совпадают тип свойства и тип переданного параметра.</exception>
        /// <exception cref="FormatException"><seealso cref="M:Convert.ChangeType(object, Type)"/></exception>
        /// <returns>Преобразованный аргумент.</returns>
        internal static object ConvertValue(Type type, object value)
        {
            ValidateValue(value);

            var nctType = GetObjectType(type).NetCompatibilityType;
            var res     = value;

            if (res.GetType().IsEnum)
            {
                if (nctType == typeof(string))
                {
                    res = EnumCaption.GetCaptionFor(res);
                }
                else if (nctType == typeof(decimal))
                {
                    res = Convert.ChangeType(res, nctType);
                }
            }

            if (IsKeyType(nctType))
            {
                res = PKHelper.GetKeyByObject(res);
                if (res == null)
                {
                    throw new ArgumentException(nameof(value));
                }
            }

            ValidateValue(res);

            // Когда свойство строкового типа, а значение - не строка.
            if (nctType == typeof(string) && GetObjectType(res.GetType()).NetCompatibilityType != typeof(string))
            {
                res = Convert.ToString(res);
            }

            if (GetObjectType(res.GetType()).NetCompatibilityType != nctType)
            {
                if (res.GetType().GetInterfaces().Any(x => x == typeof(IConvertible)))
                {
                    // Попробуем преобразовать в нужный тип.
                    res = Convert.ChangeType(res, type);
                }
                else
                {
                    throw new InvalidCastException(nameof(value));
                }
            }

            return(res);
        }
        /// <summary>
        /// Обновить подписку.
        /// </summary>
        /// <param name="subscriptionId">Идентификатор подписки, которую нужно обновить.</param>
        /// <param name="subscription">Новые данные подписки.</param>
        public void UpdateSubscription(string subscriptionId, ServiceBusSubscription subscription)
        {
            Subscription currentSubscription = new Subscription {
                __PrimaryKey = subscriptionId
            };
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            _dataService.LoadObject(currentSubscription);

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

            _statisticsService.NotifyAvgTimeSql(null, (int)time, "DefaultSubscriptionsManager.UpdateSubscription() load subscription.");

            if (subscription.ExpiryDate != null)
            {
                currentSubscription.ExpiryDate = subscription.ExpiryDate.Value;
            }

            if (subscription.Description != null)
            {
                currentSubscription.Description = subscription.Description;
            }

            if (subscription.Callback != null)
            {
                bool callback = subscription.Callback.Value;
                currentSubscription.IsCallback = callback;
            }

            TransportType transportType;

            EnumCaption.TryGetValueFor(subscription.SendBy, out transportType);
            if (transportType != default(TransportType))
            {
                currentSubscription.TransportType = transportType;
            }

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

            _dataService.UpdateObject(currentSubscription);

            stopwatch.Stop();
            time = stopwatch.ElapsedMilliseconds;
            _statisticsService.NotifyAvgTimeSql(null, (int)time, "DefaultSubscriptionsManager.UpdateSubscription() update subscription.");
        }
        public override IQueryable <DataObject> GetAltKey(ChangeAppointmentPayment dobj, IDataService defDS,
                                                          IDataService syncDS, Source source, ref List <DataObject> arrToUpd,
                                                          ref Dictionary <string, List <DataObject> > arrConformity)
        {
            var naznachenie = MapperHelper.GetMaster(typeof(NaznachenieVyplaty), dobj.PaymentAppointment.Guid,
                                                     defDS.Query <NaznachenieVyplaty>(NaznachenieVyplaty.Views.NaznachenieVyplatyE), syncDS, source,
                                                     ref arrToUpd, ref arrConformity);
            var date        = (NullableDateTime)dobj.AppointmentDate;
            var paymentType = (tTipVyplaty)EnumCaption.GetValueFor(dobj.PaymentType.ToString(), typeof(tTipVyplaty));

            return(defDS.Query <IzmenenieNaznachVypl>(IzmenenieNaznachVypl.Views.AuditView).Where(x =>
                                                                                                  x.DataNaznacheniia == date &&
                                                                                                  x.TipVypl == paymentType &&
                                                                                                  x.Naznachenie.__PrimaryKey.Equals(naznachenie.__PrimaryKey)));
        }
Exemple #25
0
        public void EnumCaptionGetCaptionForNullTest()
        {
            var exception = Xunit.Record.Exception(() =>
            {
                // Arrange.

                // Act.
                EnumCaption.GetCaptionFor(null);

                // Assert.
                // Ожидаем исключения.
            });

            Assert.IsType(typeof(ArgumentNullException), exception);
        }
        public override IQueryable <DataObject> GetAltKey(Movement dobj, IDataService defDS, IDataService syncDS,
                                                          Source source, ref List <DataObject> arrToUpd, ref Dictionary <string, List <DataObject> > arrConformity)
        {
            var leechnost = MapperHelper.GetMaster(typeof(Leechnost), dobj.Beneficiary.Guid,
                                                   defDS.Query <Leechnost>(Leechnost.Views.LeechnostE), syncDS, source, ref arrToUpd, ref arrConformity);
            var address = Helper.GetProzhivanie(dobj.DepatureAddress, defDS, syncDS, source, ref arrToUpd,
                                                ref arrConformity);
            var typeAddress = (tTipAdresa)EnumCaption.GetValueFor(dobj.AddressType.ToString(), typeof(tTipAdresa));
            var date        = (NullableDateTime)dobj.DepatureDate;

            return(defDS.Query <Peremeshchenie>(Peremeshchenie.Views.PeremeshchenieE).Where(x =>
                                                                                            x.DataUbytiia == date &&
                                                                                            x.TipAdresa == typeAddress &&
                                                                                            x.AdresUbytiia.__PrimaryKey.Equals(address.__PrimaryKey) &&
                                                                                            x.Leechnost.__PrimaryKey.Equals(leechnost.__PrimaryKey)));
        }
Exemple #27
0
        public void EnumCaptionGetValueForNotExistTest()
        {
            var exception = Xunit.Record.Exception(() =>
            {
                // Arrange.
                Type enumType = typeof(NumberedYear);

                // Act.
                EnumCaption.GetValueFor("notexist", enumType);

                // Assert.
                // Ожидаем исключения.
            });

            Assert.IsType(typeof(ArgumentException), exception);
        }
Exemple #28
0
        public void EnumCaptionGetCaptionForNotEnumTest()
        {
            var exception = Xunit.Record.Exception(() =>
            {
                // Arrange.
                SimpleDataObject simpleDataObject = new SimpleDataObject();

                // Act.
                EnumCaption.GetCaptionFor(simpleDataObject);

                // Assert.
                // Ожидаем исключения.
            });

            Assert.IsType(typeof(NotEnumTypeException), exception);
        }
Exemple #29
0
        public void EnumCaptionGetValueForPositionNumberTest()
        {
            var exception = Xunit.Record.Exception(() =>
            {
                // Arrange.
                Type enumType = typeof(NumberedYear);

                // Act.
                // Enum.Parse вернул бы 1ый элемент enum, а GetValueFor должен бросить exception.
                EnumCaption.GetValueFor("1", enumType);

                // Assert.
                // Ожидаем исключения.
            });

            Assert.IsType(typeof(ArgumentException), exception);
        }
Exemple #30
0
        /// <summary>
        /// Возвращает количество взятий в прокат велосипедов выбранного типа.
        /// </summary>
        public static int GetRentsCount(BicycleType type)
        {
            var lcs  = LoadingCustomizationStruct.GetSimpleStruct(typeof(RentSession), RentSession.Views.RentSessionE);
            var ld   = SQLWhereLanguageDef.LanguageDef;
            var func = ld.GetFunction(
                ld.funcEQ,
                new VariableDef(
                    ld.StringType,
                    Information.ExtractPropertyPath <RentSession>(item => item.Bicycle.Type)
                    ),
                EnumCaption.GetCaptionFor(type)
                );

            lcs.LimitFunction = func;
            var ds = (SQLDataService)DataServiceProvider.DataService;

            return(ds.LoadObjects(lcs).Length);

            //return ds.Query<RentSession>(RentSession.Views.RentSessionE.Name)
            //    .Count(item => item.Bicycle.Type.Equals(type));
        }