Agregar Referencia

16/12/2009 - 14:55 por Paul P. Garcia | Informe spam
Saludos.

Intento aprender CSharp, el cual me esta costando...
Por el momento me gustaria saber cuales son los pasos para agregar
referencias.
En VB.net2008 podia mostrar todos los eventos de una dll agregando el
siguiente codigo (primero le doy al menu Project > Add Reference):
Inherits System.Windows.Forms.Form


" Código generado por el Diseñador de Windows Forms "



Dim WithEvents WinSockServer As New Servidor()



Pero en CSharp no veo como se lista los eventos de un control o de un
componente. En VB.Net en la parte de arriba, tiene una lista desplegable el
cual muestra todos los eventos de un control.



Tengo mi DLL (el cual contiene eventos) hecho en VB.NET el cual quiero
agregarlo a mi aplicación desarrollado en CSharp.



Gracias de antemano.

Preguntas similare

Leer las respuestas

#6 Paul P. Garcia
18/12/2009 - 15:59 | Informe spam
Muchas gracias Alberto por tus comentarios, poco a poco voy aprendiendo...
Sobre la DLL es algo que yo desarrolle, supongo que debo meterle un IDispose
a mi dll
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.IO
Public Class Cliente
#Region "VARIABLES"
Private tcpThd As New Thread(AddressOf LeerSocket) 'Se encarga de escuchar
mensajes enviados por el Servidor
Private m_IPDelHost As String 'Direccion del objeto de la clase Servidor
Private m_PuertoDelHost As String 'Puerto donde escucha el objeto de la
clase Servidor
Private client As New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
#End Region

#Region "EVENTOS"
Public Event ConexionTerminada()
Public Event DatosRecibidos(ByVal datos As String)
Public Event Conectado()
#End Region

#Region "PROPIEDADES"
Public Property IPDelHost() As String
Get
IPDelHost = m_IPDelHost
End Get

Set(ByVal Value As String)
m_IPDelHost = Value
End Set
End Property

Public Property PuertoDelHost() As String
Get
PuertoDelHost = m_PuertoDelHost
End Get
Set(ByVal Value As String)
m_PuertoDelHost = Value
End Set
End Property
#End Region

#Region "METODOS"
Public Sub Conectar()
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(IPDelHost)
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
'Establecer el host y el puerto
Dim remoteEP As New IPEndPoint(ipAddress, PuertoDelHost)
'Conectar con el ip remoto
client.Connect(remoteEP) : RaiseEvent Conectado()
'Creo e inicio un thread para que escuche los mensajes enviados por el
Servidor
'tcpThd = New Thread(AddressOf LeerSocket)
tcpThd.Start()
End Sub
Public Sub Cerrar()
tcpThd.Abort()
client.Shutdown(SocketShutdown.Both)
Try
client.Disconnect(reuseSocket:=True)
Catch e As SocketException
MsgBox(e.ErrorCode)
End Try
End Sub

Public Sub EnviarDatos(ByVal datos As String)
Dim BufferDeEscritura() As Byte
BufferDeEscritura = Encoding.ASCII.GetBytes(datos)
If (client.Connected) Then
Dim bytesSent As Integer = client.Send(BufferDeEscritura)
End If
End Sub

#End Region
#Region "FUNCIONES PRIVADAS"
Private Sub LeerSocket()
Dim bytes(100) As Byte
While True
Try
Dim bytesRec As Integer = client.Receive(bytes)
'Genero el evento DatosRecibidos, ya que se han recibido datos desde
el Servidor
RaiseEvent DatosRecibidos(Encoding.ASCII.GetString(bytes, 0,
bytesRec))
Catch e As SocketException
Exit While
End Try
End While
'Finalizo la conexion, por lo tanto genero el evento correspondiente
client.Shutdown(SocketShutdown.Both) : client.Close()
RaiseEvent ConexionTerminada()
End Sub
#End Region
End Class

Como implementaria mi Dispose?

