Mostrando las entradas con la etiqueta C#. Mostrar todas las entradas
Mostrando las entradas con la etiqueta C#. Mostrar todas las entradas
domingo, 17 de julio de 2011
Store Procedure que regresa un select oracle
1.) Crear un Ref Cursor que será retornado:
create or replace PACKAGE Types AS
TYPE cursor_type IS REF CURSOR;
END Types;
2.) Creando el Store procedure
create or replace
PROCEDURE getAllCity(p_recordset OUT types.cursor_type) AS
BEGIN
OPEN p_recordset FOR
select * from tbl_country;
END getAllCity;
3.) Código c# que llama el store procedure
string strconn = myDynconnStr;
OracleConnection conn = new OracleConnection(strconn);
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = conn;
objCmd.CommandText = "getAllCity";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("p_recordset", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataAdapter odr = new OracleDataAdapter(objCmd);
DataSet ds = new DataSet();
odr.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Ver
create or replace PACKAGE Types AS
TYPE cursor_type IS REF CURSOR;
END Types;
2.) Creando el Store procedure
create or replace
PROCEDURE getAllCity(p_recordset OUT types.cursor_type) AS
BEGIN
OPEN p_recordset FOR
select * from tbl_country;
END getAllCity;
3.) Código c# que llama el store procedure
string strconn = myDynconnStr;
OracleConnection conn = new OracleConnection(strconn);
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = conn;
objCmd.CommandText = "getAllCity";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("p_recordset", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataAdapter odr = new OracleDataAdapter(objCmd);
DataSet ds = new DataSet();
odr.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
viernes, 15 de julio de 2011
Calcular tiempos ( Timespan)
Representa un intervalo de tiempo. Un objeto TimeSpan representa un intervalo de tiempo (duración de tiempo o tiempo transcurrido) que se mide como un número positivo o negativo de días, horas, minutos, segundos y fracciones de segundo.
Ejemplo:
protected void Button1_Click(object sender, EventArgs e)
{
TimeSpan tspan;
DateTime inicio;
DateTime final;
inicio = DateTime.Now;
//codigo de proceso o consulta
final = DateTime.Now;
tspan = final.Subtract(inicio).Duration();
Label1.Text = tspan.Duration().ToString();
Label2.Text = " Minutos: " + tspan.Minutes.ToString();
Label3.Text = " Segundos: " + tspan.Seconds.ToString();
}
Ver
Ejemplo:
protected void Button1_Click(object sender, EventArgs e)
{
TimeSpan tspan;
DateTime inicio;
DateTime final;
inicio = DateTime.Now;
//codigo de proceso o consulta
final = DateTime.Now;
tspan = final.Subtract(inicio).Duration();
Label1.Text = tspan.Duration().ToString();
Label2.Text = " Minutos: " + tspan.Minutes.ToString();
Label3.Text = " Segundos: " + tspan.Seconds.ToString();
}
jueves, 24 de febrero de 2011
Primer y Ultimo día de Mes c#
DateTime? fechatemp = null;
DateTime? fecha1 = null;
DateTime? fecha2 = null;
fechatemp = DateTime.Today;
fecha1 = new DateTime(fechatemp.Value.Year, fechatemp.Value.Month, 1);
fecha2 = new DateTime(fechatemp.Value.Year, fechatemp.Value.Month + 1, 1).AddDays(-1);
Ver
DateTime? fecha1 = null;
DateTime? fecha2 = null;
fechatemp = DateTime.Today;
fecha1 = new DateTime(fechatemp.Value.Year, fechatemp.Value.Month, 1);
fecha2 = new DateTime(fechatemp.Value.Year, fechatemp.Value.Month + 1, 1).AddDays(-1);
lunes, 27 de julio de 2009
¿Cómo hacer un Servicio Windows en C#? (Con timer)
Tenimos el servicio. Escribiendo al log. Unicamente:
public partial class MyNewService: ServiceBase
{
  public MyNewService()
   {
     InitializeComponent();
      if (!System.Diagnostics.EventLog.SourceExists("MySource"))
      {
      System.Diagnostics.EventLog.CreateEventSource(
      "MySource","MyNewLog");
     }
     eventLog1.Source = "MySource";
     eventLog1.Log = "MyNewLog";
    }
   protected override void OnStart(string[] args)
   {
      eventLog1.WriteEntry("In OnStart");
   }
   protected override void OnStop()
   {
      eventLog1.WriteEntry("In onStop.");
   }
 }
Bueno ahora hay que agregar un timer:
Pueden agregar un timer grafico o por codigo.
como agregarlo por código
Abran el archivo
MyNewService.Designer.cs
agreguen el código en la parte de abajo de su documento para definir el timer:
private System.Timers.Timer mytimer;
ahora busquen el evento
private void InitializeComponent()
agreguen esta definicion alli:
this.mytimer = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.mytimer)).BeginInit();
this.mytimer.Enabled = true;
this.mytimer.Interval = 2000D;
this.mytimer.Elapsed += new System.Timers.ElapsedEventHandler(this.mytimer_Elapsed);
((System.ComponentModel.ISupportInitialize)(this.mytimer)).EndInit();
ahora cambiemonos al servicio MyNewService
y busquemos el evento OnStart y agreguen la configuracion tal y como aparece abajo:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
this.mytimer.Elapsed += new System.Timers.ElapsedEventHandler(mytimer_Elapsed);
mytimer.Interval = 2000;
mytimer.Enabled = true;
}
agregue el siguiente evento:
en medio de este evento puede conectarse a la db o hacer lo que ustedes quieran.
private void mytimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
}
Ver
public partial class MyNewService: ServiceBase
{
  public MyNewService()
   {
     InitializeComponent();
      if (!System.Diagnostics.EventLog.SourceExists("MySource"))
      {
      System.Diagnostics.EventLog.CreateEventSource(
      "MySource","MyNewLog");
     }
     eventLog1.Source = "MySource";
     eventLog1.Log = "MyNewLog";
    }
   protected override void OnStart(string[] args)
   {
      eventLog1.WriteEntry("In OnStart");
   }
   protected override void OnStop()
   {
      eventLog1.WriteEntry("In onStop.");
   }
 }
