Exemplo n.º 1
0
        /// <summary>
        /// Only intended to be used by the EntityFramework itself! Creates the native property information for a reflected managed property and returns the created managed EntityProperty. Returns 'null', if the property is not marked as 'EntityProperty', or no property converter can be found for the type of the property.
        /// </summary>
        /// <param name="managed">Managed.</param>
        internal static EntityProperty Create(PropertyInfo managed)
        {
            EntityPropertyAttribute attrib = (EntityPropertyAttribute)managed.GetCustomAttributes(typeof(EntityPropertyAttribute), true).FirstOrDefault();

            if (attrib == null)
            {
                return(null);
            }

            if (!s_converters.ContainsKey(managed.PropertyType))
            {
                return(null);
            }

            EEditTypes editType = attrib.EditType;

            if (editType == EEditTypes.Default)
            {
                editType = s_converters [managed.PropertyType].DefaultEditType;
            }
            string strEditType = StringValueAttribute.GetStringValue(editType);

            IEntityPropertyHandler.SPropertyInfo engine = new IEntityPropertyHandler.SPropertyInfo();
            engine.name        = managed.Name;
            engine.description = attrib.Description;
            engine.editType    = strEditType;
            engine.limits      = new IEntityPropertyHandler.SPropertyInfo.SLimits();
            engine.limits.min  = attrib.Min;
            engine.limits.max  = attrib.Max;
            engine.type        = s_converters [managed.PropertyType].EngineType;

            return(new EntityProperty(managed, engine, attrib.Default));
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string stringValue     = StringValueAttribute.GetValue(value);
            string translatedValue = Translation.GetTranslation(stringValue);

            return(translatedValue);
        }
Exemplo n.º 3
0
 public void TestHelpTopicsAssigned()
 {
     foreach (HelpTopic topic in Enum.GetValues(typeof(HelpTopic)))
     {
         Assert.IsFalse(string.IsNullOrEmpty(StringValueAttribute.GetValue(topic)), $"Topic {topic} does not have a html reference attached");
     }
 }
Exemplo n.º 4
0
 public void TestGetEnum()
 {
     Assert.AreEqual(TestEnum.Value1, StringValueAttribute.Get <TestEnum>("Test1"));
     Assert.AreEqual(TestEnum.Value2, StringValueAttribute.Get <TestEnum>(""));
     Assert.AreEqual(TestEnum.Value3, StringValueAttribute.Get <TestEnum>(null));
     Assert.AreEqual(TestEnum.Value1, StringValueAttribute.Get <TestEnum>("Missing")); // default(0) is Value1
 }
Exemplo n.º 5
0
 public void TestGetString()
 {
     Assert.AreEqual("Test1", StringValueAttribute.Get(TestEnum.Value1));
     Assert.AreEqual("", StringValueAttribute.Get(TestEnum.Value2));
     Assert.AreEqual(null, StringValueAttribute.Get(TestEnum.Value3));
     Assert.AreEqual(null, StringValueAttribute.Get(TestEnum.Value4));
 }
 public static void ValidateDefaults()
 {
     StringValueAttribute sav =  new StringValueAttribute("test");
     Assert.Equal(false, sav.IsDefaultAttribute());
     Assert.Equal(sav.GetType(), sav.TypeId);
     Assert.Equal(true, sav.Match(sav));
 }
 public static string SelecionaChaveParametroTipoMovimentacao
 (
     ChaveParametroTipoMovimentacao chave
 )
 {
     return(StringValueAttribute.GetStringValue(chave));
 }
Exemplo n.º 8
0
        public static void ValidateDefaults()
        {
            StringValueAttribute sav = new StringValueAttribute("test");

            Assert.Equal(false, sav.IsDefaultAttribute());
            Assert.Equal(sav.GetType(), sav.TypeId);
            Assert.Equal(true, sav.Match(sav));
        }
Exemplo n.º 9
0
        public void Ctor_Test()
        {
            // Act
            StringValueAttribute sva = new StringValueAttribute("value value");

            // Assert
            Assert.AreEqual("value value", sva.Value);
        }
