sexta-feira, 11 de fevereiro de 2011

Utilizando o tipo implícito “var” no C#

Um padrão de programação muito utilizado entre os programadores C# é deixar de declarar variáveis locais com tipos explícitos, veja exemplo:

public void Teste()
{
    string fantasia = "Unimake Softwares";
    int valor = 100;
}



Neste caso deixamos claro o tipo de cada uma das variáveis, sendo uma do tipo string e outra do tipo inteiro, mas existe um tipo implícito que deixa o código mais alinhado e facilita a programação que é o tipo “var”, veja um exemplo:

public void Teste()
{
    var fantasia = "Unimake Softwares";
    var valor = 100;
}



Como as variáveis já tem seu valor prédefinido na declaração, o C# já reconhece automaticamente o seu tipo, por isso podemos utilizar o tipo “var”. Reforçamos que se o valor da variável não for prédefinido na declaração, será necessário utilizar tipo explicito.

terça-feira, 10 de agosto de 2010

Criando objetos em ASP

Script de exemplo para criar um objeto personalizado e ASP.
Script retirado do site: Geekpedia

<%
Option Explicit

Class MyClass
'
'-------------------------------
' Properties (local variables)
' - You can make them public, but that is
' insecure and stupid.
'
Private i_MyData ' Used internally, but given secured access
' via Property Let/Get
Private s_String ' Only used internally
'
'-------------------------------
' Property Accessots
' - These are the rules for i_MyData (Let/Get)
'
Public Property Let MyData(valueIn)
'
' valueIn is the data given to property
' (as in... property = valueIn)
'
If valueIn>777 Then valueIn = 777
If valueIn<111 Then valueIn = 111
'
i_MyData = valueIn
End Property

Public Property Get MyData
'
' This allows data to be retrived
' [as in... Response.write(myObj.MyData) ]
'
MyData = i_MyData
End Property

'
'-------------------------------
' Constructors/Deconstructors/
' - These fire when creating/destroying object
'
Private Sub Class_Initialize
'
' Use this to set local variables...
'
i_MyData = 777 ' Monkeys gone to heaven...
s_String = "No data here... "
'
Response.Write("myClass has started<br>")
End Sub
'
Private Sub Class_Terminate
'
' Use this to clean up
'
Response.Write("myClass has stopped<br>")
End Sub

'-------------------------------
' Methods
'
Public Sub DoSomething()
'
' internal Sub (called a method)
'
Response.Write(s_String & i_MyData & "<br>")
End Sub

Public Function NonsenseMaths(NumberIn)
'
' internal Function (also called a method)
'
If NumberIn>20 Then NumberIn = 20
If NumberIn<5 Then NumberIn = 5
'
NonsenseMaths = i_MyData * NumberIn
End Function
End Class
'
'==================================================
'
' Now for use...
'
Dim sStick ' This will hold our new object

Set sStick = New MyClass
Response.write(sStick.MyData)
Response.write("<br>")
sStick.MyData = 666 ' the devil (booo!)
Response.write(sStick.MyData)
Response.write("<br>")
sStick.DoSomething()
Response.write(sStick.NonsenseMaths(9))
Response.write("<br>")
Set sStick = Nothing
%>

terça-feira, 3 de agosto de 2010

Função Crossbrowser getElementById()

Esta função é para garantir que o seu script irá funcionar com versões mais antigas do Internet Explorer.

function getElementById2(elemID)
{
    if(document.all) // Se for uma versão mais antiga
    {
         return eval("document.all['" + elemID + "']");
    }
    else
    {
         return document.getElementById(elemID);
    }
}

quarta-feira, 28 de julho de 2010

Lista de Atalhos do VS 2005 e 2008

A Microsoft disponibilizou para download pôsters de referência com a lista de atalhos do Visual Studio 2005 e 2008. Eles são para o perfil C-Sharp.

Links abaixo.
Microsoft Visual C# 2005 Keybinding Reference Poster
Microsoft Visual C# 2008 Keybinding Reference Poster

segunda-feira, 26 de julho de 2010

Impedir Cache do Navegador Web

Response.Expires = -1
Response.Buffer = True
Response.CacheControl = "no-cache"
Response.ExpiresAbsolute = Now() - 1
Response.AddHeader "cache-control", "private"
Response.AddHeader "Pragma", "no-cache"

terça-feira, 6 de julho de 2010

Números Aleatórios com CSharp

// Retorna um número aleatório não negativo
Random n = new Random();
Console.WriteLine(n.Next());


// Retorna um número aleatório não negativo até 108
Random n = new Random();
Console.WriteLine(n.Next(108)); // Não gera maior que 108


// Gera um número aleatório em um intervalo
Random n = new Random();
Console.WriteLine(n.Next(1, 108)); // Não maior que 108, não inferior a 1


// Este não gera um número aleatório propriamente dito,
// por que é especificado uma semente
Random n = new Random(1986);
Console.WriteLine(n.Next()); // Isso sempre gera 564610494


// O método NextDouble() retornará um número entre 0 e 1
Random n = new Random();
Console.WriteLine(n.NextDouble());


// Gera um array de bytes, cada elemento da matriz será um
// byte com um valor de 0 a 255
byte[] b = new byte[108];
Random n = new Random();
n.NextBytes(b);

quinta-feira, 14 de maio de 2009

AddChr

A função AddChr é usada para adicionar caráteres a uma string. Há três argumentos requeridos: Entrada, adição, posição.

<%
' Dim a
' a = "Help Me! Trapped in computer"
' Response.Write AddChr(a, ", can't get out", Len(a)) & "
"
' returns: "Help Me! Trapped in computer, can't get out"

Private Function AddChr(byVal string, byVal addition, byVal location)
Dim leftString, rightString

On Error Resume Next

leftString = Left(string, location)

If Err Then
leftString = ""
location = 0
End If

rightString = Mid(string, location + 1)

AddChr = leftString & addition & rightString

On Error GoTo 0
End Function

%>