segunda-feira, 31 de janeiro de 2011

SQL Server - Funções de data


Prezado leitor. Se você tivesse nascido ontem, obviamente hoje você teria um dia de idade. Agora responda rápido, e em SQL: qual o número de dias vividos por você até hoje?
Aprenderemos neste artigo a trabalhar com funções de data no SQL Server. As principais são:GETDATEDATEPARTDATEADD e DATEDIFF.
Um detalhe importante é que as funções de data trabalham referenciando unidades de data. As mais comuns são:
- year(ano);
- month(mês);
- day(dia);
Observações:
1) Books OnLine do SQL Server apresenta a lista completa desses parâmetros de valores (unidades ), bem como outras funções de data;
2) as configurações de data para esse artigo estão no formato americano. Logo, a data 02/01/2004 deve ser lida como primeiro de fevereiro de 2004.
GETDATE ( )
A função GETDATE retorna a data e a hora atuais do sistema. Podemos, no Query Analyzer , digitar o seguinte comando para obter a data e hora atuais:
SELECT GETDATE ( )
DATEPART ( unidade data )
A função DATEPART retorna a parte especificada de uma data como um inteiro. Observe os exemplos:
SELECT DATEPART ( YEAR , '02/01/2004' )
Reposta: 2004
SELECT DATEPART ( MONTH , '02/01/2004' )
Reposta: 2
SELECT DATEPART ( DAY , '02/01/2004' )
Reposta: 1
DATEADD ( unidade numero_unid,data )
A função DATEADD retorna uma nova data através da soma do número de unidades especificadas pelo valor unidade a uma data. Observe os exemplos:
SELECT DATEADD ( DAY ,6, '02/01/2004' )
Reposta: 2004-02-07
SELECT DATEADD ( MONTH ,6, '02/01/2004' )
Reposta: 2004-08-01
SELECT DATEADD ( YEAR ,6, '02/01/2004' )
Reposta: 2010-02-01
DATEDIFF ( unidade data1,data2 )
A função DATEDIFF calcula a diferença entre as datas data2 data1 , retornando o resultado como um inteiro, cuja unidade é definida pelo valor unidade . Observe os exemplos:
SELECT DATEDIFF ( DAY , '02/01/2004' , '05/25/2004' )
Reposta: 114 (dias)
SELECT DATEDIFF ( MONTH , '02/01/2004' , '05/25/2004' )
Reposta: 3(meses)
SELECT DATEDIFF ( YEAR , '02/01/2004' , '05/25/2006' )
Reposta: 2(anos)
Dessa forma, a expressão SQL que retorna o número de dias vivido por você até hoje é:
SELECT DATEDIFF(DAY, suadata, GETDATE())
onde suadata deve ser substituída pela sua data de nascimento.
Outro exemplo interessante é mostrado através do código T-SQL abaixo. Usando funções de data, exibimos, para cada cliente, a idade em dias, meses e em anos (idade do cliente na data atual e em 31 de dezembro). 

Observe a lógica utilizada no comando CASE. Neste caso, é testado se o cliente já fez aniversário, comparando o mês em que ele nasceu com o mês corrente e comparando o dia em que ele nasceu com o dia corrente. Se essa comparação for verdadeira, basta diminuir o ano atual do ano de nascimento do cliente. Caso contrário (o cliente ainda não fez aniversário), temos que diminuir 1 do valor anterior.
SELECT NOME, NASCIMENTO,

  DATEDIFF(DAY,NASCIMENTO,GETDATE())AS DIASVIVIDOS,

  DATEDIFF(MONTH,NASCIMENTO,GETDATE()) AS MESESVIVIDOS,

  CASE WHEN

     DATEPART(MONTH,NASCIMENTO)<= DATEPART(MONTH,GETDATE()) AND

     DATEPART(DAY,NASCIMENTO)<= DATEPART(DAY,GETDATE())

  THEN

        (DATEDIFF(YEAR,NASCIMENTO,GETDATE()))

  ELSE

       (DATEDIFF(YEAR,NASCIMENTO,GETDATE()))- 1

       END AS IDADEATUAL,

  DATEDIFF(YEAR,NASCIMENTO,GETDATE())AS IDADE3112

FROM CLIENTE
26-05pic.JPG 
Vimos, neste artigo, exemplos do uso de funções de data no SQL Server. Outros SGBDs implementam funções de data, provavelmente com sintaxe diferente. Consulte a documentação do SGBD que você utiliza, para obter maiores detalhes.
Baixe aqui o script utilizado nesse artigo.
Referências:
•  Books OnLine do SQL Server
•  SQL Server 7: Transact-SQL – Guia de Consulta Rápida: Novatec Editora
Tenha bons estudos!