Exemplo n.º 10
0
        public void TestStringValueAttributeGet()
        {
            TestClass2 item  = new TestClass2(7, "test", 0);
            string     value = StringValueAttribute.Get(() => item.Id);

            Assert.IsNotNull(value);
            Assert.IsTrue(((string)value).StartsWith("IdTest"));
        }
        public void LicenseStatus_ReturnsStatusFromEdition()
        {
            var viewModel = BuildViewModel();

            _activationHelper.LicenseStatus.Returns(LicenseStatus.Blocked);

            Assert.AreEqual(LicenseStatus.Blocked, viewModel.LicenseStatus);
            Assert.AreEqual(StringValueAttribute.GetValue(LicenseStatus.Blocked), viewModel.LicenseStatusText);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets a property's value.
        /// </summary>
        /// <param name="prop">The <see cref="PropertyInfo"/> object.</param>
        /// <param name="obj">The target object.</param>
        /// <returns>The string value.</returns>
        public static string GetPropValue(PropertyInfo prop, object obj)
        {
            var val = prop.GetValue(obj, null);

            if (val == null)
            {
                return(null);
            }

            if (val is bool boolVal)
            {
                return(boolVal ? "1" : "0");
            }

            if (val is Enum enumVal)
            {
                return(StringValueAttribute.GetStringValue(enumVal));
            }

            if (val is IEnumerable <Enum> enumVals)
            {
                return(enumVals.Select(x => StringValueAttribute.GetStringValue(x))
                       .Aggregate((ret, x) => $"{ret},{x}"));
            }

            if (val is IEnumerable <string> strVals)
            {
                return(strVals.Aggregate((ret, x) => $"{ret},{x}"));
            }

            if (val is IEnumerable <int> intVals)
            {
                return(intVals.Select(x => $"{x}")
                       .Aggregate((ret, x) => $"{ret},{x}"));
            }

            if (val is IEnumerable <long> longVals)
            {
                return(longVals.Select(x => $"{x}")
                       .Aggregate((ret, x) => $"{ret},{x}"));
            }

            var converterAttrType = typeof(JsonConverterAttribute);

            if (prop.GetCustomAttribute(converterAttrType) is JsonConverterAttribute converterAttr)
            {
                var converters = new[]
                {
                    (JsonConverter)Activator.CreateInstance(converterAttr.ConverterType),
                };

                return(JsonConvert.SerializeObject(val, converters));
            }

            return(val.ToString());
        }
Exemplo n.º 13
0
        public void ConstructTest()
        {
            // Test parameter validation/
            Assert.Throws <ArgumentNullException>(() => new StringValueAttribute(null));

            // Test normal operation.
            var attribute = new StringValueAttribute("FooBar");

            Assert.AreEqual("FooBar", attribute.Text);
        }
Exemplo n.º 14
0
        public bool DiscoverDevices(string name)
        {
            ICardDevice device = DeviceProvider.GetDevice(name);

            if (device == null)
            {
                throw new Exception(StringValueAttribute.GetStringValue(DeviceDiscovery.NoDeviceAvailable));
            }

            return(device.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        }
Exemplo n.º 15
0
 public override byte[] Serialize()
 {
     using (var stream = new MemoryStream())
     {
         stream.WriteASCII(StringValueAttribute.Get(MessageType));
         stream.WriteASCII(' ');
         stream.WriteASCII(FileId.ToString());
         stream.WriteASCII("\r\n\r\n");
         return(stream.ToArray());
     }
 }
Exemplo n.º 16
0
        private void TestSingleHelpFile(string filename, string folder)
        {
            var helpPath = folder;

            foreach (HelpTopic topic in Enum.GetValues(typeof(HelpTopic)))
            {
                var sourceFile = StringValueAttribute.GetValue(topic);
                sourceFile = Path.Combine(helpPath, sourceFile + ".html");
                Assert.IsTrue(File.Exists(sourceFile), $"Help file '{sourceFile}' does not exist in {filename}!");
            }
        }
        /// <summary>
        /// Retorna os parâmetros cadastrados para o parâmetro de movimentação
        /// </summary>
        /// <param name="valor"></param>
        /// <param name="chave">Chave</param>
        /// <returns></returns>
        public static bool VerificaValorParametroTipoMovimentacao
        (
            string valor
            , ChaveParametroTipoMovimentacao chave
        )
        {
            string valorChave = StringValueAttribute.GetStringValue(chave);

            MTR_ParametroTipoMovimentacaoDAO dao = new MTR_ParametroTipoMovimentacaoDAO();

            return(dao.SelectBy_ptm_chave_valor(valor, valorChave));
        }
Exemplo n.º 18
0
        public void TestStringValueAttributeGetAll()
        {
            TestClass2 item = new TestClass2(7, "test", 0);

            string[] values = StringValueAttribute.GetAll(() => item.Id);
            Assert.IsNotNull(values);
            List <string> list = new List <string>(values);

            Assert.IsTrue(list.IndexOf("IdTest1") >= 0);
            Assert.IsTrue(list.IndexOf("IdTest2") >= 0);
            Assert.IsTrue(list.IndexOf("IdTest3") >= 0);
        }
        public static string SelecionaValorParametroTipoMovimentacao
        (
            int tmo_id
            , ChaveParametroTipoMovimentacao chave
        )
        {
            string valorChave = StringValueAttribute.GetStringValue(chave);

            MTR_ParametroTipoMovimentacaoDAO dao = new MTR_ParametroTipoMovimentacaoDAO();

            return(dao.SelectBy_ptm_chave(tmo_id, valorChave));
        }
Exemplo n.º 20
0
        public void TestAttributeUtilGetCustomAttribute()
        {
            TestClass2           item      = new TestClass2(7, "test", 0);
            StringValueAttribute attribute = (StringValueAttribute)AttributeUtil.GetCustomAttribute(() => item.Id, typeof(StringValueAttribute));

            Assert.IsNotNull(attribute);
            Assert.IsTrue(attribute.Value.StartsWith("IdTest"));
            attribute = (StringValueAttribute)AttributeUtil.GetCustomAttribute(() => item.Name, typeof(StringValueAttribute));
            Assert.IsNotNull(attribute);
            Assert.AreEqual("NameTest", attribute.Value);
            attribute = (StringValueAttribute)AttributeUtil.GetCustomAttribute(() => item.Age, typeof(StringValueAttribute));
            Assert.IsNull(attribute);
        }
Exemplo n.º 21
0
        private ILocalizedTextRegistry FindRegistry()
        {
            var tagname  = StringValueAttribute.GetStringValue(Tags.Localization);
            var registry = GameObject.FindGameObjectWithTag(tagname);

                        #if UNITY_EDITOR
            if (registry == null)
            {
                Debug.LogWarning("Registry not found");
            }
                        #endif

            return((registry == null)? null : registry.GetComponent <ILocalizedTextRegistry>());
        }
Exemplo n.º 22
0
        public void AllErrorCodes_ArePresentInTranslation(ErrorCode errorCode)
        {
            // Store the english translator for other tests...
            if (_englishTranslator == null)
            {
                _englishTranslator = new BasicTranslator(Path.Combine(_translationTestHelper.FindTranslationFolder(), "english.ini"));
            }

            var section = "ErrorCodes";

            int exitCode     = (int)errorCode;
            var defaultValue = StringValueAttribute.GetValue(errorCode);

            Assert.AreEqual(defaultValue, _englishTranslator.GetTranslation(section, exitCode.ToString()), $"The value for {errorCode} ({exitCode}) is not set!\r\nAdd:\r\n{exitCode}={defaultValue}");
        }
Exemplo n.º 23
0
        private void TestSingleHelpFile(string filename, string folder, ManualPath filter)
        {
            var helpPath = folder;

            foreach (HelpTopic topic in Enum.GetValues(typeof(HelpTopic)))
            {
                var sourceFile = StringValueAttribute.GetValue(topic);
                if (filter == ManualPath.PdfCreatorManual && sourceFile.Contains("server"))
                {
                    continue;
                }

                sourceFile = Path.Combine(helpPath, sourceFile + ".html");
                Assert.IsTrue(File.Exists(sourceFile), $"Help file '{sourceFile}' does not exist in {filename}!");
            }
        }
        private MethodDeclarationSyntax GenerateDeserializeInto(LayoutInfo layoutInfo, TypeSyntax dataType, ITypeSymbol dataTypeSymbol)
        {
            var statements = new List <StatementSyntax>();

            var sortedMembers = layoutInfo.MemberInfos.OrderBy(a => a.LayoutAttribute.Offset);

            foreach (var member in sortedMembers)
            {
                var memberStatements = member.LayoutAttribute switch
                {
                    PrimitiveValueAttribute prim => GeneratePrimitiveValueRead(member, prim, dataTypeSymbol),
                    PrimitiveArrayAttribute arr => GeneratePrimitiveArrayRead(member, arr, dataTypeSymbol),
                    InPlaceObjectAttribute obj => GenerateInPlaceObjectRead(member, obj, dataTypeSymbol),
                    ReferenceValueAttribute refVal => GenerateReferenceValueRead(member, refVal, dataTypeSymbol),
                    ReferenceArrayAttribute reference => GenerateReferenceArrayRead(member, reference, dataTypeSymbol),
                    StringValueAttribute str => GenerateStringValueRead(member, str, dataTypeSymbol),
                    Utf16StringValueAttribute str => GenerateStringValueRead(member, str, dataTypeSymbol),

                    _ => Array.Empty <StatementSyntax>(),
                };

                statements.AddRange(memberStatements);
            }

            statements.AddRange(GenerateInternedStringMembers(sortedMembers, dataTypeSymbol));

            statements.Add(GenerateReturn());

            var t = ParseTypeName(serializableType.ToDisplayString());

            return(MethodDeclaration(t, SerializationClassAttribute.DeserializeIntoMethod)
                   .AddParameterListParameters(
                       Parameter(instanceParam).WithType(t),
                       Parameter(dataParam).WithType(dataType),
                       Parameter(startParam).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))
                       .WithDefault(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
                       Parameter(offsetParam).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))
                       .WithDefault(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
                       Parameter(stringsParam).WithType(ParseTypeName(nameof(IInternedStringProvider)))
                       .WithDefault(EqualsValueClause(LiteralExpression(SyntaxKind.NullLiteralExpression)))
                       )
                   .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))
                   .WithBody(Block(statements)));
        }