Esta DLL lo quiero pasar a C#, pero al crear un hilo (private Thread tcpThd
= new Thread(new ThreadStart(LeerSocket));) hago referencia a un static,
pero cuando hago esto todo lo referente a client me da error (solo lo que
esta dentro de public static void LeerSocket()) supongo porque esta fuera de
alcanze...
Hice una pregunta sobre este tema pero nadie me esta respondiendo y nose
como resolverlo a ver esperare que alguien me de una manito...

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
public class Cliente
{
#region "VARIABLES"
//Se encarga de escuchar mensajes enviados por el Servidor
private Thread tcpThd = new Thread(new ThreadStart(LeerSocket));
//Direccion del objeto de la clase Servidor
private string m_IPDelHost;
//Puerto donde escucha el objeto de la clase Servidor
private int m_PuertoDelHost;
#endregion
private Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
#region "EVENTOS"
public event ConexionTerminadaEventHandler ConexionTerminada;
public delegate void ConexionTerminadaEventHandler();
public event DatosRecibidosEventHandler DatosRecibidos;
public delegate void DatosRecibidosEventHandler(string datos);
public event ConectadoEventHandler Conectado;
public delegate void ConectadoEventHandler();
#endregion
#region "PROPIEDADES"
public String IPDelHost
{
get { return m_IPDelHost; }
set { m_IPDelHost = value; }
}

public int PuertoDelHost
{
get { return m_PuertoDelHost; }
set { m_PuertoDelHost = value; }
}
#endregion
#region "METODOS"
public void Conectar()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(IPDelHost);
IPAddress ipAddress = ipHostInfo.AddressList[0];
//Establecer el host y el puerto
IPEndPoint remoteEP = new IPEndPoint(ipAddress, PuertoDelHost);
//Conectar con el ip remoto
client.Connect(remoteEP);
if (Conectado != null)
{
Conectado();
}
//Creo e inicio un thread para que escuche los mensajes enviados por
el Servidor
//tcpThd = New Thread(AddressOf LeerSocket)
tcpThd.Start();
}
public void Cerrar()
{
tcpThd.Abort();
client.Shutdown(SocketShutdown.Both);
try
{
client.Disconnect(true);
}
catch (SocketException e)
{
//Interaction.MsgBox(e.ErrorCode);
}
}
public void EnviarDatos(string datos)
{
byte[] BufferDeEscritura = null;
BufferDeEscritura = Encoding.ASCII.GetBytes(datos);
if ((client.Connected))
{
int bytesSent = client.Send(BufferDeEscritura);
}
}

#endregion
#region "FUNCIONES PRIVADAS"
public static void LeerSocket()
{
byte[] bytes = new byte[101];
while (true)
{
try
{
int bytesRec = client.Receive(bytes);
//Genero el evento DatosRecibidos, ya que se han recibido
datos desde el Servidor
if (DatosRecibidos != null)
{
DatosRecibidos(Encoding.ASCII.GetString(bytes, 0,
bytesRec));
}
}
catch (SocketException e)
{
break; // TODO: might not be correct. Was : Exit While
}
}
//Finalizo la conexion, por lo tanto genero el evento
correspondiente
client.Shutdown(SocketShutdown.Both);
client.Close();
if (ConexionTerminada != null)
{
ConexionTerminada();
}
}
#endregion
}
Respuesta Responder a este mensaje
#7 Alberto Poblacion
18/12/2009 - 17:49 | Informe spam
"Paul P. Garcia" wrote in message
news:%23XlreJ$
Sobre la DLL es algo que yo desarrolle, supongo que debo meterle un
IDispose [...]
Public Sub Cerrar()
tcpThd.Abort()
[...]
Como implementaria mi Dispose?



Bueno, ya tienes un Cerrar() que se supone que hace lo mismo que debería
hacer el Dispose(). Así que basta con que debajo de la clase pongas
"Implements IDisposable" y añadas un método Dispose que símplemente llame al
método Cerrar.
También te sugeriría, como precaución adicional, que pongas
tcpThd.IsBackground=True para asegurarte de que el hilo se para
automáticamente cuando se hayan parado todos los threads de foreground.

Esta DLL lo quiero pasar a C#, pero al crear un hilo (private Thread
tcpThd = new Thread(new ThreadStart(LeerSocket));) hago referencia a un
static,



Lo que no comprendo es por qué has hecho ese cambio al pasar de VB a C#.
En VB, tienes tanto el tcpThd como el LeerSocket declarados como miembros de
instancia, pero al traducirlos a C# le has puesto un "static" al LeerSocket,
convirtiéndolo en estático (Shared), con lo que tienes ahi una discrepancia
respecto a la clase original. También has cambiado, sin motivo aparente, el
Private por public (aunque esto no debería dar error).