sexta-feira, 28 de janeiro de 2011

Ajax - Calendário em Português


<asp:ToolkitScriptManager ID="ToolkitScriptManager1" EnableScriptGlobalization="true" EnableScriptLocalization="true" runat="server">
</asp:ToolkitScriptManager>

terça-feira, 25 de janeiro de 2011

ASP.NET - QueryString


Query String allows you to pass values between the asp.net pages.

Let us say, you are navigating to below URL

QueryString1.gif

In above URL, you are navigating to a page called Add.aspx and Number1 and Number2 are query string to page Add.aspx.

To create Query String,

  1. Add a question mark (?) to URL.
  2. After Question mark, give variable name and value separated by equal to (=).
  3. If more than one parameter need to be passed then separate them by ampersand (&).
To read query String,
Say your URL is,
http://localhost:12165/Add.aspx?Number1=72&Number2=27

Then to read query string, on Add.aspx

QueryString2.gif

You can read by passing exact variable name in index or,

QueryString3.gif

You can read, by passing index value as above.

Now, I am going to show you a very basic sample,
  1. I will create a page with two text boxes and one link button.
  2. I will pass text boxes values as query string to other page on click event of link button.
  3. On the other page, I will read the query string value and will add them in display in a label.
I have created a new asp.net application. Then I dragged and dropped two textboxes and one link button on the page. On click event of link button, I am performing the below operation.

QueryString4.gif

I am constructing the URL, as to navigate to Add.aspx page and then appending two query strings from textbox1 text and textbox2 text.

Now, add a page to project say Add.aspx . Drag and drop a label on the page. On the page load event perform the below operation.

QueryString5.gif

So, when you run the application you will get the output as below,


QueryString6.gif

For your reference, the whole source code is given below,

Default.aspx.cs
using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;
namespacequeryparameterexample
{
publicpartialclass_Default : System.Web.UI.Page    {protectedvoidPage_Load(object sender, EventArgs e)        {

        }
protectedvoid LinkButton1_Click(object sender, EventArgs e)
        {
stringurltoNaviget = "~/Add.aspx?Number1=" +                                      TextBox1.Text +"&Number2=" +
                                     TextBox2.Text;

            LinkButton1.PostBackUrl = urltoNaviget;
        }
    }
}

Add.aspx.cs
using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;
namespacequeryparameterexample
{publicpartialclassWebForm1 : System.Web.UI.Page    {protectedvoidPage_Load(object sender, EventArgs e)        {
string number1 = Request.QueryString[0];string number2 = Request.QueryString[1];
// The other way to Read the values
//string number1 = Request.QueryString["Number1"];
//string number2 = Request.QueryString["Number2"];
int result = Convert.ToInt32(number1) + Convert.ToInt32(number2);
            Label2.Text = result.ToString();

        }
    }
}

quinta-feira, 20 de janeiro de 2011

ASP.NET (C#) - Visualizar ficheiros


 System.Diagnostics.Process.Start(@"C:\windows\system32\explorer.exe", @"C:\jardel.jpeg");

para ir buscar o caminho do servidor:

Server.MapPath("..\\Documentos\\Empresas\\20.png")

Ajax - Retroceder ao separador de origem


Quando for para outra página enviar:
 int tab = 6;
String red = "Detalhes.aspx?emp=" + emp+"&tab="+tab;
Response.Redirect(red);

Depois de receber:
tab = Request.QueryString["tab"];
int tb = Convert.ToInt32(tab);
TabContainer1.ActiveTabIndex = tb;

terça-feira, 18 de janeiro de 2011

Java - Abrir ficheiros zip dentro de zip (recursivo)


      

   FileInputStream zf = new FileInputStream(zipFileName.toString());
                        ZipInputStream zipFile = new ZipInputStream(new BufferedInputStream(zf));
            parseZipFile(zipFile, granularity);                                          
                        ...
       
                       
private void parseZipFile(ZipInputStream zIS, PmGranularity granularity){

ZipEntry ze;
                                while((ze = zIS.getNextEntry()) != null){
                                String fname = ze.getName();
                                if (fname.endsWith(".zip")) {                  
                                        parseZipFile(new ZipInputStream(new ZipClose(zIS)), granularity);
                                        continue;
                                }      
                               
                                //DO SOMETHING LIKE PARSING TEXT FILES
                               
                                zIS.closeEntry();
                        }
                    zIS.close();
}              
private final class ZipClose extends java.io.FilterInputStream {
            public ZipClose(ZipInputStream is) {
                super(is);
            }
            @Override
            public void close() throws IOException {
                ((ZipInputStream) in).closeEntry();
            }
        }