Exemplo n.º 25
0
 public override byte[] Serialize()
 {
     using (var stream = new MemoryStream())
     {
         stream.WriteASCII(StringValueAttribute.Get(MessageType));
         stream.WriteASCII(' ');
         stream.WriteASCII(VersionM.ToString("D"));
         stream.WriteASCII('.');
         stream.WriteASCII(VersionN.ToString("D"));
         stream.WriteASCII(' ');
         stream.WriteASCII(FileId.ToString());
         stream.WriteASCII(' ');
         stream.WriteASCII(ChunkNo.ToString("D"));
         stream.WriteASCII(' ');
         stream.WriteASCII(ReplicationDeg.ToString("D"));
         stream.WriteASCII("\r\n\r\n");
         stream.Write(Body);
         return(stream.ToArray());
     }
 }
Exemplo n.º 26
0
        public static Message Deserialize(byte[] data)
        {
            if (data == null)
            {
                return(null);
            }

            var    minLength = Math.Min(15, data.Length); // assuming max type length is 15
            string typeStr   = null;

            for (var i = 0; i < minLength; ++i)
            {
                if (data[i] == ' ')
                {
                    typeStr = Encoding.ASCII.GetString(data, 0, i);
                    break;
                }
            }

            if (string.IsNullOrWhiteSpace(typeStr))
            {
                return(null);
            }

            var type = StringValueAttribute.Get <MessageType>(typeStr);

            if (type == MessageType.None)
            {
                return(null);
            }

            Func <byte[], Message> deserializeMethod;

            if (_deserializeDict.TryGetValue(type, out deserializeMethod))
            {
                return(deserializeMethod(data));
            }
            return(null);
        }
