jueves, 28 de noviembre de 2019

Exportar Lista Objeto a Excel C#



public void ExportToExcel<T>(List<T> list)
    {
        int columnCount = 0;
        DateTime StartTime = DateTime.Now;
        StringBuilder rowData = new StringBuilder();
        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        rowData.Append("<Row ss:StyleID=\"s62\">");
        foreach (PropertyInfo p in properties)
        {
            if (p.PropertyType.Name != "EntityCollection`1" && p.PropertyType.Name != "EntityReference`1" && p.PropertyType.Name != p.Name)
            {
                columnCount++;
                rowData.Append("<Cell><Data ss:Type=\"String\">" + p.Name + "</Data></Cell>");
            }
            else
                break;
        }
        rowData.Append("</Row>");
        foreach (T item in list)
        {
            rowData.Append("<Row>");
            for (int x = 0; x < columnCount; x++) //each (PropertyInfo p in properties)
            {
                object o = properties[x].GetValue(item, null);
                string value = o == null ? "" : o.ToString();
                rowData.Append("<Cell><Data ss:Type=\"String\">" + value + "</Data></Cell>");
            }
            rowData.Append("</Row>");
        }
        var sheet = @"<?xml version=""1.0""?>
<?mso-application progid=""Excel.Sheet""?>
<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
xmlns:o=""urn:schemas-microsoft-com:office:office""
xmlns:x=""urn:schemas-microsoft-com:office:excel""
xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
xmlns:html=""http://www.w3.org/TR/REC-html40"">
<DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office"">
<Author>MSADMIN</Author>
<LastAuthor>MSADMIN</LastAuthor>
<Created>2011-07-12T23:40:11Z</Created>
<Company>Microsoft</Company>
<Version>12.00</Version>
</DocumentProperties>
<ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel"">
<WindowHeight>6600</WindowHeight>
<WindowWidth>12255</WindowWidth>
<WindowTopX>0</WindowTopX>
<WindowTopY>60</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID=""Default"" ss:Name=""Normal"">
<Alignment ss:Vertical=""Bottom""/>
<Borders/>
<Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID=""s62"">
<Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""
ss:Bold=""1""/>
</Style>
</Styles>
<Worksheet ss:Name=""Sheet1"">
<Table ss:ExpandedColumnCount=""" + (properties.Count() + 1) + @""" ss:ExpandedRowCount=""" + (list.Count() + 1) + @""" x:FullColumns=""1""
x:FullRows=""1"" ss:DefaultRowHeight=""15"">
" + rowData.ToString() + @"
</Table>
<WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
<PageSetup>
<Header x:Margin=""0.3""/>
<Footer x:Margin=""0.3""/>
<PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
</PageSetup>
<Print>
<ValidPrinterInfo/>
<HorizontalResolution>300</HorizontalResolution>
<VerticalResolution>300</VerticalResolution>
</Print>
<Selected/>
<Panes>
<Pane>
<Number>3</Number>
<ActiveCol>2</ActiveCol>
</Pane>
</Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
<Worksheet ss:Name=""Sheet2"">
<Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
x:FullRows=""1"" ss:DefaultRowHeight=""15"">
</Table>
<WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
<PageSetup>
<Header x:Margin=""0.3""/>
<Footer x:Margin=""0.3""/>
<PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
</PageSetup>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
<Worksheet ss:Name=""Sheet3"">
<Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
x:FullRows=""1"" ss:DefaultRowHeight=""15"">
</Table>
<WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
<PageSetup>
<Header x:Margin=""0.3""/>
<Footer x:Margin=""0.3""/>
<PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
</PageSetup>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>";
        System.Diagnostics.Debug.Print(StartTime.ToString() + " - " + DateTime.Now);
        System.Diagnostics.Debug.Print((DateTime.Now - StartTime).ToString());
        string attachment = "attachment; filename=Report.xml";
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.Write(sheet);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.End();
    }




USO DEL METODO:

  ExportToExcel(TuLista);

martes, 26 de noviembre de 2019

Llenar control DevExpress.XtraBars.BarEditItem (How to bind it to a data source)


