Not Another WordPress site

From the Blog

abr
19

Javascript:

<script type="text/javascript" language="javascript">

var dataAtual = new Date();

var dia = mydate.getDay();
var mes = mydate.getMonth();
var ano = mydate.getYear();

document.write( dia + "/" + mes + "/" + ano );

var hora = dataAtual.getHours();
var minutos = dataAtual.getMinutes();

var timeValue = hora + ((minutos < 10) ? ":0" : ":") + minutos;

document.write( timeValue );

</script>

 

PHP:

<?php
$data = date('d/m/Y');
echo $data;

$hora = date('h:i');
echo $hora;
?>

Asp.Net (C#):

DateTime agora = DateTime.Now;
String data = agora.ToString("MM-dd-yyyy");
Response.Write(data);

String hora = agora.ToString("HH:mm");
Response.Write(hora);

ago
16

I was wondering what to write about, and I realized that I needed to post something about what we have trouble to find the solution. Then I decided to write how to disable a button in a HTML page (using Asp.Net and C#) after the user clicked it. Avoiding so that the user click several times and send several requests to the server.

The solution uses basically javascript to disable the button just after the user clicked it. The method we used lays in a different namespace, called Common, which we pass the button and the text we wish to appear after the user click it (something like “Wait”), as parameters.

The method is bellow:

public static void DisableOnClick(System.Web.UI.WebControls.Button btn, string Message)
{
  string theScript = "";
  if ( btn.CausesValidation )
  {
     theScript = @"
        if (typeof(Page_ClientValidate) == 'function') 
        { 
           if (Page_ClientValidate() == false )
              return false; 
        }";
   }
   theScript += @"
      this.value = '" + Message + @"';
      this.disabled = true;
      document.getElementById('" + btn.ClientID + @"')
.disabled = true;" +
   btn.Page.ClientScript.GetPostBackEventReference(btn, string.Empty) + @";";
            
   btn.Attributes["onclick"] = theScript;
}

Basicaly what the method does is to create a script and attach it at the button click event. This script verify if the button does any kind of validation and, if any, run that code, after it the button is disabled and the new text is setted to the button, then the postback call is made.

Bellow is an example of use:

private void Page_Load(object sender, System.EventArgs e)
{
    Common.DisableOnClick(btnRegister, "Wait...");
}

Simple, easy and usefull…
Enjoy ;)

abr
28
Posted by Felipe V. Rigo at 11:25 pm

Estou usando o livro C# 3.0 Cookbook que ganhei durante o Pantanet Seminars I e ao procurar algumas receitas, vi que elas não constavam no livro, então resolvi publicar essas receitas nos mesmos moldes do livro. Claro que elas não serão tão didáticas e discutidas como no livro, mas o que vale é a intenção. Então o didatismo e a discussão dependerá dos comentários e dúvidas postados.
Como mesclar 2 vetores
Quando você tem um array e quer mesclar (unir) com outro array, não existe um método para isso como numa Lista, por exemplo, então é necessário fazer uma gambiarra. Nesta receita tenho 2 arrays a1 e a2, e quero uni-los no array a3:
string[] a1 = { “dog”, “dock”, “deer” };
string[] a2 = { “lion”, “tiger” };
string[] a3 = new string[a1.Length + a2.Length];
a1.CopyTo(a3, 0);
a2.CopyTo(a3, a1.Length);
Simples e conciso.
Outro caso poderia ser se você quisesse unir a2 a a1, como no C# não há como redimensionar arrays dinamicamente como no VB.Net, ou você pode atribuir a3 a a1, ou então usar uma função auxiliar para redimensionar a1 e depois copiar os valores de a2 para a1, como abaixo:
int pos = a1.Length;
a1  = RedimArray(a1, a1.Length + a2.Length);
a2.CopyTo(a1, pos);
Abaixo uma função para expandir arrays:
/// <summary>
/// Realoca um vetor com um novo tamanho, e copia seu 
/// conteúdo para o novo vetor.
/// </summary>
/// <param name=”oldArray”>o vetor antigo, a ser realocado.</param>
/// <param name=”newSize”>o tamanho do novo vetor.</param>
/// <returns>Um novo vetor com o mesmo conteúdo.</returns>

public static System.Array RedimArray(System.Array vetor, int novoTamanho)
{
    int tamanhoAnt = vetor.Length;
    System.Type tipo = vetor.GetType().GetElementType();
    System.Array novoVetor = System.Array.CreateInstance(tipo, novoTamanho);
    int tamanho = System.Math.Min(tamanhoAnt, novoTamanho);
    if (tamanho > 0)
        System.Array.Copy(vetor, novoVetor, tamanho);
    return novoVetor;
}
Porém caso fosse necessário fazer muitos redimensionamentos é recomendado usar uma Lista ou alguma outra coleção, especialmente se os vetores forem grandes ou com objetos de grande tamanho.

Technorati Tags: ,,,



Fique pensando em que tipo de assunto abordar, mas acho que quando se trata de um blog de informática, mais especificamente pra quem desenvolve (assim como eu), penso em postar um tópico que encontramos alguma dificuldade e achamos a solução.

Como não tenho feito muita coisa nova ultimamente, fui buscar nas soluções de problemas básicos e antigos que encontramos em projetos anteriores.
Uma dessas soluções, resolvida basicamente com javascript, é desabilitar um botão logo após este ser clicado, para evitar que um usuário clique várias vezes neste, causando várias requisições ao servidor e quem sabe um problema inesperado.

Nós usamos um método que fica em um namespace separado, chamado Common, em que passamos o botão e o texto do botão após o clique (algo como “Aguarde”), como parâmetros.

Veja abaixo:

public static void DisableOnClick(System.Web.UI.WebControls.Button btn, string Message)
{
  string theScript = "";
  if ( btn.CausesValidation )
  {
     theScript = @"
        if (typeof(Page_ClientValidate) == 'function') 
        { 
           if (Page_ClientValidate() == false )
              return false; 
        }";
   }
   theScript += @"
      this.value = '" + Message + @"';
      this.disabled = true;
      document.getElementById('" + btn.ClientID + @"')
.disabled = true;" +
   btn.Page.ClientScript.GetPostBackEventReference(btn, string.Empty) + @";";
            
   btn.Attributes["onclick"] = theScript;
}

Basicamente o que o método faz é criar um script e anexar ao evento de clique do botão. Este script verifica se o botão faz algum tipo de validação e, caso afirmativo, executa essa função, depois o botão é desabilitado, o novo texto é setado e é feita a chamada de postback que está anexada ao botão.

Exemplo de uso:

private void Page_Load(object sender, System.EventArgs e)
{
    Common.DisableOnClick(btnRegister, "Aguarde...");
}

Simples, prático e útil… Enjoy ;)