miércoles, 28 de agosto de 2013

Open File Dialog WPF


          Para inocar el open dialog desde WPF es sencillo solo necesitamos el siguiente codigo

 Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Establece el filtro para archovs .CSv
            dlg.DefaultExt = ".csv";
            dlg.Filter = "Archivo separado por comas (.csv)|*.csv";

            // metodo que despliega el dialogo
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                FileInfo FI = new FileInfo(filename);

            }

Capturar Audio a WAV C#

Esta clase  nos ayuda a  capturar un WAv desde C# de forma sencilla

  class Audio2
    {
        [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
        Boolean recording = false;

        public String Iniciar()
        {
            try
            {
                if (!recording)
                {
                    mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
                    mciSendString("record recsound", "", 0, 0);
                    recording = true;
                    return "OK";
                }
                else
                {
                    return "Ya se esta grabando";
                }
       }
       catch (Exception ex)
       {
                //recording = false;
                return ex.Message;
       }
         
        }
        public String Stop(String _file)
        {
            try
            {
                if (recording)
                {
                    mciSendString(@"save recsound " + _file, "", 0, 0);
                    mciSendString("close recsound ", "", 0, 0);
                    recording = true;
                    return "OK";
                }
                else
                {
                    return "No se esta grabando";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public byte[] Stop(String _file)
        {
            try
            {
                if (recording)
                {
                    mciSendString(@"save recsound " + _file, "", 0, 0);
                    mciSendString("close recsound ", "", 0, 0);
                    byte[] bytes = File.ReadAllBytes(_file);
                    recording = false;
                    return bytes;
                }
                else
                {
                    throw new Exception("No se esta grabando");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

Exportar a excell sencillo

En el siguiente código veremos cómo exportar el contenido de un DataGridView a un fichero Excel con WindowsForms usando C#.
Inicialmente tendremos que añadir la siguiente referencia al proyecto de tipo COM:
Microsoft Excel 12.0 Object Library
Para poder añadir la referencia anterior, tenemos que tener instalado previamente en nuestro sistema el Microsoft Excel.
El método nos preguntará por la ruta donde queremos almacenar el fichero en el disco mediante un objeto del tipo SaveFileDialog.
El código del método que rellena el documento excel es el siguiente:

///

/// Método que exporta a un fichero Excel el contenido de un DataGridView
///

/// DataGridView que contiene los datos a exportar
private void ExportarDataGridViewExcel(DataGridView grd)
{
    SaveFileDialog fichero = new SaveFileDialog();
    fichero.Filter = "Excel (*.xls)|*.xls";
    if (fichero.ShowDialog() == DialogResult.OK)
    {
        Microsoft.Office.Interop.Excel.Application aplicacion;
        Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
        Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
        aplicacion = new Microsoft.Office.Interop.Excel.Application();
        libros_trabajo = aplicacion.Workbooks.Add();
        hoja_trabajo = 
            (Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
        //Recorremos el DataGridView rellenando la hoja de trabajo
        for (int i = 0; i < grd.Rows.Count - 1; i++)
        {
            for (int j = 0; j < grd.Columns.Count; j++)
            {
                hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();
            }
        }
        libros_trabajo.SaveAs(fichero.FileName, 
            Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
        libros_trabajo.Close(true);
        aplicacion.Quit();
    }
}

miércoles, 14 de agosto de 2013

Guardar un Grid como Imagen en WPF

Primero necesiamos agregar la calse Model con el siguiente Codigo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.IO;

namespace WpfApplication9
{

public enum ImageFormat
{
        JPG, BMP, PNG, GIF, TIF
}
public class Model
{
          private ObservableCollection<BitmapSource> imagecollection;
public ObservableCollection<BitmapSource> ImageCollection
{
        get
        {
                this.imagecollection = this.imagecollection ?? new ObservableCollection<BitmapSource>();
                return this.imagecollection;
        }
}

public RenderTargetBitmap RenderVisaulToBitmap(Visual vsual, int width, int height)
{
        RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
        rtb.Render(vsual);
        BitmapSource bsource = rtb;
        this.ImageCollection.Add(bsource);
        return rtb;
}

public MemoryStream GenerateImage(Visual vsual, int widhth, int height, ImageFormat format)
{
        BitmapEncoder encoder = null;
        switch (format)
        {
                case ImageFormat.JPG :
                        encoder = new JpegBitmapEncoder();
                        break;
                case ImageFormat.PNG:
                        encoder = new PngBitmapEncoder();
                        break;
                case ImageFormat.BMP:
                        encoder = new BmpBitmapEncoder();
                        break;
                case ImageFormat.GIF:
                        encoder = new GifBitmapEncoder();
                        break;
                case ImageFormat.TIF:
                        encoder = new TiffBitmapEncoder();
                        break;
        }
        if (encoder == null) return null;

        RenderTargetBitmap rtb = this.RenderVisaulToBitmap(vsual, widhth, height);
        MemoryStream file = new MemoryStream();
        encoder.Frames.Add(BitmapFrame.Create(rtb));
        encoder.Save(file);

        return file;
    }
}
}
Luego se agrega en el Windows.Resource de l Xaml
<
Window.Resources>
            <local:Model x:Key="Foto" />
</Window.Resources>

Instanciamos la case y lo referimos al recuros del xaml

 private Model DataModel
{
        get { return this.Resources["Foto"] as Model; }
}

ahora usamos el evento del boton que renderisará el grid  a una imagen y listo

private void Button_Click_1(object sender, RoutedEventArgs e)
{
        BitmapEncoder encoder = new JpegBitmapEncoder();
        //ImgFinal --> Grid aconvertir
        RenderTargetBitmap rtb = this.DataModel.RenderVisaulToBitmap(ImgFinal, (int)ImgFinal.ActualWidth, (int)ImgFinal.ActualHeight);
        MemoryStream file = new MemoryStream();
        encoder.Frames.Add(BitmapFrame.Create(rtb));
        encoder.Save(file);

        if (file != null)
        {
                SaveFileDialog fdlg = new SaveFileDialog
                {
                        DefaultExt = "jpg",
                        Title = "Choose filename and location",
                        Filter = "*Jpeg files|.jpg|Bmp Files|*.bmp|PNG Files|*.png|Tiff Files|*.tif|Gif Files|*.gif"
                };
                bool? result = fdlg.ShowDialog();
                if (result.HasValue && result.Value)
                {
                        using (FileStream fstream = File.OpenWrite(fdlg.FileName))
                        {
                                file.WriteTo(fstream);
                                fstream.Flush();
                                fstream.Close();
                        }
                }
        }
}