public UCOpciones()
        {
            InitializeComponent();
            LISTAPARALLENARCOMBO dataAreaList = new LISTAPARALLENARCOMBO();
            KernelOperation.DataAreabynbAlias(LISTAPARALLENARCOMBO, Program.UserInfo.Username);      

            foreach(var empresa in LISTAPARALLENARCOMBO)
            {
                (barEditItemEmpresa.Edit as RepositoryItemComboBox).Items.Add(empresa.cveCia);
            }  
         //SELECCIONAR VALOR     
            barEditItemEmpresa.EditValue = Program.cveCiaCurrent == null ?  Program.UserInfo.CompanyCode : Program.cveCiaCurrent;
          
            Recargar();
        }

sábado, 23 de noviembre de 2019

El formulario especificado como MdiParent para este formulario no es un contenedor MdiContainer. Nombre del parámetro: value

Error:
El formulario especificado como MdiParent para este formulario no es un contenedor MdiContainer. Nombre del parámetro: value

Codigo:

Form2 frm2 = new Form2();
 frm2.MdiParent = this;
 frm2.Show();

Solucion:
Form2 form2 = new Form2();
form2.MdiParent = this.MdiParent;
form2.Show();

miércoles, 20 de noviembre de 2019

Validar conexión a Internet winforms

El siguiente código valida si tienes conexión a Internet

        public static bool InternetConnection()
        {
            try
            {
                System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry("www.google.com");

                return true;
            }
            catch
            {
                return false;
            }
        } 






































regresa true si se pudo conectar.

Error en switch "Se espera un valor constante"

Al trabajar con un switch y un enumerador me encontre con el siguiente error:

Error CS0150 Se espera un valor constante














Solución

Cambiar las variables estáticas a constantes:

Antes:

public static string NotificacionXCorreo = "navigationPageNotificacionXCorreo";

despues: Corregido

public const string NotificacionXCorreo = "navigationPageNotificacionXCorreo";


lunes, 18 de noviembre de 2019

Variables globales ASP.NET

Web Config

se puede guardar los datos en el Web.config en la zona de “appSettings”, esto lo haría de la siguiente forma:
Primero añadiendo una clave a la zona de appSettings en el Web.config
<appSettings>  
        <add key=”NombreVariable” value=”valor” />
</appSettings>
Y luego en el código de la página en la que lo necesitemos podemos obtener o modificar el valor de la clave mediante:
System.Configuration.ConfigurationSettings.AppSettings[“NombreVariable”] 
Otra manera:
Global.asax
En el archivo Global.asax. Este archivo permite manejar eventos que ocurren a nivel de la aplicación y de sesión, también nos permite declarar valores que necesitemos entre las diferentes solicitudes.
En el fichero Global.asax declaramos una variable string y luego en Session_Start otorgamos el valor de la cadena a un objeto de tipo Session que en mi caso se llama valorCadena.
public class Global : System.Web.HttpApplication
    {
        string cadena=”valor inicial”;
        protected void Application_Start(object sender, EventArgs e) { }
        protected void Session_Start(object sender, EventArgs e)
        {
            Session[“valorCadena”] = cadena;
        } 
}
 En la página que lo necesitemos podemos escribir valores:
       Session[“valorCadena”] = “la_cadena_que_quiera_poner”;
y leer de la variable:
       Label1.Text = (string)Session[“valorCadena”];

viernes, 15 de noviembre de 2019

APP.CONFIG EN WIN FORMS EN .NET C#

En nuestra aplicacion tendremos un archivo de configuracion llamada app.config n el que podremos ir añadiendo las variables que queramos extraer añadiendo entradas al tag “appSettings” como el ejemplo siguiente:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="AppCode" value="GestionInvent"/>
  </appSettings>
</configuration>

Leer el fichero de configuración desde la aplicación

Una vez creado el fichero de configuración y añadidas las variables de configuración que queramos basta con hacer uso de la clase ConfigurationManager para leer el valor de las misma desde el código de nuestra aplicación:
codAplicacion = ConfigurationManager.AppSettings["GestionInvent"];
Utiliza el namespace “System.Configuration”