Bueno ahora hay que agregar un timer:
Pueden agregar un timer grafico o por codigo.
como agregarlo por código
Abran el archivo
MyNewService.Designer.cs
agreguen el código en la parte de abajo de su documento para definir el timer:
private System.Timers.Timer mytimer;
ahora busquen el evento
private void InitializeComponent()
agreguen esta definicion alli:
this.mytimer = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.mytimer)).BeginInit();
this.mytimer.Enabled = true;
this.mytimer.Interval = 2000D;
this.mytimer.Elapsed += new System.Timers.ElapsedEventHandler(this.mytimer_Elapsed);
((System.ComponentModel.ISupportInitialize)(this.mytimer)).EndInit();
ahora cambiemonos al servicio MyNewService
y busquemos el evento OnStart y agreguen la configuracion tal y como aparece abajo:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
this.mytimer.Elapsed += new System.Timers.ElapsedEventHandler(mytimer_Elapsed);
mytimer.Interval = 2000;
mytimer.Enabled = true;
}
agregue el siguiente evento:
en medio de este evento puede conectarse a la db o hacer lo que ustedes quieran.
private void mytimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
}
martes, 27 de mayo de 2008
Como leer y escribir fotos en una db en .net
No hay comentarios.:
Publicadas por
Carlos Juan
a la/s
8:27 p.m.
Etiquetas:
C#,
Visual Basic,
Visual studio
Manejar objetos de gran tamaño en .net es sumamente facil, cuando me refiero a objetos grandes me refiero a Fotos o textos grandes.
aqui doy un ejemplo de como guardar fotos en la base de datos:
Guardar fotos
Tabla del sql server
CREATE TABLE fotos(
[codigo] [int] primary key IDENTITY (1, 1),
[nombre] [varchar](50) NULL,
[foto] [image] NULL
)
Tu formulario tiene que estar de la siguiente manera:

-- Codigo del boton Imagen
(despliega la ventan para seleccionar la imagen)
OpenFileDialog1.ShowDialog()
txtruta.Text = OpenFileDialog1.FileName
-- codigo del boton grabar
Dim cn As New SqlClient.SqlConnection("user id=sa;password=pass;initial" & _ "catalog=northwind;data source=.\sqlexpress")
'lectura de la foto de imagen a binario
Dim filePath As String = txtruta.Text
Dim stream As IO.FileStream = New IO.FileStream(filePath, _
IO.FileMode.Open, IO.FileAccess.Read)
Dim reader As IO.BinaryReader = New IO.BinaryReader(stream)
Dim foto() As Byte = reader.ReadBytes(stream.Length)
reader.Close()
stream.Close()
'guardado de la fot en la db
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand( _
"INSERT INTO fotos( nombre, foto) " & _
"Values(@nombre, @foto)", _
cn)
cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 50).Value = txtnombre.Text
cmd.Parameters.Add("@foto", SqlDbType.Image, foto.Length).Value = foto
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Lleer fotos
Tu formulario tiene que estar de la siguiente manera:

-- Codigo del boton buscar(busca el codigo del textbox y despliega la imagen)
nota: no usen * en el select, es mas eficiente poner los campos.
Dim cn As New SqlClient.SqlConnection("user id=sa;" & _
"password=pass;initial catalog=northwind;data source=.\sqlexpress")
Dim cmd As New SqlClient.SqlCommand("", cn)
Dim dr As SqlClient.SqlDataReader
Dim sql As String
sql = "select nombre, foto from fotos where codigo=@codigo"
cmd.CommandText = sql
cmd.Parameters.Add("@codigo", SqlDbType.Int, 4).Value = txtcodigo.Text
cn.Open()
dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess _
Or CommandBehavior.CloseConnection)
If dr.HasRows Then
While dr.Read()
'nombre de la foto
lblnombre.Text = Convert.ToString(dr!nombre)
'
If (dr.IsDBNull(1)) Then
MessageBox.Show("No hay imagen", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
Else
Dim bytes As SqlTypes.SqlBytes = dr.GetSqlBytes(1)
PictureBox1.Image = Image.FromStream(bytes.Stream)
'PictureBox1.Image=bytes.Write
End If
End While
Else
MessageBox.Show("Codigo no existe", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
cn.Close()
Cambien la propiedad SizeMode a StretchImage para que la imagen se adapte al control.
Ver
aqui doy un ejemplo de como guardar fotos en la base de datos:
Guardar fotos
Tabla del sql server
CREATE TABLE fotos(
[codigo] [int] primary key IDENTITY (1, 1),
[nombre] [varchar](50) NULL,
[foto] [image] NULL
)
Tu formulario tiene que estar de la siguiente manera:
-- Codigo del boton Imagen
(despliega la ventan para seleccionar la imagen)
OpenFileDialog1.ShowDialog()
txtruta.Text = OpenFileDialog1.FileName
-- codigo del boton grabar
Dim cn As New SqlClient.SqlConnection("user id=sa;password=pass;initial" & _ "catalog=northwind;data source=.\sqlexpress")
'lectura de la foto de imagen a binario
Dim filePath As String = txtruta.Text
Dim stream As IO.FileStream = New IO.FileStream(filePath, _
IO.FileMode.Open, IO.FileAccess.Read)
Dim reader As IO.BinaryReader = New IO.BinaryReader(stream)
Dim foto() As Byte = reader.ReadBytes(stream.Length)
reader.Close()
stream.Close()
'guardado de la fot en la db
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand( _
"INSERT INTO fotos( nombre, foto) " & _
"Values(@nombre, @foto)", _
cn)
cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 50).Value = txtnombre.Text
cmd.Parameters.Add("@foto", SqlDbType.Image, foto.Length).Value = foto
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Lleer fotos
Tu formulario tiene que estar de la siguiente manera:
-- Codigo del boton buscar(busca el codigo del textbox y despliega la imagen)
nota: no usen * en el select, es mas eficiente poner los campos.
Dim cn As New SqlClient.SqlConnection("user id=sa;" & _
"password=pass;initial catalog=northwind;data source=.\sqlexpress")
Dim cmd As New SqlClient.SqlCommand("", cn)
Dim dr As SqlClient.SqlDataReader
Dim sql As String
sql = "select nombre, foto from fotos where codigo=@codigo"
cmd.CommandText = sql
cmd.Parameters.Add("@codigo", SqlDbType.Int, 4).Value = txtcodigo.Text
cn.Open()
dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess _
Or CommandBehavior.CloseConnection)
If dr.HasRows Then
While dr.Read()
'nombre de la foto
lblnombre.Text = Convert.ToString(dr!nombre)
'
If (dr.IsDBNull(1)) Then
MessageBox.Show("No hay imagen", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
Else
Dim bytes As SqlTypes.SqlBytes = dr.GetSqlBytes(1)
PictureBox1.Image = Image.FromStream(bytes.Stream)
'PictureBox1.Image=bytes.Write
End If
End While
Else
MessageBox.Show("Codigo no existe", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
cn.Close()
Cambien la propiedad SizeMode a StretchImage para que la imagen se adapte al control.
Suscribirse a:
Entradas (Atom)