Exemple #1
0
        public static string GetDescription(this Enum value)
        {
            if (null == value || value.ToString() == "-1")
            {
                return(string.Empty);
            }

            System.Reflection.FieldInfo field      = value.GetType().GetField(value.ToString());
            DescriptionAttribute[]      attributes = (DescriptionAttribute[])field?.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return(attributes?.Length > 0 ? attributes[0]?.Description : value.ToString());
        }
        /// <summary>
        /// Obter o valor da Annotation Description: [Description("Minha Descrição")]
        /// </summary>
        /// <typeparam name="TType">automaticamente obtido com o objeto.</typeparam>
        /// <param name="myEnum">objeto do tipo Enum.</param>
        /// <returns></returns>

        public static string GetDescription <TType>(this TType myEnum) where TType : Enum
        {
            System.Reflection.FieldInfo _fieldInfo = myEnum.GetType().GetField(myEnum.ToString());

            DescriptionAttribute[] _customAttributes = (DescriptionAttribute[])_fieldInfo?.GetCustomAttributes(
                typeof(DescriptionAttribute), false);

            return
                (_customAttributes != null && _customAttributes.Any()
                       ? _customAttributes[0].Description
                       : myEnum.ToString());
        }
        public static string GetStringValue(this Enum value)
        {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

            // Caso retorne NULL é porque não encontro o enum
            if (fieldInfo != null)
            {
                // Get the stringvalue attributes
                StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                    typeof(StringValueAttribute), false) as StringValueAttribute[];

                // Return the first if there was a match.
                return(attribs.Length > 0 ? attribs[0].StringValue : null);
            }
            else
            {
                return(string.Empty);
            }
        }
        public static string ToStringAttribute(this Enum value)
        {
            System.Collections.Hashtable _stringValues = new System.Collections.Hashtable();

            string output = null;
            Type   type   = value.GetType();

            if (_stringValues.ContainsKey(value))
            {
                output = (_stringValues[value] as StringValueAttribute).Value;
            }
            else
            {
                System.Reflection.FieldInfo fi        = type.GetField(value.ToString());
                StringValueAttribute[]      atributos = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (atributos.Length > 0)
                {
                    _stringValues.Add(value, atributos[0]);
                    output = atributos[0].Value;
                }
            }
            return(output);
        }
        /// <summary>
        /// 获取枚举类子项描述信息
        /// </summary>
        /// <param name="enumSubitem">枚举类子项</param>
        public static string GetEnumDescription(this Enum enumSubitem)
        {
            string strValue = enumSubitem.ToString();

            System.Reflection.FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);
            if (fieldinfo != null)
            {
                Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs == null || objs.Length == 0)
                {
                    return(strValue);
                }
                else
                {
                    DescriptionAttribute da = (DescriptionAttribute)objs[0];
                    return(da.Description);
                }
            }
            else
            {
                return("UnKonw");
            }
        }
Exemple #6
0
 public static EnumTitleAttribute GetEnumTitleAttribute(Enum e, Enum language = null)
 {
     if (e == null)
     {
         return null;
     }
     string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries);
     Type type = e.GetType();
     EnumTitleAttribute ret = null;
     foreach (string enumValue in valueArray)
     {
         System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim());
         if (fi == null)
             continue;
         EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[];
         if (attrs != null && attrs.Length > 0)
         {
             ret = attrs[0];
             break;
         }
     }
     return ret;
 }
        public static string GeneratedCode(object obj)
        {
            Debug.Check(obj != null);

            if (obj != null)
            {
                Type type = obj.GetType();
                Debug.Check(type.IsEnum);

                string enumName = Enum.GetName(type, obj);

                System.Reflection.FieldInfo fi = obj.GetType().GetField(obj.ToString());
                Attribute[] attributes         = (Attribute[])fi.GetCustomAttributes(typeof(EnumMemberDescAttribute), false);

                if (attributes.Length > 0)
                {
                    enumName = ((EnumMemberDescAttribute)attributes[0]).NativeValue;
                }

                return(enumName);
            }

            return(string.Empty);
        }
        public static bool isDefaultLeafValue(object from, string propertyName, object leafValue, LeafDefaultSet LeafDefaultSet)
        {
            // check the attribute
            FieldInfo fieldInfo = from.GetType().GetField(propertyName);

            if (fieldInfo == null)
            {
                return(false);
            }
            object[] dmas = fieldInfo.GetCustomAttributes(typeof(DataMemberAttribute), true);
            //check whether we are emitting default values
            if (dmas.Length == 0 || ((DataMemberAttribute)dmas[0]).EmitDefaultValue)
            {
                return(false);
            }

            if (leafValue == null)
            {
                return(true);
            }
            Type leafType = leafValue.GetType();

            if (Nullable.GetUnderlyingType(leafType) != null)
            {
                leafType = Nullable.GetUnderlyingType(leafType);
            }
            if (NumberTypes.Contains(leafType))
            {
                return(leafValue.Equals((int)0) || leafValue.Equals((double)0.0) || leafValue.Equals((uint)0) || leafValue.Equals((float)0));
            }
            if (leafType == typeof(bool) || leafType == typeof(Boolean))
            {
                return(!((bool)leafValue));
            }
            return(false);
        }
Exemple #9
0
        /// <summary>
        /// 获取枚举的描述 Description
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Type enumType, object val)
        {
            if (val == null)
            {
                return("");
            }
            string enumvalue = System.Enum.GetName(enumType, val);

            if (string.IsNullOrEmpty(enumvalue))
            {
                return("");
            }
            System.Reflection.FieldInfo finfo = enumType.GetField(enumvalue);
            object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
            if (enumAttr.Length > 0)
            {
                System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute;
                if (desc != null)
                {
                    return(desc.Description);
                }
            }
            return(enumvalue);
        }
