Ir para conteúdo
Fórum Script Brasil

ursolouco

Veteranos
  • Total de itens

    2.314
  • Registro em

  • Última visita

Posts postados por ursolouco

  1. Brothers,

    Estou deixando abaixo um pequeno script (html/javascript) para localizar GeoCoordenadas (latitude e longitude) de um determinado endereço,

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://maps.google.com/maps?file=api"></script>
    <style type="text/css" media="screen">
    * { font: 20px 'Trebuchet MS'; }
    </style>
    </head>
    <body>
        <form id="formPesquisa" method="post" action="">    
            <div>
                <p>Informe seu endereco para localizar suas coordenadas geograficas</p>
            </div>    
            <fieldset>
                <legend>Consulta de endereco:</legend>
                <label for="endereco">Informe o endereco a pesquisar:</label>
                <input style="width: 650px;" type="text" id="endereco" value="Av Manuel Velho Moreira, são Paulo, Brasil" />
                <input type="button" id="pesquisar" value="Localizar Coordenadas" />
            </fieldset>
            <div id="container-resultado">
                <ul id="resultado"></ul>
            </div>
        </form>
    </body>
    </html>
    <script type="text/javascript">
    <!--
    $(document).ready(function(){
        $('#pesquisar').click(function(event){
            event.preventDefault();
            event.stopPropagation();
            $resultado = $('#resultado');
            $endereco = $('#endereco');
            _endereco = $.trim($endereco.val());
            if(_endereco.length > 0){
                $.ajax({
                    url: 'https://maps.googleapis.com/maps/api/geocode/json',
                    dataType: 'json',
                    data: {
                        sensor: false,
                        region: 'BR',
                        address: _endereco
                    },
                    beforeSend: function(){
                        $resultado.html('').append('<li>Carregando! Aguarde...</li>');
                    },
                    success: function(response){
                        $resultado.html('');
                        $resultado.parent().prepend('<h4>Resultado da sua pesquisa:</h4>');
                        if(response.status == 'OK'){                                            
                            $resultado.append('<li><span style="font-weight:bold;">Latitude:</span>'+ response.results[0].geometry.location.lat.toString() +'</li>');
                            $resultado.append('<li><span style="font-weight:bold;">Longitude:</span>'+ response.results[0].geometry.location.lng.toString() +'</li>');
                        }
                    }
                });
            }
            return false;
        });
    });
    //-->
    </script>
    

    Abraços!

  2. Exemplo 3

    USE TESTE
    GO
    
    CREATE PROCEDURE DEMO
    AS
    BEGIN
    SET NOCOUNT ON
    DECLARE @NOME VARCHAR(100);
    SET @NOME = 'WELLINGTON RODRIGUES';
    SELECT @NOME;
    END
    GO
    
    EXEC DEMO
    Default3.aspx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Configuration;
    
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            ConnectionStringSettings strCon = WebConfigurationManager.ConnectionStrings["local"] as ConnectionStringSettings;
            using (SqlConnection con = new SqlConnection(strCon.ConnectionString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("DEMO", con);
                var nome = cmd.ExecuteScalar();
                Label1.Text = nome.ToString();
            }
        }
    }

  3. Novo exemplo:

    ALTER PROCEDURE RETORNA_VALOR 
        @SAIDA FLOAT OUTPUT
    AS
    BEGIN
        SET @SAIDA = RAND();
    END
    GO
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Web.Configuration;
    using System.Data;
    
    public partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            ConnectionStringSettings strCon = WebConfigurationManager.ConnectionStrings["local"] as ConnectionStringSettings;
            using (SqlConnection con = new SqlConnection(strCon.ConnectionString)) {
                con.Open();
                SqlCommand cmd = new SqlCommand("RETORNA_VALOR", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@saida", SqlDbType.Float).Direction = ParameterDirection.Output;
                cmd.ExecuteNonQuery();
                Label1.Text = cmd.Parameters["@saida"].Value.ToString();
            }
        }
    }

  4. Salve,

    Veja se te ajuda (não sei bem se vai funcionar porque estou só usando EF4)

    script.sql

    USE TESTE
    GO
    
    ALTER PROCEDURE RETORNAVALORES
    AS
    BEGIN;
    SET NOCOUNT ON
    SELECT RAND()
    END;
    GO
    Default.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Executar" onclick="Button1_Click" 
                Width="140px" />    
            <br />
            <br />
            <asp:Label ID="Label1" runat="server"></asp:Label>
        </div>
        </form>
    </body>
    </html>
    Default.aspx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Web.Configuration;
    using System.Configuration;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            ConnectionStringSettings strCon = WebConfigurationManager.ConnectionStrings["local"] as ConnectionStringSettings;
            using (SqlConnection con = new SqlConnection(strCon.ConnectionString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("EXEC RETORNAVALORES", con);
                var valor = cmd.ExecuteScalar();
                Label1.Text = valor.ToString();
            }
        }
    }

    []s

  5. Mesmo removendo o método substring() o problema permanece

    System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Dados de cadeia ou binários seriam truncados.
    A instrução foi finalizada.
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
       at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
       --- End of inner exception stack trace ---
       at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
       at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
       at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
       at System.Data.Objects.ObjectContext.SaveChanges()
       at ProjWebTestePoco.Add.btnAddCliente_Click(Object sender, EventArgs e)

  6. Salve,

    Alguém poderia me explicar por qual motivo está disparando a exceção ao adicionar o registro na base?

    Add.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using PocoLibrary;
    
    namespace ProjWebTestePoco
    {
        public partial class Add : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void btnAddCliente_Click(object sender, EventArgs e)
            {
                if (IsPostBack)
                {
                    try
                    {
                        using (NorthwindPocoContext contexto = new NorthwindPocoContext())
                        {
                            Customer customer = new Customer();                        
                            customer.CustomerID = txtCodigoCliente.Text.Trim().Substring(0, 10);                        
                            customer.CompanyName = txtNomeEmpresa.Text.Trim().Substring(0, 80);
                            contexto.Customers.AddObject(customer);
                            contexto.SaveChanges();
                            lblMensagem.Text = "Cliente Registrado com sucesso";
                        }
                    }
                    catch (Exception ex)
                    {
                        lblMensagem.Text = "<pre>" + ex.ToString() + "</pre>";
                    }
                }
            }
        }
    }
    Customer.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace PocoLibrary
    {
        public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
            public string Address { get; set; }
            public string City { get; set; }
            public string Region { get; set; }
            public string PostalCode { get; set; }
            public string Country { get; set; }
            public string Phone { get; set; }
            public string Fax { get; set; }
            public List<Order> Orders { get; set; }
        }
    }
    Add.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Add.aspx.cs" Inherits="ProjWebTestePoco.Add" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="lblMensagem" runat="server" Text=""></asp:Label>    
                <table>
                    <tbody>
                        <tr>
                            <td>Código do cliente:</td>
                            <td>
                                <asp:TextBox ID="txtCodigoCliente" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td>Nome da empresa:</td>
                            <td>
                                <asp:TextBox ID="txtNomeEmpresa" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2"> </td>
                        </tr>
                        <tr>
                            <td> </td>
                            <td>
                                <asp:Button ID="btnAddCliente" runat="server" onclick="btnAddCliente_Click" 
                                    Text="Adicionar Cliente" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <br />
                <a href="Default.aspx" target="_self">Listar Consumidores</a>
            </div>
        </form>
    </body>
    </html>
    Exception
    System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
    Parameter name: length
       at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
       at System.String.Substring(Int32 startIndex, Int32 length)
       at ProjWebTestePoco.Add.btnAddCliente_Click(Object sender, EventArgs e)

  7. Exemplo (não dos melhores):

    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Drawing" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        protected void ResetBackGroundGridView()
        {
            foreach (DataControlField c in GridView1.Columns)
            {
                c.ItemStyle.BackColor = Color.Transparent;
            }
        }
    
        protected void btnNome_Click(object sender, EventArgs e)
        {
            SqlDataSource1.SelectCommand = "SELECT [CustomerID], [CompanyName], [ContactName], [Phone] FROM [Customers] order by ContactName";
            ResetBackGroundGridView();
            GridView1.Columns[2].ItemStyle.BackColor = Color.Yellow;
        }
    
        protected void btnCia_Click(object sender, EventArgs e)
        {
            SqlDataSource1.SelectCommand = "SELECT [CustomerID], [CompanyName], [ContactName], [Phone] FROM [Customers] order by CompanyName";
            ResetBackGroundGridView();
            GridView1.Columns[1].ItemStyle.BackColor = Color.Yellow;
        }
    
        protected void btnId_Click(object sender, EventArgs e)
        {
            SqlDataSource1.SelectCommand = "SELECT [CustomerID], [CompanyName], [ContactName], [Phone] FROM [Customers] order by CustomerID";
            ResetBackGroundGridView();
            GridView1.Columns[0].ItemStyle.BackColor = Color.Yellow;
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" 
                AutoGenerateColumns="False" DataKeyNames="CustomerID" 
                DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" 
                        SortExpression="CustomerID" />
                    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" 
                        SortExpression="CompanyName" />
                    <asp:BoundField DataField="ContactName" HeaderText="ContactName" 
                        SortExpression="ContactName" />
                    <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:NWind %>" 
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Phone] FROM [Customers]">
            </asp:SqlDataSource>
            <br />
            <br />
        &nbsp;<asp:Button ID="btnId" runat="server" Text="Ordenar Por Id" 
                onclick="btnId_Click" />
        &nbsp;&nbsp;
            <asp:Button ID="btnCia" runat="server" onclick="btnCia_Click" 
                Text="Ordenar por CIA" />
    &nbsp;&nbsp;
            <asp:Button ID="btnNome" runat="server" onclick="btnNome_Click" 
                Text="Ordenar por Nome" />
        </div>
        </form>
        <p>
            &nbsp;</p>
    </body>
    </html>

  8. Salve,

    Tenho novidades.

    Segui um conteúdo do fórum da Adobe e consegui resolver o problema instalando a versão antiga do flash player (10.3.183.20).

    Segue a referência: http://forums.adobe.com/thread/1022066?tstart=0

    Se alguém precisar do conteúdo que utilizei, segue o link para download dos arquivos.

    Para testar se tudo deu ok, basta acessar o site do Youtube e ouvir uma música de preferência.

    Abraços

  9. Salve,

    Feliz 2011, segue meus comentários abaixo:

    Se voce não informa o que cabe na lista ela por padrão recebe qualquer objeto, ou seja, "Object".

    Hum... entendi!!!

    Precisaria determinar mais ou menos assim:

    public static void processar(java.util.List<Cliente> cliente)
    Em Object voce não possui esse método por isso dá pau! Se fizer cast corrigi o problema:
    ((ICliente)cliente.get(i)).mostraTipo();

    Mas.... se voce passa um Objeto que não implementa ICliente vai dar pau novamente. rs

    Abraço!

    Valeu, eu compreendi o problema da coisa.

    Pode trancar o tópico.

    Obrigado

  10. Salve,

    Vou postar o código para começar:

    //Teste.java
    
    public class Teste
    {
        public static void main(String[] args)
        {
            java.util.List<Cliente> cliente = new java.util.ArrayList<Cliente>();
            
            cliente.add(new ClienteNacional());
            
            cliente.add(new ClienteInternacional());
            
            Processamento.processar(cliente);
            
            cliente = null;
            
        }
    }
    //Processamento.java
    
    public class Processamento
    {
        public static void processar(java.util.List cliente)
        {       
            int i, j;
            for(i = 0, j = cliente.size(); i < j; i++)
            {
                /*
                O erro esta aqui, teoricamente quando chamo 'cliente.get(i)'
                ele não retorna um objeto que pode ser ClienteNacional ou ClienteInternacional 
                que, obrigatóriamente, tem o método implantando definido da interface ICliente.
                
                Só não entendo o porque do erro...
                
                Tá faltando um 'TypeCast' ?
                */
                cliente.get(i).mostraTipo();
            }
        }
    }
    //Cliente.java
    
    public abstract class Cliente
    {
        
    }
    //ClienteNacional.java
    
    public class ClienteNacional extends Cliente implements ICliente
    {
        public ClienteNacional()
        {    
        }
        
        public void mostraTipo()
        {
            System.out.println("Cliente Nacional");
        }
    }
    //ClienteInternacional.java
    
    public class ClienteInternacional extends Cliente implements ICliente
    {
        public ClienteInternacional()
        {    
        }
        
        public void mostraTipo()
        {
            System.out.println("Cliente Internacional");
        }
    }
    //ICliente.java
    
    public interface ICliente
    {
        public void mostraTipo();
    }
    Nâo entendo o motivo do erro abaixo:
    C:\POO\Java>javac *.java
    Processamento.java:18: cannot find symbol
    symbol  : method mostraTipo()
    location: class java.lang.Object
                cliente.get(i).mostraTipo();

    Alguém pode me explicar ?

  11. Salve,

    Ainda dá tempo ? Estou enferrujado, mas acho que nessa ainda posso ajudar.

    Segue código abaixo:

    /*  BIBLIOTECAS */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    /*  ESTRUTURAS E ASSINATURAS  */
    
    struct aluno
    {
        char nome[81];
        int matricula;
        char end[121];
        char tel[21];            
    };
    
    struct aluno* novoAluno();
    void debugAluno( struct aluno* );
    
    /*  IMPLEMENTAÇÕES  */
    
    struct aluno* novoAluno()
    {
      struct aluno* aluno;
      aluno = (struct aluno*) malloc( sizeof( struct aluno ) );
      aluno->matricula = 0;
      aluno->nome[0] = '';
      aluno->end[0] = '';
      aluno->tel[0] = '';
      return aluno;
    }
    
    void debugAluno( struct aluno* aluno )
    {
      printf("\n----------------------------");
      printf("\n aluno->matricula = %d", aluno->matricula); 
      printf("\n aluno->nome      = %s", aluno->nome);
      printf("\n aluno->end       = %s", aluno->end);
      printf("\n aluno->tel       = %s", aluno->tel);
      printf("\n----------------------------");
    }
    
    /*  APLICAÇÃO */
    int main(int argc, char *argv[])
    {
      struct aluno* ursao;
      ursao = novoAluno();
        
      debugAluno( ursao );
      
      system("PAUSE");    
      return 0;
    }

  12. Salve,

    Acredito que seja na query mesmo.

    Experimente o código abaixo:

    select 
        count(distinct p.products_id) as total 
    from 
        products p,
        products_description pd, 
        categories c, 
        products_to_categories p2c 
         left join manufacturers m 
             -- using(manufacturers_id) 
             p.manufacturers_id = m.manufacturers_id
         left join specials s 
                on p.products_id = s.products_id 
    where 
            p.products_status = '1' 
        and 
            p.products_id = pd.products_id 
        and 
            pd.language_id = '4' 
        and 
            p.products_id = p2c.products_id 
        and 
            p2c.categories_id = c.categories_id 
        and 
            (
                    (pd.products_name like '%teste%' or p.products_model like '%teste%' or m.manufacturers_name like '%teste%')
                or
                    (pd.products_name like '%e%' or p.products_model like '%e%' or m.manufacturers_name like '%e%')
                or
                    (pd.products_name like '%10%' or p.products_model like '%10%' or m.manufacturers_name like '%10%') 
            )

×
×
  • Criar Novo...