miércoles, 31 de diciembre de 2008

Obtener el dirctorio actual de la aplicacion

string dir = System.IO.Directory.GetCurrentDirectory();

Soluciones CRM Argentina

martes, 30 de diciembre de 2008

atributo propiedad por defecto vb.net

imports System.ComponentModel


_
Class Prueba
Inherits Control
Public Property Item() As Control
Get
Return newPropertyValue
End Get
Set(ByVal value As Control)
newPropertyValue = value
End Set
End Property
End Class

viernes, 19 de diciembre de 2008

agregar evento en vb.net

Este es la linea a agregar para que "ate" el evento del control al sub

AddHandler boton.Command, AddressOf BotonNoContestadas_OnCommand

Funcion donde se pone que hacer cuando se ejecuta el evento:
Private Sub BotonNoContestadas_OnCommand(ByVal sender As Object, ByVal e As CommandEventArgs)

End Sub


Desarrollo de Soluciones Informaticas

miércoles, 10 de diciembre de 2008

Numeros verdaderamente random en vb.net

poner este namespace:

Imports System.Security.Cryptography


codigo:

Dim ByteArray As Byte() = New Byte(3) {}
Dim rnd As New RNGCryptoServiceProvider()
rnd.GetBytes(ByteArray)
Return BitConverter.ToInt32(ByteArray, 0)


Diseño de sistemas a medida

viernes, 5 de diciembre de 2008

deshabilitar boton de imagen y "grisarlo" en asp.net

Private Sub deshabilitarBoton(ByVal img As ImageButton, ByVal habilitado As Boolean)
img.Enabled = habilitado
img.Style.Clear()
If Not habilitado Then
img.Style.Add("filter", "alpha(opacity=30)")
End If
End Sub

Obtener datatable de un sqlDtasource

Se obtiene de un metodo del SqldataSource

datasourceControl es del tipo SqldataSource

dim view as DataView = datasourceControl.Select(New DataSourceSelectArguments)
dim table as DataTable = view.ToTable()

lunes, 1 de diciembre de 2008

Hacer que una propiedad sea obligatoria

RequiredProperty()> _
Public Property Nombre_Propiedad() As String

viernes, 24 de octubre de 2008

como generar numeros verdaderamente random en sql server

La funcion RAND en SQL Server no es muy buena, y necesita un seed la primera vez dentro del un stored procedure, por ejemplo, y luego llamarla sin parametros.
De esta forma se obtienen numeros un poco mas variados.
El tema es como generar el "Seed".

Se puede hacer a partir de los milisegundos de la maquina mas algun otro valor de parametro que varie, porque sino ni los milisegundos lo hacen variar mucho

DECLARE @seed INT, @temp INT

SET @seed = DATEPART(ms, getdate()) + @parametroEntero --genero el seed
SET @temp = RAND(@seed) --Genero un numero dummy con el seed, no lo uso

DECLARE @i INT
SET @i=0

WHILE @i < 5
BEGIN
SELECT FLOOR(RAND()* 100) --Genero numeros aleatorios del 0-99

SET @i=@i+1
END

Como medir los tiempos de ejecucion en .Net

Esta es una forma de medir tiempo de ejecución hasta el milisegundo.
Se debe inlcuir: using System.Diagnostics;

Stopwatch stopWatch = new Stopwatch();

stopWatch.Start();
//Aca va el codigo que querramos probar
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string intervalo = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine(intervalo);

Desarrollo a medida

jueves, 16 de octubre de 2008

Autenticacion manual de forms

Si la pagina ha sido redireccionada a la pagina de login podemos hacer esto (autoriza y redirecciona a la pagina anterior):
FormsAuthentication.RedirectFromLoginPage("administrador", True)

Si no hay pagina donde volver, solo autorizamos al usuario y seguimos adelante:
FormsAuthentication.SetAuthCookie("administrador", False)

Presupuesto desarrollo web

martes, 14 de octubre de 2008

lunes, 13 de octubre de 2008

sentencia en sql server para que no reconozca letras acentuadas

se agrega el collation al final de la linea del where que busca el varchar:
SELECT * FROM Tabla
WHERE campoTexto LIKE '%' + @prefijo + '%' COLLATE Latin1_General_CI_AI

http://www.pointsolutions.com.ar/

jueves, 9 de octubre de 2008

Error: The following module was built either with optimizations enabled or without

The following module was built either with optimizations enabled or without
debug information:
{test.dll}
To debug this module, change its
project build configuration to Debug mode. To suppress this message, disable the
'Warn if no user code on launch' debugger option.

La solucion que encontre fue cambiar en el web.config