Exemple #10
0
        protected void ImprimirReporte(Dictionary <string, Object> datos, XmlDocument documento)
        {
            try
            {
                #region Obtener Formato del XML
                string leyendaCondiciones      = string.Empty;
                string leyendaCargoCombustible = string.Empty;
                string leyendaBitacora         = string.Empty;
                string leyendaSeguro           = string.Empty;
                string leyendaArrendatarios    = string.Empty;
                string leyendaOperacion        = string.Empty;
                string leyendaInspeccion       = string.Empty;
                string leyendaTitulo           = string.Empty;
                string numeroPlaca             = string.Empty;
                string direccionSuc            = string.Empty;
                string telefonoUO  = string.Empty;
                string direccionUO = string.Empty;

                XmlNodeList textoCondiciones = documento.GetElementsByTagName("condiciones");
                if (textoCondiciones.Count < 1)
                {
                    throw new Exception("el formato del archivo XML es incorrecto");
                }
                leyendaCondiciones = textoCondiciones[0].InnerText;
                XmlNodeList textoCargoCombustible = documento.GetElementsByTagName("cargoCombustible");
                if (textoCargoCombustible.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaCargoCombustible = textoCargoCombustible[0].InnerText;
                XmlNodeList textoBitacora = documento.GetElementsByTagName("bitacora");
                if (textoBitacora.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaBitacora = textoBitacora[0].InnerText;
                XmlNodeList textoSeguro = documento.GetElementsByTagName("seguro");
                if (textoSeguro.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaSeguro = textoSeguro[0].InnerText;
                XmlNodeList textoArrendatarios = documento.GetElementsByTagName("arrendatarios");
                if (textoArrendatarios.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaArrendatarios = textoArrendatarios[0].InnerText;
                XmlNodeList textoOperacion = documento.GetElementsByTagName("operacion");
                if (textoOperacion.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaOperacion = textoOperacion[0].InnerText;
                XmlNodeList textoInspeccion = documento.GetElementsByTagName("inspeccion");
                if (textoInspeccion.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaInspeccion = textoInspeccion[0].InnerText;
                XmlNodeList textoTitulo = documento.GetElementsByTagName("Titulo");
                if (textoTitulo.Count < 1)
                {
                    throw new Exception("El formato del archivo XML es incorrecto");
                }
                leyendaTitulo = textoTitulo[0].InnerText;
                #endregion
                #region Iniciar Variables

                if (datos["Contrato"] == null)
                {
                    throw new Exception("Se esperaba un contrato");
                }
                if (datos["Firmantes"] == null)
                {
                    throw new Exception("Se esperaba Firmantes");
                }
                if (datos["Modulo"] == null)
                {
                    throw new Exception("Se esperaba una configuración de módulo");
                }
                if (!(datos["Contrato"] is ContratoRDBO))
                {
                    throw new Exception("Se esperaba un contrato de Renta Diaria");
                }

                // Contrato
                ContratoRDBO contrato = (ContratoRDBO)datos["Contrato"];
                if (contrato == null)
                {
                    contrato = new ContratoRDBO();
                }
                if (contrato.Sucursal == null)
                {
                    contrato.Sucursal = new SucursalBO();
                }
                if (contrato.Sucursal.DireccionesSucursal == null)
                {
                    direccionSuc = string.Empty;
                }
                else
                {
                    var direcUO = contrato.Sucursal.DireccionesSucursal.Find(x => x.Primaria != null && x.Primaria.Value == true);
                    if (direcUO != null)
                    {
                        if (!string.IsNullOrEmpty(direcUO.Calle) &&
                            !string.IsNullOrWhiteSpace(direcUO.Calle))
                        {
                            direccionSuc = direcUO.Calle;
                        }
                    }
                }
                if (contrato.Cliente == null)
                {
                    contrato.Cliente = new CuentaClienteIdealeaseBO();
                }
                if (contrato.Cliente.Cliente == null)
                {
                    contrato.Cliente.Cliente = new ClienteBO();
                }
                if (contrato.Cliente.Direcciones == null)
                {
                    DireccionClienteBO direccion = new DireccionClienteBO();
                    contrato.Cliente.Agregar(direccion);
                }
                if (contrato.Operador == null)
                {
                    contrato.Operador = new OperadorBO();
                }
                if (contrato.Operador.Direccion == null)
                {
                    contrato.Operador.Direccion = new DireccionPersonaBO();
                }
                if (contrato.Operador.Licencia == null)
                {
                    contrato.Operador.Licencia = new LicenciaBO();
                }
                if (contrato.Operador.Direccion.Ubicacion == null)
                {
                    contrato.Operador.Direccion.Ubicacion = new UbicacionBO();
                }
                if (contrato.Operador.Direccion.Ubicacion.Ciudad == null)
                {
                    contrato.Operador.Direccion.Ubicacion.Ciudad = new CiudadBO();
                }
                if (contrato.Operador.Direccion.Ubicacion.Estado == null)
                {
                    contrato.Operador.Direccion.Ubicacion.Estado = new EstadoBO();
                }

                LineaContratoRDBO linea = contrato.ObtenerLineaContrato();
                if (linea == null)
                {
                    linea = new LineaContratoRDBO();
                }
                if (linea.Equipo == null)
                {
                    linea.Equipo = new UnidadBO();
                }
                if (linea.Equipo.TipoEquipoServicio == null)
                {
                    linea.Equipo.TipoEquipoServicio = new TipoUnidadBO();
                }
                if (linea.Equipo.ActivoFijo == null)
                {
                    linea.Equipo.ActivoFijo = new ActivoFijoBO();
                }
                if (linea.Equipo.Modelo == null)
                {
                    linea.Equipo.Modelo = new ModeloBO();
                }
                if (((UnidadBO)linea.Equipo).CaracteristicasUnidad == null)
                {
                    ((UnidadBO)linea.Equipo).CaracteristicasUnidad = new CaracteristicasUnidadBO();
                }
                if (linea.Equipo.TipoEquipoServicio == null)
                {
                    linea.Equipo.TipoEquipoServicio = new TipoUnidadBO();
                }
                if (linea.Cobrable == null)
                {
                    linea.Cobrable = new TarifaContratoRDBO();
                }
                contrato.LineasContrato = new List <ILineaContrato>();
                contrato.AgregarLineaContrato(linea);
                if (linea.ListadosVerificacion == null)
                {
                    linea.ListadosVerificacion = new List <ListadoVerificacionBO>();
                }

                // Configuración del Modulo

                ModuloBO modulo = (ModuloBO)datos["Modulo"];
                ConfiguracionUnidadOperativaBO unidadOperativaConfiguracion;
                if (modulo == null)
                {
                    modulo = new ModuloBO();
                }
                if (modulo.Configuracion == null)
                {
                    modulo.Configuracion = new ConfiguracionModuloBO();
                }
                if (contrato.Sucursal.UnidadOperativa.Id == null)
                {
                    unidadOperativaConfiguracion = new ConfiguracionUnidadOperativaBO();
                }
                else
                {
                    unidadOperativaConfiguracion = modulo.ObtenerConfiguracionUO(new UnidadOperativaBO {
                        Id = contrato.Sucursal.UnidadOperativa.Id
                    });
                }
                if (unidadOperativaConfiguracion == null)
                {
                    unidadOperativaConfiguracion = new ConfiguracionUnidadOperativaBO();
                }
                if (unidadOperativaConfiguracion.ConfiguracionModulo == null)
                {
                    unidadOperativaConfiguracion.ConfiguracionModulo = new ConfiguracionModuloBO();
                }
                //Tramites
                List <TramiteBO> tramites = (List <TramiteBO>)datos["Tramites"];
                if (tramites == null)
                {
                    tramites = new List <TramiteBO>();
                }

                PlacaEstatalBO placaEstatal = (PlacaEstatalBO)tramites.Find(t => t.Tipo == ETipoTramite.PLACA_ESTATAL);
                if (placaEstatal != null)
                {
                    numeroPlaca = placaEstatal.Resultado;
                }
                PlacaFederalBO placaFederal = (PlacaFederalBO)tramites.Find(t => t.Tipo == ETipoTramite.PLACA_FEDERAL);
                if (placaFederal != null)
                {
                    numeroPlaca = placaFederal.Resultado;
                }
                //Firmantes

                Tuple <IConstituible, List <PersonaBO>, List <IConstituible> > firmantes =
                    (Tuple <IConstituible, List <PersonaBO>, List <IConstituible> >)datos["Firmantes"];
                if (firmantes == null)
                {
                    IConstituible        cliente        = new CuentaClienteIdealeaseBO();
                    List <PersonaBO>     representantes = new List <PersonaBO>();
                    List <IConstituible> depositarios   = new List <IConstituible>();
                    firmantes = new Tuple <IConstituible, List <PersonaBO>, List <IConstituible> >(cliente, representantes,
                                                                                                   depositarios);
                }

                //Usuarios
                UsuarioBO usuarioCreacion = (UsuarioBO)datos["UsuarioCreacion"];
                if (usuarioCreacion == null)
                {
                    usuarioCreacion = new UsuarioBO();
                }

                UsuarioBO usuarioCierre = (UsuarioBO)datos["UsuarioCierre"];
                if (usuarioCierre == null)
                {
                    usuarioCierre = new UsuarioBO();
                }

                //Sucursal Matriz
                SucursalBO matriz = (SucursalBO)datos["SucursalMatriz"];
                if (matriz == null)
                {
                    matriz = new SucursalBO();
                }
                if (matriz.UnidadOperativa == null)
                {
                    matriz.UnidadOperativa = new UnidadOperativaBO();
                }
                if (matriz.DireccionesSucursal == null)
                {
                    direccionUO = string.Empty;
                }
                else
                {
                    var direcUO = matriz.DireccionesSucursal.Find(x => x.Primaria != null && x.Primaria.Value == true);
                    if (direcUO != null)
                    {
                        if (!string.IsNullOrEmpty(direcUO.Telefono) &&
                            !string.IsNullOrWhiteSpace(direcUO.Telefono))
                        {
                            telefonoUO = direcUO.Telefono;
                            if (!string.IsNullOrEmpty(direcUO.Calle) &&
                                !string.IsNullOrWhiteSpace(direcUO.Calle))
                            {
                                direccionUO = direcUO.Calle;
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(direcUO.Calle) &&
                                !string.IsNullOrWhiteSpace(direcUO.Calle))
                            {
                                direccionUO = direcUO.Calle;
                            }
                        }
                    }
                }

                #endregion
                #region Asignar valores al Reporte
                #region Encabezado
                xrlblTitulo.Html = leyendaTitulo;
                if (String.IsNullOrEmpty(unidadOperativaConfiguracion.ConfiguracionModulo.URLLogoEmpresa))
                {
                    xrLogo.ImageUrl = modulo.Configuracion.URLLogoEmpresa;
                }
                else
                {
                    xrLogo.ImageUrl = unidadOperativaConfiguracion.ConfiguracionModulo.URLLogoEmpresa;
                }
                xrlblFormatoNumero.Text = contrato.NumeroContrato ?? String.Empty;
                if (contrato.Estatus == EEstatusContrato.Borrador || contrato.Estatus == EEstatusContrato.EnPausa)
                {
                    Watermark.Text = "BORRADOR";
                }

                #endregion
                #region Seccion Izquierda

                xrlblUnidadOperativa.Text = matriz.UnidadOperativa.Nombre ?? String.Empty;
                xrlblCliente.Text         = contrato.Cliente.Nombre ?? String.Empty;
                xrlblRFC.Text             = contrato.Cliente.Cliente.RFC ?? String.Empty;
                xrtblCellDireccion.Text   = contrato.Cliente.Direccion ?? String.Empty;

                DireccionClienteBO direccionCliente = contrato.Cliente.Direcciones.Find(c => c.Primaria != null && c.Primaria.Value) ??
                                                      new DireccionClienteBO();

                if (direccionCliente.Ubicacion == null)
                {
                    direccionCliente.Ubicacion = new UbicacionBO();
                }
                if (direccionCliente.Ubicacion.Ciudad == null)
                {
                    direccionCliente.Ubicacion.Ciudad = new CiudadBO();
                }
                if (direccionCliente.Ubicacion.Estado == null)
                {
                    direccionCliente.Ubicacion.Estado = new EstadoBO();
                }

                xrtblCellCiudad.Text = direccionCliente.Ubicacion.Ciudad.Codigo ?? String.Empty;
                xrtblCellEstado.Text = direccionCliente.Ubicacion.Estado.Codigo ?? String.Empty;
                xrtblCellCP.Text     = direccionCliente.CodigoPostal ?? String.Empty;



                xrtblCellNumeroCuenta.Text = contrato.Cliente.Id != null?contrato.Cliente.Id.ToString() : String.Empty;

                //SC0021 orden de compra con N/A
                if (contrato.FormaPago == null)
                {
                    xrtblCellOrdenCompra.Text = String.Empty;
                }
                if (contrato.FormaPago == null && contrato.TipoConfirmacion == null)
                {
                    xrtblCellOrdenCompra.Text = String.Empty;
                }
                else
                {
                    if (contrato.FormaPago != null && contrato.TipoConfirmacion != null &&
                        contrato.FormaPago == EFormaPago.CREDITO &&
                        contrato.TipoConfirmacion == ETipoConfirmacion.ORDEN_DE_COMPRA)
                    {
                        xrtblCellOrdenCompra.Text = contrato.AutorizadorOrdenCompra;
                    }
                    else
                    {
                        xrtblCellOrdenCompra.Text = "N/A";
                    }
                }
                xrtblCellNombreOperador.Text      = contrato.Operador.Nombre ?? String.Empty;
                xrtblCellExperienciaOperador.Text = contrato.Operador.AñosExperiencia != null
                                                        ? contrato.Operador.AñosExperiencia.ToString()
                                                        : String.Empty;

                xrtblCellCalleOperador.Text  = contrato.Operador.Direccion.Calle ?? String.Empty;
                xrtblCellCiudadOperador.Text = contrato.Operador.Direccion.Ubicacion.Ciudad.Nombre ?? String.Empty;
                xrtblCellEstadoOperador.Text = contrato.Operador.Direccion.Ubicacion.Estado.Nombre ?? String.Empty;
                xrtblCellCPOperador.Text     = contrato.Operador.Direccion.CodigoPostal ?? String.Empty;
                if (contrato.Operador.Licencia.Tipo == ETipoLicencia.ESTATAL)
                {
                    xrchkEstatal.Checked = true;
                }
                if (contrato.Operador.Licencia.Tipo == ETipoLicencia.FEDERAL)
                {
                    xrchkFederal.Checked = true;
                }
                xrTableCell20.Controls.Add(xrchkEstatal);
                xrTableCell21.Controls.Add(xrchkFederal);
                xrtblCellNumeroLicencia.Text  = contrato.Operador.Licencia.Numero ?? String.Empty;
                xrtblCellEstadoLicencia.Text  = contrato.Operador.Licencia.Estado ?? String.Empty;
                xrtblCellFechaExpiracion.Text = contrato.Operador.Licencia.FechaExpiracion != null
                                                    ? contrato.Operador.Licencia.FechaExpiracion.Value.ToString("dd/MM/yyyy")
                                                    : String.Empty;

                xrtblCellFechaNacimiento.Text = contrato.Operador.FechaNacimiento != null
                                                    ? contrato.Operador.FechaNacimiento.Value.ToString("dd/MM/yyyy")
                                                    : String.Empty;

                xrlblLeyendaCondiciones.Html      = leyendaCondiciones;
                xrtblCellAreaOperacion.Text       = contrato.DestinoAreaOperacion ?? String.Empty;
                xrtblCellVehiculoDevuelto.Text    = direccionSuc ?? String.Empty;
                xrtblCellMercanciaTrasportar.Text = contrato.MercanciaTransportar ?? String.Empty;

                if (contrato.MotivoRenta == EMotivoRenta.DEMOSTRACION)
                {
                    xrchkDemostracion.Checked = true;
                }
                if (contrato.MotivoRenta == EMotivoRenta.MATERIAL_PELIGROSO)
                {
                    xrchkMaterialPeligroso.Checked = true;
                }
                if (contrato.MotivoRenta == EMotivoRenta.SUSTITUCION_TEMPORAL)
                {
                    xrchkSustitucionTemporal.Checked = true;
                }
                if (contrato.MotivoRenta == EMotivoRenta.UNIDAD_EXTRA)
                {
                    xrchkUnidadExtra.Checked = true;
                }
                xrlblLeyendaCargosCombustible.Html = leyendaCargoCombustible;
                xrlblLeyendaBitacoraViaje.Html     = leyendaBitacora;
                if (contrato.BitacoraViajeConductor == true)
                {
                    xrchkBitacora.Checked = true;
                }

                SeguroBO seguro = (SeguroBO)tramites.Find(t => t.Tipo == ETipoTramite.SEGURO);
                if (seguro != null)
                {
                    string aseguradoraTelefono = string.Empty;
                    aseguradoraTelefono = !String.IsNullOrEmpty(seguro.Aseguradora) ? seguro.Aseguradora : string.Empty;

                    aseguradoraTelefono = !String.IsNullOrEmpty(seguro.Contacto)
                                              ? (!String.IsNullOrEmpty(aseguradoraTelefono)
                                                     ? aseguradoraTelefono + " - " + seguro.Contacto
                                                     : aseguradoraTelefono)
                                              : aseguradoraTelefono;

                    xrtblCellCompaniaAseguradora.Text = !String.IsNullOrEmpty(aseguradoraTelefono)
                                                            ? aseguradoraTelefono
                                                            : String.Empty;
                    xrlblNumeroPoliza.Text = seguro.NumeroPoliza ?? String.Empty;
                    xrlblCompania.Text     = seguro.Aseguradora ?? String.Empty;
                }

                LineaContratoRDBO lineaTemp = contrato.ObtenerLineaContrato();
                if (lineaTemp.Equipo.ActivoFijo.CostoSinIva == null)
                {
                    leyendaSeguro = leyendaSeguro.Replace("{MONTODEDUCIBLE}", "__________");
                }
                else
                {
                    Decimal?montoDeducibleCalcuado = 0;
                    montoDeducibleCalcuado = lineaTemp.Equipo.ActivoFijo.CostoSinIva;
                    var unidad = (UnidadBO)lineaTemp.Equipo;
                    if (unidad.EquiposAliados.Count > 0)
                    {
                        montoDeducibleCalcuado = unidad.EquiposAliados.Aggregate(montoDeducibleCalcuado, (monto, equipoAliado) => equipoAliado.ActivoFijo != null ? equipoAliado.ActivoFijo.CostoSinIva != null ? monto + equipoAliado.ActivoFijo.CostoSinIva : monto : monto);
                    }
                    //SC0021 formato de decimales
                    leyendaSeguro = leyendaSeguro.Replace("{MONTODEDUCIBLE}", String.Format("{0:#,##0.00##}", contrato.CalcularMontoDeducible((Decimal)montoDeducibleCalcuado).Value));
                }
                xrlblLeyendaSeguro.Html = leyendaSeguro;

                xrlblFirmaUnidadOperativa.Text         = matriz.UnidadOperativa.Nombre;
                xrlblRepresentanteUnidadOperativa.Text = unidadOperativaConfiguracion.Representante;
                xrlblTelefonoUnidadOperativa.Text      = telefonoUO;
                xrlblDireccionUnidadOperativa.Text     = direccionUO;
                if (contrato.Cliente.EsFisico == null || contrato.Cliente.EsFisico == true)
                {
                    RepresentanteLegalBO representante;
                    if (firmantes.Item2 == null)
                    {
                        representante = new RepresentanteLegalBO();
                    }
                    else
                    {
                        representante = (RepresentanteLegalBO)firmantes.Item2[0];
                    }
                    string cliente = representante.Nombre;
                    cliente = !String.IsNullOrEmpty(representante.Telefono)
                                  ? cliente + "/n" + representante.Telefono
                                  : cliente;
                    cliente = !String.IsNullOrEmpty(representante.Direccion)
                                  ? cliente + "/n" + representante.Direccion
                                  : cliente;
                    xrlblDatosClienteMoral.Text = cliente;

                    xrSubreport3.Visible = false;
                }
                if (contrato.Cliente.EsFisico == false)
                {
                    xrlblDatosClienteMoral.BorderWidth = 0;
                    string clienteMoral = contrato.Cliente.Nombre;
                    var    direccion    = contrato.Cliente.Direcciones.Find(p => p.Primaria != null && p.Primaria.Value);

                    if (direccion != null)
                    {
                        if (!String.IsNullOrWhiteSpace(direccion.Telefono) && !String.IsNullOrEmpty(direccion.Telefono))
                        {
                            clienteMoral = clienteMoral + "\n" + direccion.Telefono;
                        }
                    }
                    clienteMoral = clienteMoral + "\n" + contrato.Cliente.Direccion;
                    xrlblDatosClienteMoral.Text = clienteMoral;
                    if (firmantes.Item2 != null)
                    {
                        firmantes.Item2.ForEach(r => r.Telefono = null);
                        xrSubreport3.ReportSource.DataSource    = firmantes.Item2.ConvertAll(r => (RepresentanteLegalBO)r);
                    }
                    else
                    {
                        xrSubreport3.Visible = false;
                    }
                }

                #endregion
                #region Seccion Derecha

                xrlblFecha.Text = contrato.FechaContrato != null
                                      ? contrato.FechaContrato.Value.ToShortDateString()
                                      : String.Empty;

                xrlblFechaPromesaDevolucion.Text = contrato.FechaPromesaDevolucion != null
                                                       ? contrato.FechaPromesaDevolucion.Value.ToShortDateString()
                                                       : String.Empty;

                xrlblModelo.Text = lineaTemp.Equipo.Modelo.Nombre ?? String.Empty;
                xrtblCellNumeroEconomico.Text = ((UnidadBO)lineaTemp.Equipo).NumeroEconomico ?? String.Empty;
                xrtblCellNumeroSerie.Text     = lineaTemp.Equipo.NumeroSerie ?? String.Empty;
                xrtblCellNumeroPlaca.Text     = numeroPlaca;
                //SC0021 formato de decimales
                xrtblCellPBC.Text = ((UnidadBO)lineaTemp.Equipo).CaracteristicasUnidad.PBCMaximoRecomendado != null
                                        ? String.Format("{0:#,##0.00##}", ((UnidadBO)lineaTemp.Equipo).CaracteristicasUnidad.PBCMaximoRecomendado)
                                        : String.Empty;

                xrlblTipo.Text = lineaTemp.Equipo.TipoEquipoServicio.Nombre ?? String.Empty;
                xrSubreport1.ReportSource.DataSource = ((UnidadBO)linea.Equipo).EquiposAliados;
                //xrlblModeloEquipoAliado.DataBindings.Add(new XRBinding("Text", (((UnidadBO)linea.Equipo).EquiposAliados), "Modelo.Nombre"));
                //xrlblSerieEquipoAliado.DataBindings.Add(new XRBinding("Text", (((UnidadBO)linea.Equipo).EquiposAliados), "NumeroSerie"));


                if (lineaTemp.Equipo.EquipoID != null)
                {
                    xrtblCellFechaDevolucion.Text = contrato.ObtenerFechaDevolucion((UnidadBO)lineaTemp.Equipo) != null
                                                        ? contrato.ObtenerFechaDevolucion((UnidadBO)lineaTemp.Equipo)
                                                    .Value.ToString()
                                                        : String.Empty;

                    xrtblCellFechaSalida.Text = contrato.ObtenerFechaEntrega((UnidadBO)lineaTemp.Equipo) != null
                                                    ? contrato.ObtenerFechaEntrega((UnidadBO)lineaTemp.Equipo)
                                                .Value.ToString()
                                                    : String.Empty;

                    xrtblCellKmTotal.Text = contrato.CalcularKilometrajeRecorrido((UnidadBO)lineaTemp.Equipo) != null
                                            ? String.Format("{0:#,##0}", contrato.CalcularKilometrajeRecorrido((UnidadBO)lineaTemp.Equipo))
                                            : String.Empty;

                    xrlblCargoKilometro.Text =
                        ((TarifaContratoRDBO)lineaTemp.Cobrable).RangoTarifas.First().CargoKm != null
                                              ? "$ " + String.Format("{0:#,##0.00##}", ((TarifaContratoRDBO)lineaTemp.Cobrable).RangoTarifas.First().CargoKm)
                                              : "$";


                    xrtblCellTotalEquipoAliado.Text = contrato.CalcularHorasConsumidas((UnidadBO)lineaTemp.Equipo) != null
                                                          ? String.Format("{0:#,##0}", contrato.CalcularHorasConsumidas((UnidadBO)lineaTemp.Equipo))
                                                          : String.Empty;
                }
                else
                {
                    xrtblCellFechaDevolucion.Text   = String.Empty;
                    xrtblCellFechaSalida.Text       = String.Empty;
                    xrtblCellKmTotal.Text           = String.Empty;
                    xrlblCargoKilometro.Text        = "$";
                    xrtblCellTotalEquipoAliado.Text = String.Empty;
                }
                xrtblCellDias.Text = contrato.CalcularDiasTranscurridosRenta() != null
                                         ? String.Format("{0:#,##0}", contrato.CalcularDiasTranscurridosRenta())
                                         : String.Empty;

                xrtblCellHoras.Text = contrato.CalcularHorasTranscurridasRenta() != null
                                          ? String.Format("{0:#,##0.00##}", contrato.CalcularHorasTranscurridasRenta())
                                          : String.Empty;

                if (contrato.LectorKilometraje == ELectorKilometraje.HUBODOMETRO)
                {
                    xrchkHubodometro.Checked = true;
                }
                if (contrato.LectorKilometraje == ELectorKilometraje.ODOMETRO)
                {
                    xrchkOdometro.Checked = true;
                }
                ListadoVerificacionBO listadoEntrada =
                    lineaTemp.ListadosVerificacion.Find(l => l.Tipo == ETipoListadoVerificacion.RECEPCION);
                if (listadoEntrada == null)
                {
                    xrtblCellKmEntrada.Text = String.Empty;
                    xrtblCellHrEntrada.Text = String.Empty;
                }
                else
                {
                    xrtblCellKmEntrada.Text = listadoEntrada.Kilometraje != null
                                                  ? String.Format("{0:#,##0}", listadoEntrada.Kilometraje)
                                                  : String.Empty;

                    xrtblCellHrEntrada.Text = listadoEntrada.Horometro != null
                                                  ? String.Format("{0:#,##0}", listadoEntrada.Horometro)
                                                  : String.Empty;
                }
                ListadoVerificacionBO listadoSalida =
                    lineaTemp.ListadosVerificacion.Find(l => l.Tipo == ETipoListadoVerificacion.ENTREGA);
                if (listadoSalida == null)
                {
                    xrtblCellKmSalida.Text = String.Empty;
                    xrtblCellHrSalida.Text = String.Empty;
                }
                else
                {
                    xrtblCellKmSalida.Text = listadoSalida.Kilometraje != null
                                                 ? String.Format("{0:#,##0}", listadoSalida.Kilometraje)
                                                 : String.Empty;

                    xrtblCellHrSalida.Text = listadoSalida.Horometro != null
                                                 ? String.Format("{0:#,##0}", listadoSalida.Horometro)
                                                 : String.Empty;
                }

                //SC0021 formato de decimales
                var tarifaContrato = lineaTemp.Cobrable != null ? lineaTemp.Cobrable as TarifaContratoRDBO : new TarifaContratoRDBO();
                xrlblTarifaDiaria.Text = tarifaContrato.TarifaDiaria != null
                                                 ? "$ " + String.Format("{0:#,##0.00##}", tarifaContrato.TarifaDiaria)
                                                 : "$";

                xrlblTarifaHora.Text = tarifaContrato.RangoTarifas != null && tarifaContrato.RangoTarifas.Any() && tarifaContrato.RangoTarifas.First().CargoHr != null
                                               ? "$ " + String.Format("{0:#,##0.00##}", tarifaContrato.RangoTarifas.First().CargoHr)
                                               : "$";
                if (unidadOperativaConfiguracion.PrecioUnidadCombustible == null)
                {
                    xrtblCellLitro.Text = "";
                }

                xrtblCellPrecioLitro.Text = unidadOperativaConfiguracion.PrecioUnidadCombustible != null
                                                ? "$ " + String.Format("{0:#,##0.00##}", unidadOperativaConfiguracion.PrecioUnidadCombustible)
                                                : "$";

                string descripcion = string.Empty;
                if (contrato.FormaPago != null)
                {
                    FieldInfo fi = contrato.FormaPago.GetType().GetField(contrato.FormaPago.ToString());

                    DescriptionAttribute[] attributes =
                        (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                    if (attributes != null &&
                        attributes.Length > 0)
                    {
                        descripcion = attributes[0].Description;
                    }
                    else
                    {
                        descripcion = contrato.FormaPago.ToString();
                    }
                }
                if (contrato.TipoConfirmacion != null)
                {
                    FieldInfo fi = contrato.TipoConfirmacion.GetType().GetField(contrato.TipoConfirmacion.ToString());

                    DescriptionAttribute[] attributes =
                        (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                    if (attributes != null &&
                        attributes.Length > 0)
                    {
                        descripcion = !String.IsNullOrEmpty(descripcion)
                                          ? descripcion + " - " + attributes[0].Description
                                          : attributes[0].Description;
                    }
                    else
                    {
                        descripcion = !String.IsNullOrEmpty(descripcion)
                                          ? descripcion + " - " + contrato.TipoConfirmacion.ToString()
                                          : contrato.TipoConfirmacion.ToString();
                    }
                }

                this.xrtblCellCreditoAprobadoPor.Text = !string.IsNullOrEmpty(contrato.AutorizadorTipoConfirmacion) &&
                                                        !string.IsNullOrWhiteSpace(contrato.AutorizadorTipoConfirmacion)
                                                            ? contrato.AutorizadorTipoConfirmacion.Trim().ToUpper()
                                                            : string.Empty;

                xrtblCellTipoConfirmacion.Text = descripcion;

                if (contrato.FormaPago != null)
                {
                    xrchkDeposito.Checked = true;
                    if (lineaTemp.Equipo.ActivoFijo.CostoSinIva == null)
                    {
                        xrtblCellDepositoRecibido.Text = "$";
                    }
                    else
                    {
                        Decimal?montoDeducibleCalcuado = 0;
                        montoDeducibleCalcuado = lineaTemp.Equipo.ActivoFijo.CostoSinIva;
                        var unidad = (UnidadBO)lineaTemp.Equipo;
                        if (unidad.EquiposAliados.Count > 0)
                        {
                            montoDeducibleCalcuado = unidad.EquiposAliados.Aggregate(montoDeducibleCalcuado, (monto, equipoAliado) => equipoAliado.ActivoFijo != null ? equipoAliado.ActivoFijo.CostoSinIva != null ? monto + equipoAliado.ActivoFijo.CostoSinIva : monto : monto);
                        }
                        //SC0021 formato de decimales
                        xrtblCellDepositoRecibido.Text =
                            contrato.CalcularMontoDeposito((Decimal)montoDeducibleCalcuado) != null
                                ? "$" +
                            String.Format("{0:#,##0.00##}", contrato.CalcularMontoDeposito((Decimal)montoDeducibleCalcuado))
                                : "$";
                    }
                }
                if (contrato.TipoConfirmacion != null && contrato.TipoConfirmacion == ETipoConfirmacion.ORDEN_DE_COMPRA)
                {
                    xrchkDeposito.Checked          = false;
                    xrtblCellDepositoRecibido.Text = "$0.00";
                }
                xrtblCellPreparadoPor.Text  = usuarioCreacion.Nombre ?? String.Empty;
                xrtblCellCompletadoPor.Text = usuarioCierre.Nombre ?? String.Empty;

                #region CU011 – Imprimir Cierre de Contrato de Renta Diaria

                //se obtiene los datos de finalizacion del contrato
                object             finalizacion   = contrato.ObtenerFinalizacionContratoRD();
                CierreContratoRDBO cierreContrato = null;
                if (finalizacion != null && typeof(CierreContratoRDBO) == finalizacion.GetType() && lineaTemp != null)
                {
                    cierreContrato = (CierreContratoRDBO)finalizacion;
                }

                if (cierreContrato != null)
                {
                    // se realizan los calculos
                    decimal?importeRenta       = contrato.CalcularDiasTranscurridosRenta() * ((TarifaContratoRDBO)lineaTemp.Cobrable).TarifaDiaria;
                    decimal?importeKmAdicional = contrato.CalcularMontoPorKilometrosExcedidos((UnidadBO)lineaTemp.Equipo);
                    decimal?importeHrAdicional = contrato.CalcularMontoPorHorasExcedidas((UnidadBO)lineaTemp.Equipo);
                    decimal?subtotalTarifa     = importeRenta + importeKmAdicional + importeHrAdicional;
                    int?    litrosUnidad       = contrato.CalcularDiferenciaCombustible();
                    decimal?importeLitros      = contrato.CalcularMontoPorCombustible(unidadOperativaConfiguracion.PrecioUnidadCombustible);
                    decimal?subtotalCargos     = unidadOperativaConfiguracion.PrecioUnidadCombustible.HasValue ? contrato.CalcularSubTotalCargos(unidadOperativaConfiguracion.PrecioUnidadCombustible.Value) : null;
                    decimal?importeSinIva      = subtotalTarifa + subtotalCargos;
                    decimal?importeDelIva      = (importeSinIva * (contrato.Sucursal.Impuesto != null ? contrato.Sucursal.Impuesto.PorcentajeImpuesto : null)) / 100;
                    decimal?cargoNeto          = importeSinIva + importeDelIva;
                    //decimal? montoDeposito = contrato.CalcularMontoDeposito(lineaTemp.Equipo.ActivoFijo.CostoSinIva.Value);
                    decimal?totalPagar = cargoNeto;

                    // se asignan valores a los campos del reporte
                    xrtblCellTarifaDiaria.Text   = importeRenta != null ? "$ " + String.Format("{0:#,##0.00##}", importeRenta) : string.Empty;
                    xrtblCellCargoKilometro.Text = importeKmAdicional != null ? "$ " + String.Format("{0:#,##0.00##}", importeKmAdicional) : string.Empty;
                    xrtblCellTarifaHora.Text     = importeHrAdicional != null ? "$ " + String.Format("{0:#,##0.00##}", importeHrAdicional) : string.Empty;
                    xrtblCellSubtotalTarifa.Text = subtotalTarifa != null ? "$ " + String.Format("{0:#,##0.00##}", subtotalTarifa) : string.Empty;
                    xrtblCellLitros.Text         = litrosUnidad != null?String.Format("{0:#,##0.00##}", litrosUnidad) : string.Empty;

                    xrtblCellImporteLitros.Text       = importeLitros != null ? "$ " + String.Format("{0:#,##0.00##}", importeLitros) : string.Empty;
                    xrtblCellCargoAbuso.Text          = cierreContrato.CargoAbusoOperacion != null ? "$ " + String.Format("{0:#,##0.00##}", cierreContrato.CargoAbusoOperacion) : string.Empty;
                    xrtblCellCargoBasura.Text         = cierreContrato.CargoDisposicionBasura != null ? "$ " + String.Format("{0:#,##0.00##}", cierreContrato.CargoDisposicionBasura) : string.Empty;
                    xrtblCellSubtotalCargos.Text      = subtotalCargos != null ? "$ " + String.Format("{0:#,##0.00##}", subtotalCargos) : string.Empty;
                    xrtblCellPorcentajeIva.Text       = contrato.Sucursal.Impuesto.PorcentajeImpuesto.HasValue ? contrato.Sucursal.Impuesto.PorcentajeImpuesto.Value.ToString() + " %" : string.Empty;
                    xrtblCellCargoNeto.Text           = cargoNeto != null ? "$ " + String.Format("{0:#,##0.00##}", cargoNeto) : string.Empty;
                    xrtblCellRembolso.Text            = cierreContrato.ImporteReembolso != null ? "$ " + String.Format("{0:#,##0.00##}", cierreContrato.ImporteReembolso) : string.Empty;
                    xrtblCellTotalPagar.Text          = totalPagar != null ? "$ " + String.Format("{0:#,##0.00##}", totalPagar) : string.Empty;
                    xrtblCellRembolsoRecibidoPor.Text = cierreContrato.PersonaRecibeReembolso;
                    xrtblCellImporteIVA.Text          = importeDelIva != null ? "$ " + String.Format("{0:#,##0.00##}", importeDelIva) : string.Empty;
                }
                #endregion
                #endregion
                #region Pie de Reporte
                xrlblLeyendaArrendatarios.Html = leyendaArrendatarios;
                xrlblLeyendaOperacion.Html     = leyendaOperacion;
                xrlblLeyendaInspeccion.Html    = leyendaInspeccion;
                xrlblNumeroCheckList.Text      = contrato.CalcularNumeroListadoVerificacion() ?? String.Empty;
                #endregion
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("ContratoRentaDiariaRPT.ImprimirReporte:Error al intentar generar el reporte." + ex.Message);
            }
        }
Exemple #11
0
        /// <summary>
        /// 获取枚举的中文描述
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>没有描述返回空字符串</returns>
        public static string GetDescription(this System.Enum obj)
        {
            string objName = obj.ToString();
            Type   t       = obj.GetType();

            System.Reflection.FieldInfo fi = t.GetField(objName);
            System.ComponentModel.DescriptionAttribute[] arrDesc = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            if (arrDesc.Length > 0)
            {
                return(arrDesc[0].Description);
            }
            return("");
        }
        static private string getConfigValue(System.Reflection.FieldInfo fieldInfo, ConfigTable table, ConfigRow configRow)
        {
            string[] columnNames = getDescriptionNames(fieldInfo);

            if (columnNames != null)
            {
                string configValue = string.Empty;

                int columnNamesLength = columnNames.Length;
                for (int i = 0; i < columnNamesLength; i++)
                {
                    if (i > 0)
                    {
                        configValue += SEPARATOR;
                    }

                    string columnName  = columnNames[i];
                    int    columnIndex = 0;
                    string cellValue   = "";

                    ListAttribute[] attributes = (ListAttribute[])fieldInfo.GetCustomAttributes(typeof(ListAttribute), false);
                    if (attributes.Length > 0)
                    {
                        //如果是多欄位要合成list 就執行這邊
                        string columnNameTemp = columnName + 0;
                        columnIndex = table.getColumnIndex(columnNameTemp);
                        if (columnIndex != -1)
                        {
                            cellValue = configRow.getStringValue(columnIndex);
                            if (!string.IsNullOrEmpty(cellValue))
                            {
                                configValue = cellValue;
                            }
                        }

                        for (int j = 1; j < 100; j++)
                        {
                            columnNameTemp = columnName + j;
                            columnIndex    = table.getColumnIndex(columnNameTemp);
                            if (columnIndex != -1)
                            {
                                cellValue = configRow.getStringValue(columnIndex);
                                if (!string.IsNullOrEmpty(cellValue))
                                {
                                    configValue = configValue + ":" + cellValue;
                                }
                            }
                        }
                    }
                    else
                    {
                        columnIndex  = table.getColumnIndex(columnName);
                        cellValue    = configRow.getStringValue(columnIndex);
                        configValue += cellValue;
                    }
                }

                return(configValue);
            }

            return(null);
        }
Exemple #13
0
 /// <summary>
 /// Search for and return the all attributes of the specified attribute type attached to the provided type field.
 /// </summary>
 /// <typeparam name="TAttribute">The attribute type to be searched for.</typeparam>
 /// <param name="field">The type field which may have attributes attached to it.</param>
 /// <returns>An array of all instances of attributes of the specified type attached to the type field, or an empty array if no matching attribute was found.</returns>
 public static TAttribute[] GetAttributes <TAttribute>(System.Reflection.FieldInfo field) where TAttribute : System.Attribute
 {
     return(GetAttributes <TAttribute>(field.GetCustomAttributes(true)));
 }
 public static Oranikle.Studio.Controls.EnumDisplay[] GetEnumDisplayList(System.Type enumType)
 {
     System.Collections.Generic.List <Oranikle.Studio.Controls.EnumDisplay> list = new System.Collections.Generic.List <Oranikle.Studio.Controls.EnumDisplay>();
     foreach (object obj in System.Enum.GetValues(enumType))
     {
         System.Reflection.FieldInfo fieldInfo = enumType.GetField(obj.ToString());
         System.ComponentModel.DescriptionAttribute[] descriptionAttributeArr = fieldInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true) as System.ComponentModel.DescriptionAttribute[];
         if (descriptionAttributeArr.Length > 0)
         {
             list.Add(new Oranikle.Studio.Controls.EnumDisplay(enumType, obj, descriptionAttributeArr[0]));
         }
     }
     return(list.ToArray());
 }
Exemple #15
0
        public static string stringValueOf(Enum value)
        {
            System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
            System.ComponentModel.DescriptionAttribute[] attributes = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return(attributes[0].Description);
            }
            else
            {
                return(value.ToString());
            }
        }
        public CustomPropertyDescriptor(Type insType, System.Reflection.FieldInfo field, bool parentIsValueType)
        {
            Fields[insType] = field;
            Name            = field.Name;
            var disNameAtt = field.GetCustomAttributes(typeof(DisplayNameAttribute), true);

            if (disNameAtt != null && disNameAtt.Length > 0)
            {
                mDisplayName = ((DisplayNameAttribute)disNameAtt[0]).DisplayName;
            }
            mPropertyType = field.FieldType;
            var browsableAtt = field.GetCustomAttributes(typeof(BrowsableAttribute), true);

            if (browsableAtt != null && browsableAtt.Length > 0)
            {
                IsBrowsable = ((BrowsableAttribute)browsableAtt[0]).Browsable;
            }
            else
            {
                IsBrowsable = true;
            }
            var atts = field.GetCustomAttributes(true);

            Attribute[] tAtts = new Attribute[atts.Length];
            for (int i = 0; i < atts.Length; i++)
            {
                tAtts[i] = atts[i] as Attribute;
            }
            Attributes = new AttributeCollection(tAtts);
            var desAtt = field.GetCustomAttributes(typeof(DescriptionAttribute), true);

            if (desAtt != null && desAtt.Length > 0)
            {
                Description = ((DescriptionAttribute)desAtt[0]).Description;
            }
            else
            {
                var MacrossType = field.GetCustomAttributes(typeof(EngineNS.Editor.Editor_RNameMacrossType), true);
                if (MacrossType.Length > 0)
                {
                    Description = ((EngineNS.Editor.Editor_RNameMacrossType)MacrossType[0]).MacrossBaseType.FullName;
                }
            }
            var readOnlyAtt = field.GetCustomAttributes(typeof(ReadOnlyAttribute), true);

            if (readOnlyAtt != null && readOnlyAtt.Length > 0)
            {
                mIsReadOnly = ((ReadOnlyAttribute)readOnlyAtt[0]).IsReadOnly;
            }
            var categoryAtt = field.GetCustomAttributes(typeof(CategoryAttribute), true);

            if (categoryAtt != null && categoryAtt.Length > 0)
            {
                Category = ((CategoryAttribute)categoryAtt[0]).Category;
            }
            else
            {
                Category = "杂项";
            }
            var notifyAtt = field.GetCustomAttributes(typeof(EngineNS.Editor.Editor_NotifyMemberValueChangedAttribute), true);

            if (notifyAtt != null && notifyAtt.Length > 0)
            {
                IsNotifyValueChange = true;
            }
            var converAtts = field.FieldType.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), true);

            if (converAtts != null && converAtts.Length > 0)
            {
                var  convertName = ((System.ComponentModel.TypeConverterAttribute)converAtts[0]).ConverterTypeName;
                Type converType  = null;
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    converType = assembly.GetType(convertName);
                    if (converType != null)
                    {
                        break;
                    }
                }
                Converter = System.Activator.CreateInstance(converType) as TypeConverter;
            }

            if (parentIsValueType)
            {
                ParentIsValueType = parentIsValueType;
            }
            else
            {
                ParentIsValueType = insType.IsValueType;
            }
        }
Exemple #17
0
        public static Result DrawGUI(Rect position, GUIContent label, System.Reflection.FieldInfo field, Resource value, bool hasMultipleDifferentValues)
        {
            var result = new Result()
            {
                resource = value,
                changed  = false
            };

            var requiredType = UnityEngine.UI.Windows.Utilities.RequiredType.None;
            var type         = typeof(Object);

            if (field != null)
            {
                var attrs = field.GetCustomAttributes(typeof(ResourceTypeAttribute), inherit: false);
                if (attrs.Length > 0)
                {
                    var attr = (ResourceTypeAttribute)attrs[0];
                    type         = attr.type;
                    requiredType = attr.required;
                }
            }

            var labelSize = 40f;

            var objRect = position;

            objRect.width -= labelSize;

            var labelPadding = 3f;
            var labelRect    = position;

            labelRect.x      += position.width - labelSize + labelPadding;
            labelRect.width   = labelSize - labelPadding * 2f;
            labelRect.y      += labelPadding;
            labelRect.height -= labelPadding * 2f;

            var obj      = Resource.GetEditorRef(value.guid, value.subObjectName, type, value.objectType, value.directRef);
            var oldValue = EditorGUI.showMixedValue;

            EditorGUI.showMixedValue = hasMultipleDifferentValues;
            var newObj = EditorGUI.ObjectField(objRect, label, obj, type, allowSceneObjects: true);

            EditorGUI.showMixedValue = oldValue;
            if (newObj == null)
            {
                WindowSystemRequiredReferenceDrawer.DrawRequired(objRect, requiredType);
            }
            if (newObj != obj)
            {
                result.changed = true;
                {
                    var assetPath = AssetDatabase.GetAssetPath(newObj);
                    result.resource.guid          = AssetDatabase.AssetPathToGUID(assetPath);
                    result.resource.subObjectName = (newObj != null && AssetDatabase.IsSubAsset(newObj) == true ? AssetDatabase.LoadAllAssetsAtPath(assetPath).FirstOrDefault(x => x.name == newObj.name).name : string.Empty);
                }

                if (newObj != null)
                {
                    // Apply objectType
                    var val = 0;
                    switch (newObj)
                    {
                    case GameObject objType:
                        val = (int)Resource.ObjectType.GameObject;
                        break;

                    case Component objType:
                        val = (int)Resource.ObjectType.Component;
                        break;

                    case ScriptableObject objType:
                        val = (int)Resource.ObjectType.ScriptableObject;
                        break;

                    case Sprite objType:
                        val = (int)Resource.ObjectType.Sprite;
                        break;

                    case Texture objType:
                        val = (int)Resource.ObjectType.Texture;
                        break;

                    default:
                        val = (int)Resource.ObjectType.Unknown;
                        break;
                    }
                    result.resource.objectType = (Resource.ObjectType)val;
                }

                if (newObj == null)
                {
                    result.resource.type      = Resource.Type.Manual;
                    result.resource.directRef = null;
                }
                else
                {
                    if (UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings.FindAssetEntry(result.resource.guid) != null)
                    {
                        //if (loadType.enumValueIndex != (int)Resource.Type.Addressables)
                        {
                            // addressables
                            {
                                result.resource.type      = Resource.Type.Addressables; //AssetDatabase.AssetPathToGUID(assetPath);
                                result.resource.directRef = null;
                                newObj.SetAddressableID(result.resource.guid);
                            }
                        }
                    }
                    else
                    {
                        //if (loadType.enumValueIndex != (int)Resource.Type.Direct)
                        {
                            // direct
                            {
                                result.resource.type      = Resource.Type.Direct;
                                result.resource.directRef = newObj;
                            }
                        }
                    }
                }
            }

            var tooltip = "This object will be stored through GUID link.";

            if (newObj != null)
            {
                var typeRect = labelRect;
                //typeRect.x -= labelRect.width + labelPadding + 18f;
                var resType = result.resource.type;
                switch (resType)
                {
                case Resource.Type.Manual:
                    DrawLabel(typeRect, new GUIContent("MANL", tooltip + "\nResource type is Manual."), new Color(0.7f, 0.7f, 1f, 1f));
                    break;

                case Resource.Type.Direct:
                    DrawLabel(typeRect, new GUIContent("DRCT", tooltip + "\nResource type is Direct."), new Color(1f, 0.2f, 0.4f, 1f));
                    break;

                case Resource.Type.Addressables:
                    DrawLabel(typeRect, new GUIContent("ADDR", tooltip + "\nResource type is Addressable."), new Color(0.3f, 1f, 0.4f, 1f));
                    break;
                }
            }
            else
            {
                DrawLabel(labelRect, new GUIContent("GUID", tooltip), new Color(0.2f, 0.6f, 1f, 0.7f));
            }

            return(result);
        }
 static private string getTypeConverterName(System.Reflection.FieldInfo fieldInfo)
 {
     System.ComponentModel.TypeConverterAttribute[] attributes = (System.ComponentModel.TypeConverterAttribute[])fieldInfo.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false);
     return((attributes.Length > 0) ? attributes[0].ConverterTypeName : null);
 }
Exemple #19
0
        /// <summary>
        /// Returns some dashboard content that shows the background operations and their current status.
        /// </summary>
        /// <returns>The dashboard content.</returns>
        public IEnumerable <DashboardListItem> GetDashboardContent(TaskQueueResolver taskQueueResolver)
        {
            if (null == taskQueueResolver)
            {
                yield break;
            }

            foreach (var queue in taskQueueResolver.GetQueues())
            {
                // Sanity.
                if (string.IsNullOrWhiteSpace(queue))
                {
                    continue;
                }

                // Get information about the queues.
                TaskQueueAttribute          queueSettings = null;
                System.Reflection.FieldInfo fieldInfo     = null;
                try
                {
                    queueSettings = taskQueueResolver.GetQueueSettings(queue);
                    fieldInfo     = taskQueueResolver.GetQueueFieldInfo(queue);
                }
                catch
                {
                    // Throws if the queue is incorrect.
                    SysUtils.ReportToEventLog
                        ($"Cannot load details for queue {queue}; is there a static field with the [TaskQueue] attribute?",
                        System.Diagnostics.EventLogEntryType.Warning
                        );
                    continue;
                }


                // Skip anything broken.
                if (null == queueSettings || null == fieldInfo)
                {
                    continue;
                }

                // If it's marked as hidden then skip.
                {
                    var attributes = fieldInfo.GetCustomAttributes(typeof(HideOnDashboardAttribute), true)
                                     ?? new HideOnDashboardAttribute[0];
                    if (attributes.Length != 0)
                    {
                        continue;
                    }
                }

                // Get each task processor.
                foreach (var processor in taskQueueResolver.GetTaskProcessors(queue))
                {
                    // Sanity.
                    if (null == processor)
                    {
                        continue;
                    }

                    // Get information about the processor..
                    TaskProcessorAttribute       taskProcessorSettings = null;
                    System.Reflection.MethodInfo methodInfo            = null;
                    try
                    {
                        taskProcessorSettings = taskQueueResolver.GetTaskProcessorSettings(queue, processor.Type);
                        methodInfo            = taskQueueResolver.GetTaskProcessorMethodInfo(queue, processor.Type);
                    }
                    catch
                    {
                        // Throws if the task processor is not found.
                        SysUtils.ReportToEventLog
                        (
                            $"Cannot load processor details for task type {processor.Type} on queue {queue}.",
                            System.Diagnostics.EventLogEntryType.Warning
                        );
                        continue;
                    }


                    // Skip anything broken.
                    if (null == taskProcessorSettings || null == methodInfo)
                    {
                        continue;
                    }

                    // If it's marked as hidden then skip.
                    {
                        var attributes = methodInfo.GetCustomAttributes(typeof(HideOnDashboardAttribute), true)
                                         ?? new HideOnDashboardAttribute[0];
                        if (attributes.Length != 0)
                        {
                            continue;
                        }
                    }

                    // This should be shown.  Do we have any extended details?
                    var showOnDashboardAttribute = methodInfo.GetCustomAttributes(typeof(ShowOnDashboardAttribute), true)?
                                                   .FirstOrDefault() as ShowOnDashboardAttribute;

                    // Show the description?
                    var htmlString = "";
                    if (false == string.IsNullOrWhiteSpace(showOnDashboardAttribute?.Description))
                    {
                        htmlString += new DashboardCustomContent($"<p><em>{System.Security.SecurityElement.Escape(showOnDashboardAttribute?.Description)}</em></p>").ToXmlString();
                    }

                    // Does it have any configuration instructions?
                    IRecurrenceConfiguration recurrenceConfiguration = null;
                    if (this
                        .VaultApplication?
                        .RecurringOperationConfigurationManager?
                        .TryGetValue(queue, processor.Type, out recurrenceConfiguration) ?? false)
                    {
                        htmlString += recurrenceConfiguration.ToDashboardDisplayString();
                    }
                    else
                    {
                        htmlString += "<p>Does not repeat.<br /></p>";
                    }

                    // Get known executions (prior, running and future).
                    var executions = this
                                     .GetAllExecutions <TaskDirective>(queue, processor.Type)
                                     .ToList();
                    var isRunning   = executions.Any(e => e.State == MFilesAPI.MFTaskState.MFTaskStateInProgress);
                    var isScheduled = executions.Any(e => e.State == MFilesAPI.MFTaskState.MFTaskStateWaiting);

                    // Create the (basic) list item.
                    var listItem = new DashboardListItemWithNormalWhitespace()
                    {
                        Title         = showOnDashboardAttribute?.Name ?? processor.Type,
                        StatusSummary = new DomainStatusSummary()
                        {
                            Label = isRunning
                                                        ? "Running"
                                                        : isScheduled ? "Scheduled" : "Stopped"
                        }
                    };

                    // Should we show the run command?
                    {
                        var key = $"{queue}-{processor.Type}";
                        lock (this._lock)
                        {
                            if (this.TaskQueueRunCommands.ContainsKey(key))
                            {
                                var cmd = new DashboardDomainCommand
                                {
                                    DomainCommandID = this.TaskQueueRunCommands[key].ID,
                                    Title           = this.TaskQueueRunCommands[key].DisplayName,
                                    Style           = DashboardCommandStyle.Link
                                };
                                listItem.Commands.Add(cmd);
                            }
                        }
                    }

                    // Set the list item content.
                    listItem.InnerContent = new DashboardCustomContent
                                            (
                        htmlString
                        + executions?
                        .AsDashboardContent()?
                        .ToXmlString()
                                            );

                    // Add the list item.
                    yield return(listItem);
                }
            }
        }
        static public string[] getDescriptionNames(System.Reflection.FieldInfo fieldInfo)
        {
            System.ComponentModel.DescriptionAttribute[] attributes = (System.ComponentModel.DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                string   descriptionName = attributes[0].Description;
                string[] values          = ((string)descriptionName).Split(new char[] { SEPARATOR });

                return(values);
            }

            return(null);
        }
Exemple #21
0
 public static IEnumerable <LocalizerAttribute> GetLocalizedValues(this System.Reflection.FieldInfo info)
 => ((LocalizerAttribute[])info.GetCustomAttributes(typeof(LocalizerAttribute), false));
Exemple #22
0
        /// <summary>
        /// 增加告警到数据库
        /// </summary>
        /// <param name="lpszDbVarName"></param>
        /// <param name="lpszVal"></param>
        /// <param name="lpszdateTime"></param>
        /// <param name="errCode"></param>
        /// <param name="errTxt"></param>
        public static void DbAddAlarm(CommandVModel command, string lpszVal, DateTime lpszdateTime, AlarmType errCode, string errTxt, bool isSend)
        {
            DataProcessBLL bll        = new DataProcessBLL(command.Ledger, Config.Uid);
            StringBuilder  strContent = new StringBuilder();
            DataTable      dtSource   = bll.GetMapInfo(command.LpszDbVarName);
            int            ccc        = dtSource.Rows.Count;

            if (ccc == 0)
            {
                FileLog.WriteLog("告警模块变量:" + command.LpszDbVarName + "不存在映射表中");
                return;
            }
            if (ccc > 1)
            {
                FileLog.WriteLog("告警模块变量:" + command.LpszDbVarName + "在映射表中存在多个");
                return;
            }

            int    module_id  = CommFunc.ConvertDBNullToInt32(dtSource.Rows[0]["Module_id"]);
            int    co_id      = CommFunc.ConvertDBNullToInt32(dtSource.Rows[0]["Co_id"]);
            int    fun_id     = CommFunc.ConvertDBNullToInt32(dtSource.Rows[0]["Fun_id"]);
            string moduleAddr = CommFunc.ConvertDBNullToString(dtSource.Rows[0]["ModuleAddr"]);
            string funType    = CommFunc.ConvertDBNullToString(dtSource.Rows[0]["FunType"]);

            if (funType.Equals(V0Fun.LeakAlarm.ToString()))
            {
                if (lpszVal.Substring(0, 12).Contains("1"))
                {
                    int cnt = 0;
                    foreach (char c in lpszVal.Substring(0, 12).ToCharArray())
                    {
                        string content = "";
                        ++cnt;
                        if (c.ToString().Equals("1"))
                        {
                            if (cnt <= 8)
                            {
                                content = "漏电流" + cnt + "发生告警";
                            }
                            else
                            {
                                content = "温度" + (cnt - 8) + "发生告警";
                            }
                        }
                        if (!string.IsNullOrEmpty(content))
                        {
                            if (!string.IsNullOrEmpty(strContent.ToString()))
                            {
                                strContent.Append(";");
                            }
                            strContent.Append(content);
                        }
                    }
                }
            }
            else
            {
                string content = "";
                System.Reflection.FieldInfo info = typeof(V0Fun).GetField(funType);
                if (info != null)
                {
                    var obj = info.GetCustomAttributes(typeof(DisplayAttribute), false);
                    if (obj != null)
                    {
                        foreach (DisplayAttribute md in obj)
                        {
                            content = md.Name;
                        }
                    }
                }
                strContent.Append(content);
            }
            long log_id = bll.AddAlarm(co_id, module_id, moduleAddr, errCode.ToString(), fun_id, strContent.ToString(), lpszVal, lpszdateTime, (int)errCode, errTxt);

            if (isSend == true)
            {/*发送告警*/
                SendHd(command.Ledger, log_id, errCode, HdType.AL_Sms, errTxt, module_id);
                SendHd(command.Ledger, log_id, errCode, HdType.AL_Email, errTxt, module_id);
            }
        }
Exemple #23
0
        private string GetYdCollectOnExport(string jsonDataTable)
        {
            string fn       = "/XTemp/采集历史报表.xls";
            string filePath = System.Web.HttpContext.Current.Server.MapPath(@"/XTemp");

            if (System.IO.Directory.Exists(filePath) == false)
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            string filename = System.Web.HttpContext.Current.Server.MapPath(fn);

            if (System.IO.File.Exists(filename))/*先删除已存在的文件,再汇出Excel*/
            {
                System.IO.File.Delete(filename);
            }
            DataTable dtSource = new DataTable();

            if (jsonDataTable.Length > 10)
            {
                dtSource = JsonHelper.ToDataTable(jsonDataTable);
            }
            string funType = dtSource.Rows.Count == 0 ? "" : funType = CommFunc.ConvertDBNullToString(dtSource.Rows[0]["FunType"]);
            string content = "";

            System.Reflection.FieldInfo info = typeof(V0Fun).GetField(funType);
            if (info != null)
            {
                var obj = info.GetCustomAttributes(typeof(Describe), false);
                if (obj != null)
                {
                    foreach (Describe md in obj)
                    {
                        content = md.describe;
                    }
                }
            }

            Excel.ExcelCellStyle columnCellStyle0 = new Excel.ExcelCellStyle();
            columnCellStyle0 = new Excel.ExcelCellStyle()
            {
                DataFormart         = "0.00",
                HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment.RIGHT
            };
            Excel.ExcelCellStyle columnCellStyle1 = new Excel.ExcelCellStyle();
            columnCellStyle1 = new Excel.ExcelCellStyle()
            {
                DataFormart = "yyyy-MM-dd HH:mm:ss",
            };
            Excel.ExcelColumnCollection columns = new Excel.ExcelColumnCollection();
            columns.Add(new Excel.ExcelColumn("序号", "RowId", 5)
            {
                IsSetWith = true
            });
            columns.Add(new Excel.ExcelColumn("建筑", "CoStrcName", 15)
            {
                IsSetWith = true
            });
            columns.Add(new Excel.ExcelColumn("房间", "CoName", 15)
            {
                IsSetWith = true
            });
            columns.Add(new Excel.ExcelColumn("电表地址", "ModuleAddr", 15)
            {
                IsSetWith = true
            });
            columns.Add(new Excel.ExcelColumn("采集时间", "TagTime", 20)
            {
                IsSetWith = true
            });
            columns.Add(new Excel.ExcelColumn("读数", "LastVal", 15)
            {
                IsSetWith = true
            });
            Excel.ExcelOparete excel = new Excel.ExcelOparete("采集历史报表");
            excel.SetObjectValue("采集历史报表" + (content == "" ? "" : ":" + content), 0, 0, 3);
            excel.SetColumnName(columns, 1, 0);
            excel.SetColumnValue(columns, dtSource.Select(), 2, 0);
            excel.SaveExcelByFullFileName(filename);
            return(fn);
        }
Exemple #24
0
        /// <summary>
        /// Overrides the method used to provide basic behaviour for selecting editor.
        /// Shows our custom control for editing the value.
        /// </summary>
        /// <param name="context">The context of the editing control</param>
        /// <param name="provider">A valid service provider</param>
        /// <param name="value">The current value of the object to edit</param>
        /// <returns>The new value of the object</returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context != null &&
                context.Instance != null &&
                provider != null)
            {
                edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

                if (edSvc != null)
                {
                    // Create a CheckedListBox and populate it with all the enum values
                    clb              = new CheckedListBox();
                    clb.BorderStyle  = BorderStyle.FixedSingle;
                    clb.CheckOnClick = true;
                    clb.MouseDown   += new MouseEventHandler(this.OnMouseDown);
                    clb.MouseMove   += new MouseEventHandler(this.OnMouseMoved);

                    tooltipControl            = new ToolTip();
                    tooltipControl.ShowAlways = true;

                    foreach (string name in Enum.GetNames(context.PropertyDescriptor.PropertyType))
                    {
                        // Get the enum value
                        object enumVal = Enum.Parse(context.PropertyDescriptor.PropertyType, name);
                        // Get the int value
                        int intVal = (int)Convert.ChangeType(enumVal, typeof(int));

                        // Get the description attribute for this field
                        System.Reflection.FieldInfo fi    = context.PropertyDescriptor.PropertyType.GetField(name);
                        DescriptionAttribute[]      attrs = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                        // Store the the description
                        string tooltip = attrs.Length > 0 ? attrs[0].Description : string.Empty;

                        // Get the int value of the current enum value (the one being edited)
                        int intEdited = (int)Convert.ChangeType(value, typeof(int));

                        // Creates a clbItem that stores the name, the int value and the tooltip
                        clbItem item = new clbItem(enumVal.ToString(), intVal, tooltip);

                        // Get the checkstate from the value being edited
                        bool checkedItem = (intEdited & intVal) > 0;

                        // Add the item with the right check state
                        clb.Items.Add(item, checkedItem);
                    }

                    // Show our CheckedListbox as a DropDownControl.
                    // This methods returns only when the dropdowncontrol is closed
                    edSvc.DropDownControl(clb);

                    // Get the sum of all checked flags
                    int result = 0;
                    foreach (clbItem obj in clb.CheckedItems)
                    {
                        result += obj.Value;
                    }

                    // return the right enum value corresponding to the result
                    return(Enum.ToObject(context.PropertyDescriptor.PropertyType, result));
                }
            }

            return(value);
        }