Exemplo n.º 27
0
    private void Carregar(int rlt_id)
    {
        try
        {
            RelatoriosCor value       = (RelatoriosCor)VS_rlt_id;
            string        description = GetGlobalResourceObject("Enumerador", StringValueAttribute.GetStringDescription(value)).ToString();
            lblVariavel.Text = "Relatório: " + description;

            // quantidade de itens por página
            string qtItensPagina = SYS_ParametroBO.ParametroValor(SYS_ParametroBO.eChave.QT_ITENS_PAGINACAO);
            int    itensPagina   = string.IsNullOrEmpty(qtItensPagina) ? ApplicationWEB._Paginacao : Convert.ToInt32(qtItensPagina);

            grvCadastroCor.PageSize   = itensPagina;
            grvCadastroCor.DataSource = CFG_CorRelatorioBO.SelecionaCoresRelatorio(rlt_id);
            grvCadastroCor.DataBind();
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar cores do relatório", UtilBO.TipoMensagem.Erro);
        }
    }
Exemplo n.º 28
0
        public static string GetEnumByStringValueAttribute <TEnum>(TEnum value)
        {
            var enumType = Nullable.GetUnderlyingType(value.GetType()) ?? value.GetType();

            foreach (TEnum val in Enum.GetValues(enumType))
            {
                if (val.Equals(value))
                {
                    var fi         = enumType.GetField(val.ToString());
                    var attributes = (StringValueAttribute[])fi.GetCustomAttributes(
                        typeof(StringValueAttribute), false);
                    if (attributes.Any())
                    {
                        StringValueAttribute attr = attributes[0];
                        return(attr.Value);
                    }

                    return(value.ToString());
                }
            }
            throw new ArgumentException("The value '" + value + "' is not supported.");
        }
