viernes, 29 de febrero de 2008

Crystal Reports en WinForms - Exportar a pdf un reporte con C#.NET

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace ClockManager
{
public partial class Reports : Form
{
#region Propiedades

public string filePath = "";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();

#endregion

#region Metodos

public Reports()
{
InitializeComponent();
}
public void SaveFile()
{


if (filePath.Trim() == "")
return;
//
TuNameSpace.RPT_FECHA_HORA_X_ID rpt = new TuNameSpace.RPT_FECHA_HORA_X_ID();
ReportDocument myReport = new ReportDocument();

//Le paso un parametro al reporte [esto es opcional]
rpt.SetParameterValue("@ID", "25832556");

//Defino los parametros de conexion
string UserID = "usuario1";
string Password = "123456";
string ServerName = "MiPc\\SQLEXPRESS";
string DatabaseName = "MIBASE";

//Seteo los parametros de conexion
rpt.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);


try
{
//Exporto el archivo
rpt.ExportToDisk(ExportFormatType.PortableDocFormat, this.filePath);
MessageBox.Show("OK!");
}
catch (Exception ex)
{
string a = ex.Message;
}

}

#endregion

private void Reports_Load(object sender, EventArgs e)
{
//Seteo algunas propiedades del SaveFileDialog
this.saveFileDialog1.AddExtension = true;
this.saveFileDialog1.AutoUpgradeEnabled = true;
this.saveFileDialog1.CheckFileExists = false;
this.saveFileDialog1.CheckPathExists = false;
this.saveFileDialog1.DefaultExt = ".pdf";

this.saveFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk);
saveFileDialog1.ShowDialog();
}

#region Eventos

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.filePath = saveFileDialog1.FileName;
SaveFile();
}


#endregion
}

}

T-SQL - Función para saber si un numero es par

CREATE FUNCTION DBO.ISPAR
(@ID SMALLINT)
RETURNS CHAR(1)
AS

BEGIN

DECLARE @RESULT CHAR(1)

SET @RESULT = CASE WHEN ABS(@ID) % 2 = 1
THEN
'I' --IMPAR
ELSE
'P' --PAR
END
RETURN @RESULT

END

martes, 26 de febrero de 2008

FillSortGridControl

///
/// Crea los items del combo que permite la seleccion del campo por el
/// cual se desea ordena r la grilla.
/// [Las columnas del tipo Template no estan soportadas]
///

/// param name="gridControl">Grilla que contiene las columnas
/// param name="sortControl">Combo que permite la seleccion de ordenado de la grilla

public void FillSortGridControl(GridView gridControl, DropDownList sortControl)
{
sortControl.Items.Clear();

foreach (DataControlField gridColumn in gridControl.Columns)
{
string text = gridColumn.HeaderText; ;
string value = "";

switch (gridColumn.GetType().ToString())
{
case ("System.Web.UI.WebControls.BoundField"):
value = ((BoundField)gridColumn).DataField;
break;

case ("System.Web.UI.WebControls.HyperLinkField"):
value = ((HyperLinkField)gridColumn).DataTextField;
break;

case ("System.Web.UI.WebControls.TemplateField"):
//value = ((TemplateField)gridColumn).ItemTemplate;
break;

}

if (text != "" && value != "")
{
sortControl.Items.Add(new ListItem(text + " asc", value + " asc"));
sortControl.Items.Add(new ListItem(text + " desc", value + " desc"));
}

}


}

Metodo ShowMessage en ASP.NET

///
/// Muestra un mensaje del lado del cliente generado con una instruccion
/// alert() en javascript
///

/// param name="sender"> La clase (generalmente el formulario que muestra el mensaje) donde se debe mostrar el mensaje.
/// param name="message">Mensaje que desea mostrar.
public void ShowMessage(System.Web.UI.Page sender, string message)
{
string msg = "alert('" + message + "');";
sender.ClientScript.RegisterStartupScript(base.GetType(), "jsValMot", msg, true);
}

Validar campos vacios,

///
/// Para validar que los campos no están vacios
///

/// param name="a">Array de string de parametros
public bool Validar(string[] a)
{
foreach (string s in a)
{
if (s == "")
{
return false;
}
}
return true;
}


string[] a = new string[] { txtUsuario.Text.Trim(), txtPass.Text.Trim() };
if (!Validar(a))
{
MessageBox.Show("Todos los campos son obligatorios.");
return;
}

Arma llamadas a Stored Procedures

///
/// Basicamente es para no tener que agregar las comas y las comillas
/// a los parametros cada vez que quiero llamar un Stored Procedure.
///

/// param name="sp">Nombre del Stored Procedure a ejecutar
/// param name="param">Array de string de parametros para pasar al StoredProcedure
public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}

SqlServerCe - SQL Server Compact Edition (Winforms)

/*
Clase tipo capa de datos para Sql Server Compact Edition.
*/


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;

class DBPortable
{
private static string dbName = "MyDB";
private static string pass = "123456";
private static string connString = "Data Source =\"|DataDirectory|\\" + dbName + ".sdf\"; Password =\"" + pass + "\";";
private SqlCeConnection conn = new SqlCeConnection(connString);

public DBPortable()
{
if (!HaveDB())
{
CreateDB();
CreateSchema();
}
}

private bool HaveDB()
{
if (System.IO.File.Exists(conn.Database))
{
return true;
}
else
{
return false;
}
}

private void CreateDB()
{
using (SqlCeEngine sqlCeEngine = new SqlCeEngine(connString))
{
sqlCeEngine.CreateDatabase();
}
}

public string BuildQueryFromString(string sp, string[] param)
{
string query = sp + " '";
int i = 0;
foreach (string p in param)
{
if (i < param.Length - 1)
query += p + "', '";
else
query += p + "'";
i++;
}
return query;
}
public DataSet ExecQuery(string iQuery)
{
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();

try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}

return ds;

}
public DataSet ExecSP(string sp, string[] param)
{
string iQuery = BuildQueryFromString(sp, param);
DataSet ds = new DataSet();
SqlCeDataAdapter adapter = new SqlCeDataAdapter();

try
{
SqlCeCommand command = new SqlCeCommand(iQuery, this.conn);
adapter.SelectCommand = command;
this.conn.Open();
command.Connection = this.conn;
adapter.Fill(ds);
}
catch(SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}

return ds;
}
private void CreateSchema()
{
string q = "CREATE TABLE TablaDePrueba(ID int NULL, FechaHora DATETIME NULL, ESTADO NCHAR(1))";
this.ExecuteNonQuery(q);
}
private int ExecuteNonQuery(string query)
{
int RowsAffected = 0;

SqlCeCommand objCom = new SqlCeCommand();
objCom.CommandText = query;

try
{
this.conn.Open();
objCom.Connection = this.conn;
RowsAffected = objCom.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.conn.Close();
}

return RowsAffected;
}

Método para encriptar a MD5

public string md5(string strPlainText)
{
byte[] hashedDataBytes;
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText));
string a = "";
foreach (byte b in hashedDataBytes)
{
a += b.ToString();
}
return a;
}