Exemple #25
0
 public static string GetString(Enum enValue)
 {
     System.Reflection.FieldInfo fiInfo  = enValue.GetType().GetField(enValue.ToString());
     DescriptionAttribute[]      daArray = fiInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
     return(daArray.Length > 0 ? daArray[0].Description : "");
 }
Exemple #26
0
 public static string GetDescription(object name)
 {
     System.Reflection.FieldInfo oFieldInfo = name.GetType().GetField(name.ToString());
     DescriptionAttribute[]      attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
     return(attributes.Length > 0 ? attributes[0].Description : name.ToString());
 }
Exemple #27
0
 private static string GetDescriptionOfEnum(MessageCode enums)
 {
     System.Reflection.FieldInfo fieldInfo             = enums.GetType().GetField(enums.ToString());
     DescriptionAttribute[]      descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
     return(descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : enums.ToString());
 }
Exemple #28
0
        /// <summary>
        /// Overrides the method used to provide basic behaviour for selecting editor.
        /// Shows our custom control for editing the value.
        /// </summary>
        /// <param name="context">The context of the editing control</param>
        /// <param name="provider">A valid service provider</param>
        /// <param name="value">The current value of the object to edit</param>
        /// <returns>The new value of the object</returns>
        public override object EditValue(ITypeDescriptorContext context,
                                         IServiceProvider provider, object value)
        {
            if (context != null && context.Instance != null && provider != null)
            {
                edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

                if (edSvc != null)
                {
                    // Create a ListBox and populate it with all the enum values
                    clb              = new ListBox();
                    clb.BorderStyle  = BorderStyle.FixedSingle;
                    clb.DrawMode     = System.Windows.Forms.DrawMode.OwnerDrawFixed;
                    clb.MeasureItem += new MeasureItemEventHandler(this.OnMeasureItem);
                    clb.DrawItem    += new DrawItemEventHandler(this.OnDrawItem);
                    clb.MouseDown   += new MouseEventHandler(this.OnMouseDown);
                    clb.MouseMove   += new MouseEventHandler(this.OnMouseMoved);
                    clb.DoubleClick += new EventHandler(this.OnDoubleClick);

                    tooltipControl            = new ToolTip();
                    tooltipControl.ShowAlways = true;

                    clb.BeginUpdate();
                    int iSelected = 0; // by default will be selected first item

                    foreach (string name in Enum.GetNames(context.PropertyDescriptor.PropertyType))
                    {
                        // Get the enum value
                        object enumVal = Enum.Parse(context.PropertyDescriptor.PropertyType, name);

                        // Get the int value
                        int intVal = (int)Convert.ChangeType(enumVal, typeof(int));

                        // Get the description attribute for this field
                        System.Reflection.FieldInfo fi    = context.PropertyDescriptor.PropertyType.GetField(name);
                        DescriptionAttribute[]      attrs = ( DescriptionAttribute[] )
                                                            fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                        // Store the the description
                        string tooltip = attrs.Length > 0 ? attrs[0].Description : string.Empty;

                        // Creates a clbItem that stores the name, the int value and the tooltip
                        clbItem item = new clbItem(enumVal.ToString(), intVal, tooltip);

                        // Add the item with the right check state
                        int index = clb.Items.Add(item);

                        // set selected item
                        if (intVal == (int)value)
                        {
                            iSelected = index;
                        }
                    }

                    clb.EndUpdate();
                    clb.SelectedIndex = iSelected;

                    // Show our CheckedListbox as a DropDownControl.
                    // This methods returns only when the dropdowncontrol is closed
                    edSvc.DropDownControl(clb);

                    // Get the sum of all checked flags
                    int result = ((clbItem)clb.SelectedItem).Value;

                    // return the right enum value corresponding to the result
                    return(Enum.ToObject(context.PropertyDescriptor.PropertyType, result));
                }
            }

            return(value);
        }
        /// <summary>
        /// 發送資料
        /// </summary>
        /// <param name="SendUrl">網址 <para></para> Ex:http://localhost:12345/AA/BB?TEST=123  http://localhost:12345/AA/BB</param>
        /// <param name="PostString">發送資料<para></para> TEST=123</param>
        /// <param name="methodType">發送形式</param>
        /// <param name="contentType">發送類別</param>
        /// <param name="sendEncoding">發送編碼</param>
        /// <param name="sendEncode">發送編碼型態</param>
        /// <param name="Authorization">發送Auth</param>
        /// <param name="encodingType">讀取編碼</param>
        /// <returns></returns>
        public ReturnResult ResponseData(InResponseData InValue)//string SendUrl, string PostString = "", MethodType methodType = MethodType.Get, ContentType contentType = ContentType.applicationxwwwformurlencoded, SendEncoding sendEncoding = SendEncoding.Default, string sendEncode = "utf-8", string Authorization = "", EncodingType encodingType = EncodingType.UTF8)
        {
            ReturnResult ReturnResult = new ReturnResult();

            string methodTypeVal  = "";
            string contentTypeVal = "";

            System.Reflection.FieldInfo fi         = InValue.sendmethodType.GetType().GetField(InValue.sendmethodType.ToString());
            EnumMemberAttribute[]       attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false);
            if (attributes.Length > 0)
            {
                methodTypeVal = attributes[0].Value;
            }

            fi         = InValue.sendcontentType.GetType().GetField(InValue.sendcontentType.ToString());
            attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false);
            if (attributes.Length > 0)
            {
                contentTypeVal = attributes[0].Value;
            }

            if (string.IsNullOrEmpty(methodTypeVal) || string.IsNullOrEmpty(contentTypeVal) || string.IsNullOrEmpty(InValue.reponencodingType.ToString()))
            {
                ReturnResult.ReturnMsgNo = -99;
                ReturnResult.ReturnMsg   = "選擇型別錯誤";
                ReturnResult.ErrorCode   = "SRP0001";
                return(ReturnResult);
            }

            if (string.IsNullOrEmpty(InValue.sendUrl))
            {
                ReturnResult.ReturnMsgNo = -98;
                ReturnResult.ReturnMsg   = "發送網址未填";
                ReturnResult.ErrorCode   = "SRP0002";
                return(ReturnResult);
            }

            try
            {
                HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(InValue.sendUrl.Trim());
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                if (string.IsNullOrEmpty(InValue.sendAuthorization).Equals(false))
                {
                    WebRequest.Headers.Add("Authorization", InValue.sendAuthorization);
                }

                switch (InValue.sendmethodType)
                {
                case SendMethodType.Get: WebRequest.Method = "GET"; break;

                case SendMethodType.Post:
                    byte[] parameterString = null;
                    switch (InValue.sendEncoding)
                    {
                    case SendEncoding.UTF8: parameterString = Encoding.UTF8.GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.ASCII: parameterString = Encoding.ASCII.GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.GetEncoding: parameterString = Encoding.GetEncoding(InValue.sendEncode).GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.Default: parameterString = Encoding.Default.GetBytes(InValue.sendPostString);
                        break;
                    }
                    WebRequest.Method = "POST";
                    switch (InValue.sendcontentType)
                    {
                    case SendContentType.applicationxwwwformurlencoded:
                        WebRequest.ContentType = "application/x-www-form-urlencoded";
                        break;

                    case SendContentType.textxml:
                        WebRequest.ContentType = "text/xml";
                        break;

                    case SendContentType.applicationjson:
                        WebRequest.ContentType = "application/json";
                        break;
                    }
                    WebRequest.ContentLength = parameterString.Length;
                    //等待要求逾時之前的毫秒數。預設值為 100,000 毫秒 (100 秒)。
                    Stream newStream = WebRequest.GetRequestStream();
                    newStream.Write(parameterString, 0, parameterString.Length);
                    newStream.Close();
                    break;
                }

                HttpWebResponse WebResponse = (HttpWebResponse)WebRequest.GetResponse();

                StreamReader sr;
                string       ReturnString = "";
                switch (InValue.reponencodingType)
                {
                case ReponEncodingType.Default:
                    sr           = new StreamReader(WebResponse.GetResponseStream(), Encoding.Default);
                    ReturnString = sr.ReadToEnd();
                    sr.Close();
                    break;

                case ReponEncodingType.UTF8:
                    sr           = new StreamReader(WebResponse.GetResponseStream(), Encoding.UTF8);
                    ReturnString = sr.ReadToEnd();
                    sr.Close();
                    break;
                }
                //Convert the stream to a string

                if (string.IsNullOrEmpty(ReturnString).Equals(false))
                {
                    ReturnString = ReturnString.Trim();
                }

                WebResponse.Close();
                ReturnResult.ReturnMsgNo = 1;
                ReturnResult.ReturnMsg   = ReturnString;
                ReturnResult.ErrorCode   = "SRP0000";
            }
            catch (Exception Ex)
            {
                ReturnResult.ReturnMsgNo = -999;
                ReturnResult.ReturnMsg   = "發生例外錯誤" + Ex.ToString();
                ReturnResult.ErrorCode   = "SRP0003";
            }
            return(ReturnResult);
        }