Exemplo n.º 29
0
        /// <summary>
        /// Fetch all available appointment booking for a Provider based on the given date.
        /// </summary>
        /// <param name="providerId"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public List <String> GetAvailableAppointmentBookings(int providerId, string date)
        {
            using (var dataContext = new HealthReunionEntities())
            {
                var           parsedDate       = DateTime.Parse(date);
                List <String> availableSlots   = new List <String>();
                var           appointmentEnums = StringValueAttribute.GetStringValues(typeof(AppointmentTimeEnum));
                var           matchedAppointmentBookingTime = (from appointment in dataContext.Appointments
                                                               where appointment.AppointmentDate == parsedDate &&
                                                               appointment.ProviderId == providerId
                                                               select appointment.Time).ToList();

                foreach (var time in appointmentEnums)
                {
                    if (!matchedAppointmentBookingTime.Contains(time))
                    {
                        availableSlots.Add(time);
                    }
                }

                return(availableSlots);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public HttpRequestMessage CreateRequest(BaseRestService service)
        {
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(StringValueAttribute.GetStringValue(this.HttpMethod)), BuildUrl());

            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Utilities.EncodeCredentials(service.Credentials.ApiKey, service.Credentials.SecretKey));
            request.Headers.Add("Y-Client-Type", ".NET");
            request.Headers.Add("Y-Client-Info", service.GetType().GetTypeInfo().Assembly.FullName);

#if NETSTANDARD1_3
            request.Headers.Add("Y-Client-Platform", System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
            request.Headers.Add("Y-Client-Platform", System.Environment.OSVersion.ToString());
#endif

            if (service.CustomHeaders != null && service.CustomHeaders.Count > 0)
            {
                foreach (var customHeader in service.CustomHeaders)
                {
                    request.Headers.Add(customHeader.Key, customHeader.Value);
                }
            }

            return(request);
        }
        public string GetErrorText(ErrorCode errorCode, bool withNumber)
        {
            var errorNumber = (int)errorCode;

            var errorCodeSection = errorNumber.ToString();
            var errorMessage     = _translator.GetTranslation("ErrorCodes", errorCodeSection);

            if (string.IsNullOrWhiteSpace(errorMessage))
            {
                errorMessage = StringValueAttribute.GetValue(errorCode);
            }

            if (string.IsNullOrWhiteSpace(errorMessage))
            {
                errorMessage = _translator.GetTranslation("ErrorCodes", "Default");
            }

            if (withNumber)
            {
                return(errorNumber + " - " + errorMessage);
            }

            return(errorMessage);
        }