El caso es que tienes una inicialización como esta: Private tcpThd As
New Thread(AddressOf LeerSocket) que no es lícita en C# (te da un error
diciendo que el método no es estático), pero no se arregla cambiando el
método a estático, sino llevando la inicialización al constructor, y dejando
que el método siga siendo de instancia:

public class Cliente
{
private Thread tcpThd;
...
public Cliente()
{
tcpThd = new Thread(LeerSocket);
}
...
private void LeerSocket()
{
...
}
...
}
Respuesta Responder a este mensaje
#8 Paul P. Garcia
18/12/2009 - 20:21 | Informe spam
Muy pero muy agradecido Alberto...
Mira como estoy usando SharpDevelop 3.1 para pasar de vb.net a C# me lo dejo
sin que pueda implementar el hilo LeerSocket y como el C# me indicaba que
era porque no era static, ya te imaginaras.
Les dejo mi codigo por si a alguien le sirve aunque le falta mucho, poco a
poco voy a ir optimisandolo... a medida que aprenda C#, quiero plantarme en
este lenguaje de programación...

using Microsoft.VisualBasic;
using System;

using System.Collections;

using System.Collections.Generic;

using System.Diagnostics;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.Text;

using System.IO;

public class SockCliente

{

#region "VARIABLES"

//Se encarga de escuchar mensajes enviados por el Servidor

private Thread tcpThd;

private SockCliente()

{

tcpThd = new Thread(LeerSocket);

}

//Direccion del objeto de la clase Servidor

private string m_IPDelHost;

//Puerto donde escucha el objeto de la clase Servidor

private int m_PuertoDelHost;

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

#endregion

#region "EVENTOS"

public event ConexionTerminadaEventHandler ConexionTerminada;

public delegate void ConexionTerminadaEventHandler();

public event DatosRecibidosEventHandler DatosRecibidos;

public delegate void DatosRecibidosEventHandler(string datos);

public event ConectadoEventHandler Conectado;

public delegate void ConectadoEventHandler();

#endregion

#region "PROPIEDADES"

public String IPDelHost

{

get { return m_IPDelHost; }

set { m_IPDelHost = value; }

}

public int PuertoDelHost

{

get { return m_PuertoDelHost; }

set { m_PuertoDelHost = value; }

}

#endregion

#region "METODOS"

public void Conectar()

{

IPHostEntry ipHostInfo = Dns.GetHostEntry(IPDelHost);

IPAddress ipAddress = ipHostInfo.AddressList[0];

//Establecer el host y el puerto

IPEndPoint remoteEP = new IPEndPoint(ipAddress, PuertoDelHost);

//Conectar con el ip remoto

client.Connect(remoteEP);

if (Conectado != null)

{

Conectado();

}

//Creo e inicio un thread para que escuche los mensajes enviados por el
Servidor

//tcpThd = New Thread(AddressOf LeerSocket)

tcpThd.Start();

}

public void Cerrar()

{

tcpThd.Abort();

client.Shutdown(SocketShutdown.Both);

try

{

client.Disconnect(true);

}

catch (SocketException e)

{

//Interaction.MsgBox(e.ErrorCode);

}

}

public void EnviarDatos(string datos)

{

byte[] BufferDeEscritura = null;

BufferDeEscritura = Encoding.ASCII.GetBytes(datos);

if ((client.Connected))

{

int bytesSent = client.Send(BufferDeEscritura);

}

}

#endregion

#region "FUNCIONES PRIVADAS"

private void LeerSocket()

{

byte[] bytes = new byte[101];

while (true)

{

try

{

int bytesRec = client.Receive(bytes);

//Genero el evento DatosRecibidos, ya que se han recibido datos desde el
Servidor

if (DatosRecibidos != null)

{

DatosRecibidos(Encoding.ASCII.GetString(bytes, 0, bytesRec));

}

}

catch (SocketException e)

{

break; // TODO: might not be correct. Was : Exit While

}

}

//Finalizo la conexion, por lo tanto genero el evento correspondiente

client.Shutdown(SocketShutdown.Both);

client.Close();

if (ConexionTerminada != null)

{

ConexionTerminada();

}

}
#endregion
}
email Siga el debate Respuesta Responder a este mensaje
Ads by Google
Help Hacer una pregunta AnteriorRespuesta Tengo una respuesta
Search Busqueda sugerida