< compilation debug="false">

De esta forma al volver a correr el VS, pregunta si queres que cambie este setting a "True", pero debe agregar o cambiar otras cosas tambien en el Bin.

Y el proyecto empieza a funcionar.

http://www.pointsolutions.com.ar/Soluciones.aspx

martes, 7 de octubre de 2008

Error: control with id ... could not be located or a different control is assigned to the same ID after postback

Este error me salio en el GridView y la forma de solucionarlo fue activar el viewstate en el GridView es decir, agregarle la propiedad:
Viewstate="true"

http://www.pointsolutions.com.ar/presupuesto.aspx

jueves, 18 de septiembre de 2008

Obtener root del sitio (para desarrollo y produccion)

Esto devuelve el path web real del sitio (relativo)
Por ejemplor devuelve "/web/"

string a = Page.ResolveUrl("~");

jueves, 11 de septiembre de 2008

Obtener el guid del usuario logueado en este momento

MembershipUser mu = Membership.GetUser(Profile.UserName);
string id=mu.ProviderUserKey.ToString();

instanciando SqlParameterCollection

SqlParameterCollection pc = new SqlCommand().Parameters;
pc.AddWithValue("@ClienteID", 1 );

instanciando SqlParameterCollection

SqlParameterCollection pc = new SqlCommand().Parameters;
pc.AddWithValue("@ClienteID", 1 );

Obtener el ultimo id autonumerico de una tabla sql server

SET NOCOUNT ON --para que no retorne ningun recordset vacio, por las dudas
INSERT (a,b,x) VALUES(1,2,3)

SELECT @@IDENTITY --devuelve el ultimo id insertado, cuando el id de la tabla es autonumerico

lunes, 8 de septiembre de 2008

debuggear javascript en internet explorer

1) Ir a tools->internet options->advanced
2) Asegurarse que esten desmarcados “Disable Script Debugging (other)” y “Disable Script Debugging (Internet Explorer)".
3) El script debugger viene con el Office 2003 o Office XP. O usar el debugger de visual studio
3) Reiniciar el IE
4) Para activarlo ir a View -> Script Debugger -> Open. O para dispararlo del codigo poner "debugger;"

viernes, 5 de septiembre de 2008

para mostrar el atributo de texto que se ve al hacer debug.

El formato del atributo es:

<DataObjectAttribute()> _
<DebuggerDisplayAttribute("Campo: {Name} Tipo: {TypeName} Tipo SQL: {SQLType}")> _
Public Class Field

Los parametros entre {} son propiedades, si son metodos el formato sera: {GetString()}

Poner el
Imports System.Diagnostics

http://www.pointsolutions.com.ar/presupuesto2.aspx

jueves, 4 de septiembre de 2008

Clonar un objeto de forma total en .net

Private Function Clonar(ByVal obj As Object) As Object
Dim ms As New MemoryStream
Dim objResult As Object = Nothing
Try
Dim bf As New BinaryFormatter
bf.Serialize(ms, obj)
ms.Position = 0
objResult = bf.Deserialize(ms)
Finally
ms.Close()
End Try
Return objResult
End Function

Icono de la pagina (favicon)

Simplemente hacer un icono de 16x16 px de 16 o 256 colores.

Algunos browsers interpretan los iconos de 16x16px de 32 bits colores (+alpha channel). Entonces se puede hacer un archivo con los dos iconos dentro, pero no los interpreta el IE.

Luego hay que renombrarlo como favicon.ico.
Y poner en el header de las paginas:
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /gt;

miércoles, 3 de septiembre de 2008

StringComparison is not declared vb.net

Cambiar a :
System.StringComparison

martes, 2 de septiembre de 2008

un metodo de busqueda de controles recursivo

Function BuscarControl(ByVal padre As Control, ByVal id As String)
Dim ctl As Control = padre.FindControl(id)
If ctl Is Nothing Then
For Each item As Control In padre.Controls
ctl = BuscarControl(item, id)
If ctl IsNot Nothing Then Exit For
Next
End If
Return ctl
End Function


http://www.pointsolutions.com.ar/desarrollo_web.aspx

El Datalist o Gridview no se refresca al cambiarse los datos

Poner el refresh del DataSourceID en el Load del control.

protected void Datalist1_Load(object sender, EventArgs e)
{
Datalist1.DataSourceID = dlAnuncios.DataSourceID;
}




Desarrollo de sistemas a medida

Color RGB desde un color Web

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

lunes, 1 de septiembre de 2008

usercontrol (ascx) pierde los valores de las propiedades

Reemplazar las propiedades por:


public bool prop1
{
get { return (bool) ViewState["prop1"]; }
set { ViewState["prop1"] = value; }
}


y usar el valor de ViewState["prop1"]

configuracion de smtp en web.config

Poner dentro de <configuration>
(Verficar de ponerlo dentro de system.net)

<system.net>
<mailsettings>
<system.net>
<mailsettings>
<smtp from="no_responder@server.com" deliverymethod="Network">
<network defaultcredentials="true" port="25" host="mail.server.com">
</smtp>
</mailsettings>
</system.net>

estilo hover del link

a {
color:#0f305d;
text-decoration:none;
}
a:hover {
text-decoration:underline;
}

viernes, 29 de agosto de 2008

asp.net para exportar datos y mantener los acentos

Dim builder As New System.Text.StringBuilder
builder.Append("á é í ó ú ñ")
Response.BinaryWrite(Encoding.Default.GetBytes(builder.ToString))

Remover Acentos

Function convertirSinAcentos(ByVal palabra As String) As String
Dim output As String = palabra
output = output.Replace("á", "a")
output = output.Replace("é", "e")
output = output.Replace("í", "i")
output = output.Replace("ó", "o")
output = output.Replace("ú", "u")
output = output.Replace("ñ", "n")
output = output.Replace("Á", "A")
output = output.Replace("É", "E")
output = output.Replace("Í", "I")
output = output.Replace("Ó", "O")
output = output.Replace("Ú", "U")
output = output.Replace("Ñ", "N")
Return output
End Function

convertir fecha a formato yyyy-mm-dd

dim fecha as string = "29-08-2008"
dim a as string=CType(fecha, DateTime).ToString("yyyy-MM-dd hh:mm")

jueves, 28 de agosto de 2008

Problemas con recursos embebidos y custom ajax control toolkit

problemas con el recurso embebido de js ("but does not contain an embedded resource with name ...")

el problema fue que donde estaba esto:

[ClientScriptResource("AjaxControlToolkit.ITYH_Combo2.ITYH_Combo2Behavior", "AjaxControlToolkit.ITYH_Combo2.ITYH_Combo2Behavior.js")]

debia ir (sin el nombre del assembly...)
[ClientScriptResource("AjaxControlToolkit.ITYH_Combo2Behavior", "AjaxControlToolkit.ITYH_Combo2Behavior.js")]

Y en el WebResource tambien sacarle el nombre del assembly:
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.ITYH_Combo2.ITYH_Combo2Behavior.js", "text/javascript")]cambiar por:[assembly: System.Web.UI.WebResource("AjaxControlToolkit.ITYH_Combo2Behavior.js", "text/javascript")]

No encuentra el namespace Drawing

Problema: The type or namespace name 'Drawing' does not exist in the namespace 'System' (are you missing an assembly reference?)

Solucion: Agregar la referencia a ese namespace "System.Drawing"
Hacer boton derecho sobre la solucion y click en "Add Reference "

Obtener cadena de conexion del web.config

poner:
using System.Configuration;

agregar la referencia a :
System.Configuration

usar:

string NombreConexion = "cs_1";
string connStr = ConfigurationManager.ConnectionStrings[NombreConexion].ConnectionString;


http://www.pointsolutions.com.ar/presupuesto2.aspx

Devolver byte array de una string

Encoding.ASCII.GetBytes(builder.ToString)

Factory: Devolver valor de un control de cualquier tipo

Private Function tomarValorFactory(ByVal nombreControl As String) As String
If nombreControl IsNot Nothing And nombreControl <> "" Then
Dim control As Control = Me.Parent.FindControl(nombreControl)

Select Case control.GetType.Name
Case "HiddenField"
Return CType(control, HiddenField).Value
Case "TextBox"
Return CType(control, TextBox).Text
Case "Label"
Return CType(control, Label).Text
Case "DropDownList"
Return CType(control, DropDownList).SelectedValue
Case "CheckBox"
Return CType(control, CheckBox).Checked
Case "RadioButton"
Return CType(control, RadioButton).Text
Case "Literal"
Return CType(control, Literal).Text
Case "Calendar"
Return CType(control, Calendar).SelectedDate.ToShortDateString()
Case Else
Throw New Exception("Falta definir el control")
Return ""
End Select
Else
Return ""
End If
End Function

Obtener un Datatable de un SQLDataSource

Dim dv As DataView = CType(ds.Select(DataSourceSelectArguments.Empty), DataView)
dt = dv.Table



Para obtener un SQLDatareader, poner esta propiedad:
ds.DataSourceMode = SqlDataSourceMode.DataReader