Desconhecida's avatar

VB5 – ObtemDiferencaMesAno (dataInicial As String, DataFinal As String)

Public Function ObtemDiferencaMesAno(dataIni As String, DataFim As String)

Dim mes    As Integer
Dim Ano    As Integer
Dim mesIni As Integer
Dim mesFim As Integer
Dim anoIni As Integer
Dim anoFim As Integer
Dim Result As String

mesIni = CInt(Mid(dataIni, 1, 2))
mesFim = CInt(Mid(DataFim, 1, 2))
anoIni = CInt(Mid(dataIni, 4, 4))
anoFim = CInt(Mid(DataFim, 4, 4))
Result = " "

If anoIni = anoFim Then
     For mes = mesIni To mesFim Step 1
        If (Result <> "") Then
            Result = Result & ", "
        End If
        If (mes < 10) Then
            Result = Result & "'0" & CStr(mes) & "/" & CStr(anoIni) & "'"
        Else
            Result = Result & "'" & CStr(mes) & "/" & CStr(anoIni) & "'"
        End If
    Next
Else
    For Ano = anoIni To anoFim Step 1
        If (Ano = anoFim) Then
            For mes = mesIni To mesFim Step 1
                If (Result <> "") Then
                    Result = Result & ", "
                End If
                If (mes < 10) Then
                    Result = Result & "'0" & CStr(mes) & "/" & CStr(Ano) & "'"
                Else
                    Result = Result & "'" & CStr(mes) & "/" & CStr(Ano) & "'"
                End If
            Next
        Else
            For mes = mesIni To 12 Step 1
                If (Result <> "") Then
                    Result = Result & ", "
                End If
                If (mes < 10) Then
                    Result = Result & "'0" & CStr(mes) & "/" & CStr(Ano) & "'"
                Else
                    Result = Result & "'" & CStr(mes) & "/" & CStr(Ano) & "'"
                End If
            Next
        End If
    Next
End If

ObtemDiferencaMesAno = Result

End Function

Desconhecida's avatar

VB5 – ObtemProximoMes (DATA As String)

Caso precise consultar o próximo mês em vb5:

Public Function ObtemProximoMes(DATA As String)

Dim mes As Integer
Dim Ano As Integer
Dim Result As String

mes = CInt(Mid(DATA, 1, 2)) + 1
Ano = CInt(Mid(DATA, 4, 4))

If (mes > 12) Then

    Ano = CInt(Mid(DATA, 4, 4)) + 1
    mes = 1

End If

If (mes < 10) Then
    Result = "01/0" & CStr(mes) & "/" & CStr(Ano)
Else
    Result = "01/" & CStr(mes) & "/" & CStr(Ano)
End If

ObtemProximoMes = Result

End Function

Desconhecida's avatar

Visual Basic 6 String Functions

String manipulation

$ReqTestHarness$

VB has numerous built-in string functions for processing strings. Most VB string-handling functions return a string, although some return a number (such as the Len function, which returns the length of a string and functions like Instr and InstrRev, which return a character position within the string). The functions that return strings can be coded with or without the dollar sign ($) at the end, although it is more efficient to use the version with the dollar sign.

The first time I started trying to understand the VB6 string functions I was somewhat confused. This tutorial will walk you through all the different ways you can us VB to handle strings. If you are still confused feel free to post a comment and hopefully we can help get you cleared up. Also there are many other string related tutorials on this site so feel free to browse around.

Function:Len
Description:Returns a Long containing the length of the specified string
Syntax:Len(string)Where string is the string whose length (number of characters) is to be returned.
Example:lngLen = Len(“Visual Basic”) ‘ lngLen = 12
Function:Mid$ (or Mid)
Description:Returns a substring containing a specified number of characters from a string.
Syntax:Mid$(string, start[, length])The Mid$ function syntax has these parts:string Required. String expression from which characters are returned.start Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string (“”).length Optional; Long. Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.
 Example: strSubstr = Mid$(“Visual Basic”, 3, 4) ‘ strSubstr = “sual”Note: Mid$ can also be used on the left side of an assignment statement, where you can replace a substring within a string.strTest = “Visual Basic” Mid$(strTest, 3, 4) = “xxxx” ‘strTest now contains “Vixxxx Basic”In VB6, the Replace$ function was introduced, which can also be used to replace characters within a string.
Function:Left$ (or Left)
Description:Returns a substring containing a specified number of characters from the beginning (left side) of a string.
Syntax:Left$(string, length)The Left$ function syntax has these parts:string Required. String expression from which the leftmost characters are returned.length Required; Long. Numeric expression indicating how many characters to return. If 0, a zero-length string (“”) is returned. If greater than or equal to the number of characters in string, the entire string is returned.
Example:strSubstr = Left$(“Visual Basic”, 3) ‘ strSubstr = “Vis” ‘ Note that the same thing could be accomplished with Mid$: strSubstr = Mid$(“Visual Basic”, 1, 3)
Function:Right$ (or Right)
Description:Returns a substring containing a specified number of characters from the end (right side) of a string.
Syntax:Right$(string, length)The Right$ function syntax has these parts:string Required. String expression from which the rightmost characters are returned.length Required; Long. Numeric expression indicating how many characters to return. If 0, a zero-length string (“”) is returned. If greater than or equal to the number of characters in string, the entire string is returned.
Example:strSubstr = Right$(“Visual Basic”, 3) ‘ strSubstr = “sic” ‘ Note that the same thing could be accomplished with Mid$: strSubstr = Mid$(“Visual Basic”, 10, 3)
Function:UCase$ (or UCase)
Description:Converts all lowercase letters in a string to uppercase. Any existing uppercase letters and non-alpha characters remain unchanged.
Syntax:UCase$(string)
Example:strNew = UCase$(“Visual Basic”) ‘ strNew = “VISUAL BASIC”
Function:LCase$ (or LCase)
Description:Converts all uppercase letters in a string to lowercase. Any existing lowercase letters and non-alpha characters remain unchanged.
Syntax:LCase$(string)
Example:strNew = LCase$(“Visual Basic”) ‘ strNew = “visual basic”
Function:Instr
Description:Returns a Long specifying the position of one string within another. The search starts either at the first character position or at the position specified by the start argument, and proceeds forward toward the end of the string (stopping when either string2 is found or when the end of the string1 is reached).
Syntax:InStr([start,] string1, string2 [, compare])The InStr function syntax has these parts:start Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. The start argument is required if compare is specified.string1 Required. String expression being searched.string2 Required. String expression sought.compare Optional; numeric. A value of 0 (the default) specifies a binary (case-sensitive) search. A value of 1 specifies a textual (case-insensitive) search.
Examples:lngPos = Instr(“Visual Basic”, “a”) ‘ lngPos = 5 lngPos = Instr(6, “Visual Basic”, “a”) ‘ lngPos = 9 (starting at position 6) lngPos = Instr(“Visual Basic”, “A”) ‘ lngPos = 0 (case-sensitive search) lngPos = Instr(1, “Visual Basic”, “A”, 1) ‘ lngPos = 5 (case-insensitive search)
Function:InstrRev
Description:Returns a Long specifying the position of one string within another. The search starts either at the last character position or at the position specified by the start argument, and proceeds backward toward the beginning of the string (stopping when either string2 is found or when the beginning of the string1 is reached).Introduced in VB 6.
Syntax:InStrRev(string1, string2[, start, [, compare]])The InStr function syntax has these parts:string1 Required. String expression being searched.string2 Required. String expression sought.start Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the last character position.compare Optional; numeric. A value of 0 (the default) specifies a binary (case-sensitive) search. A value of 1 specifies a textual (case-insensitive) search.
Examples:lngPos = InstrRev(“Visual Basic”, “a”) ‘ lngPos = 9 lngPos = InstrRev(“Visual Basic”, “a”, 6) ‘ lngPos = 5 (starting at position 6) lngPos = InstrRev(“Visual Basic”, “A”) ‘ lngPos = 0 (case-sensitive search) lngPos = InstrRev(“Visual Basic”, “A”, , 1) ‘ lngPos = 9 (case-insensitive search) ‘ Note that this last example leaves a placeholder for the start argument

Notes on Instr and InstrRev:

·         Something to watch out for is that while Instr and InstrRev both accomplish the same thing (except that InstrRev processes a string from last character to first, while Instr processes a string from first character to last), the arguments to these functions are specified in a different order. The Instr arguments are (start, string1, string2, compare) whereas the InstrRev arguments are (string1, string2, start, compare).

·         The Instr function has been around since the earlier days of BASIC, whereas InstrRev was not introduced until VB 6.

·         Built-in “vb” constants can be used for the compare argument:

vbBinaryCompare for 0 (case-sensitive search)
vbTextCompare for 1 (case-insensitive search)

Function:String$ (or String)
Description:Returns a string containing a repeating character string of the length specified.
Syntax:String$(number, character)The String$ function syntax has these parts:number Required; Long. Length of the returned string.character Required; Variant. This argument can either be a number from 0 to 255 (representing the ASCII character code* of the character to be repeated) or a string expression whose first character is used to build the return string.
Examples:strTest = String$(5, “a”) ‘ strTest = “aaaaa” strTest = String$(5, 97) ‘ strTest = “aaaaa” (97 is the ASCII code for “a”)

* A list of the ASCII character codes is presented at the end of this topic.

Function:Space$ (or Space)
Description:Returns a string containing the specified number of blank spaces.
Syntax:Space$(number)Where number is the number of blank spaces desired.
Examples:strTest = Space$(5) ‘ strTest = ” “
Function:Replace$ (or Replace)
Description:Returns a string in which a specified substring has been replaced with another substring a specified number of times.Introduced in VB 6.
Syntax:Replace$(expressionfindreplacewith[, start[, count[, compare]]])The Replace$ function syntax has these parts:expression Required. String expression containing substring to replace.find Required. Substring being searched for.replacewith Required. Replacement substring.start Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed.count Optional. Number of substring substitutions to perform. If omitted, the default value is –1, which means make all possible substitutions.compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. (0 = case sensitive, 1 = case-insensitive)Built-in “vb” constants can be used for the compare argument:vbBinaryCompare for 0 (case-sensitive search)
vbTextCompare for 1 (case-insensitive search) 
Examples:strNewDate = Replace$(“08/31/2001”, “/”, “-“) ‘ strNewDate = “08-31-2001”
Function:StrReverse$ (or StrReverse)
Description:Returns a string in which the character order of a specified string is reversed.Introduced in VB 6.
Syntax:StrReverse$(string)
Examples:strTest = StrReverse$(“Visual Basic”) ‘ strTest = “cisaBlausiV” 
Function:LTrim$ (or LTrim)
Description:Removes leading blank spaces from a string.
Syntax:LTrim$(string)
Examples:strTest = LTrim$(” Visual Basic “) ‘ strTest = “Visual Basic “
Function:RTrim$ (or RTrim)
Description:Removes trailing blank spaces from a string.
Syntax:RTrim$(string)
Examples:strTest = RTrim$(“Visual Basic”) ‘ strTest = “Visual Basic”
Function:Trim$ (or Trim)
Description:Removes both leading and trailing blank spaces from a string.
Syntax:Trim$(string)
Examples:strTest = Trim$(” Visual Basic “) ‘ strTest = “Visual Basic” ‘ Note: Trim$(x) accomplishes the same thing as LTrim$(RTrim$(x))
Function:Asc
Description:Returns an Integer representing the ASCII character code corresponding to the first letter in a string.
Syntax:Asc(string)
Examples:intCode = Asc(“*”) ‘ intCode = 42 intCode = Asc(“ABC”) ‘ intCode = 65
Function:Chr$ (or Chr)
Description:Returns a string containing the character associated with the specified character code.
Syntax:Chr$(charcode)Where charcode is a number from 0 to 255 that identifies the character.
Examples:strChar = Chr$(65) ‘ strChar = “A”

© VBSCRIPT Tutorial

Desconhecida's avatar

Como recebi terapia reiki online

Primeiro, o fato de estar em casa e deitado na minha cama fez com que me sentisse marta-deneke-terapia-onlinesuper a vontade.  Segundo entrei em um estado meditativo e concentrado que me fez receber o tratamento de maneira completa. Diferente da experiência de receber ao vivo, no online eu estive incrivelmente mais receptivo. Na minha experiência a aplicação Online foi melhor e rendeu melhores resultados.

Quem já fez Reiki anteriormente diz que o atendimento e o resultado é muito similar ao atendimento ao vivo. Contudo as pessoas que nunca fizeram tem comentado que sentem um calor que anda pelo corpo removendo dores e aflições. Quando voltam estão se sentindo uma paz muito grande e um uma consciência restabelecida fixada no presente.

Meu atendimento foi neste site terapiareikionline.com.br

Desconhecida's avatar

RAVEN – Eventual consistência

Trabalho em um projeto cuja uma das necessidades é ter muita velocidade de leitura das informações salvas no banco de dados.
Por conta disso resolvemos optar por um banco de dados no-cicle RAVEN DB. O Banco de dados é extremamente rápido montar querys e views do sistema, o que é ótimo contudo temos que lidar com a eventual consistência.

O que é eventual consistência?
É quando existe um agendamento para uma informação ser salva no banco de dados. Não é instantâneo. Isso é preço de ter como prioridade a leitura e não a persistência.

Como proceder quando preciso de uma informação salva para continuar um processo?
Você deve utilizar uma regra na query que garanta que todos os index foram salvos e gerados no momento da sua consulta.

No RAVENDB utilizo 2 soluções. A boa e a menos boa (ruim).

A boa é criando uma tag e informando ela no método: WaitForNonStaleResultsAsOf.
Conforme exemplo:

public Invoice Load(Guid id)
{
using (var session = _store.Open())
{
var sessionInvoice = session.Load(id);
var etag = session.Advanced.GetEtagFor(sessionInvoice);

return session
.Query()
.Customize(x => x.WaitForNonStaleResultsAsOf(etag))
.Where(i => i.Type == EPersistedInvoice.Invoice && i.Id == id)
.ToList()
.Select(ConvertToInvoice).FirstOrDefault();
}
}

E a ruim é usando o método: WaitForNonStaleResultsAsOfLastWrite(), que espera atualizar todos os index que estão na fila para serem atualizados..

Fonte: https://ravendb.net/docs/article-page/3.5/all/users-issues/understanding-eventual-consistency

Desconhecida's avatar

Multi-linguagem no Angular – exemplos

Pode-se utilizar a biblioteca angular angular-translate para trabalhar com traduções de páginas feitas utilizando angular.

Bower: “angular-translate”: “2.13.0”

Dentro de uma arquitetura de sistema, sabemos que a responsabilidade de exibir as mensagens aos usuários é da tela, e nada mais justo que utilizar uma ferramenta do angular para resolver questões de multi-linguagem.

O principal argumento para responsabilizar a tela pela exibição das mensagens é porque na tela é que se estuda a melhor maneira de se apresentar uma informação, e a mesma informação pode ser exibida de maneiras diferentes em telas diferentes, por exemplo uma informação sendo exibida para celular e para computador.

No código abaixo adicionamos a referência do serviço (pascalprecht.translate) no módulo app e utilizamos a implementação config do angular para que essa configuração seja a primeira executada ao iniciar o sistema. O config do Angular não aceita a injeção de serviços, então para resolver isso usamos um provider ($translateProvider). No config utilizações 2 funções, sendo a primeira translations para informar as traduções e a  preferredLanguage para informar a linguagem padrão.

Segue a implementação em Javascript do código escrito com Angular 1, abaixo:


    var app = angular.module('app', ['pascalprecht.translate']);

    app.config(function ($translateProvider) {

        $translateProvider.translations('pt-br', {
            MENU_TITULO: 'Site',
            MENU_CAPA: 'Página inicial',
            MENU_SOBRE: 'Sobre',
            MENU_CONTATO: 'Contato'
        });

        $translateProvider.translations('en', {
            MENU_TITULO: 'Site',
            MENU_CAPA: 'Home',
            MENU_SOBRE: 'About',
            MENU_CONTATO: 'Contact'
        });

        $translateProvider.preferredLanguage('pt-br');

Segue a implementação em HTML de como usar as traduções, abaixo:

<ul class="nav navbar-nav">
	<li><a href="#">{{ 'MENU_TITULO' | translate }}</a></li>
	<li><a href="#">{{ 'MENU_CAPA' | translate }}</a></li>
	<li><a href="#">{{ 'MENU_SOBRE' | translate }}</a></li>
	<li><a href="#">{{ 'MENU_CONTATO' | translate }}</a></li>
</ul>

Para não complexificar a explicação, vou colocar meu projeto de teste em anexo.

Segue o linque do exemplo para download (zip): http://www.4shared.com/zip/YH5kRblLce/AngularTranslatePlayground.html?

Nesse projeto tenho 2 implementações.
Sendo a primeira e mais simples a que segue o exemplo acima.

E a mais complexa é utilizando cookies para salvar a linguagem selecionada e utilizando API para consultar as traduções por linguagem.
Optei por transitar na API somente 1 linguagem de cada vez por uma questão de desempenho e por salvar a linguagem em cookie pois acredito ser uma boa solução neste caso.

Desconhecida's avatar

Javascript: Exemplo de como adicionar (push) e remover (splice) itens de um Array.

Ao trabalhar com Arrays em Javascript é muito comum ter a necessidade de Adicionar e Remover itens do Array.
Para Adicionar um item deve-se utilizar a função PUSH, onde deve-se utilizar a seguinte sintaxe: arr_nomes.push(valor) onde o arr_nomes é o array e o valor é o item a ser adicionado.
Para Remover um item deve-se utilizar a função SPLICE, onde deve-se utilizar a seguinte sintaxe: arr_nomes.splice(posicao, 1) onde arr_nomes é o array, a posição é o índice a ser removido e o numero 1 é a quantidade de itens a serem excluídos.

Veja o exemplo completo abaixo:

    <div class="container">

        <h2>Adicionar:</h2>
        <p><input type="text" id="addNome" class="form-control" placeholder="Preencher o Nome" /></p>
        <p><button type="button" class="btn btn-default" onclick="Add($('#addNome').val()); $('#addNome').val('');">Adicionar</button></p>

        <h2>Remover:</h2>
        <p><input id="removeNome" type="number" class="form-control" placeholder="Preencher o Índice" /></p>
        <p><button type="button" class="btn btn-default" onclick="Remove($('#removeNome').val()); $('#removeNome').val('');">Remover</button></p>

        <h2>Resultado:</h2>
        <div id="RETORNO" class="row" style="padding: 10px 12px;"></div>
    </div>
        var arr_nomes = ["José", "Roberto", "Maria", "Silva"];
        document.getElementById("RETORNO").innerHTML = arr_nomes;

        function Add(valor) {
            arr_nomes.push(valor);
            document.getElementById("RETORNO").innerHTML = arr_nomes;
        }

        function Remove(posicao) {
            arr_nomes.splice(posicao, 1);
            document.getElementById("RETORNO").innerHTML = arr_nomes;
        }
Desconhecida's avatar

Angular JS – Documentação para Estudo

  • Como iniciar uma aplicação Angular
    • ng-app
    • script do AngularJS
  • Diretivas nativas do Angular
    • ng-app
    • ng-show
    • ng-hide
    • ng-if
    • ng-repeat
    • ng-controller
    • ng-model
    • ng-bind
  • Como escrever variáveis nos templates
    • {{ message }}
  • Controllers
    • app.controller(‘MainCtrl’, function($scope) {
             $scope.message = ‘Message’;
      });
  • $scope e $rootScope
  • $scope.watch

Material de Estudo AngularJS – 01

  • ANGULARJS EVENTS SYSTEM
    • $scope.
    • $on.
    • $emit.
    • $broadcast
  • BUILT-IN SERVICES
    •  $http,
    • $filter,
    • $log, …
  • FILTROS
    • “AngularJS” | uppercase
  •  ANGULAR.CONSTANT E ANGULAR.VALUE
  • DEPENDENCY INJECTION & PROMISES

Material de Estudo AngularJS – 02

  • Como criar serviços
  • HTTP Interceptors
  • angular.run & angular.config
  • Como criar diretivas
  • data-ng-app
  • $q
  • Como criar filtros
  • services vs factories

Material de Estudo AngularJS – 03

Desconhecida's avatar

.Net Mvc C# – Cadastro de Pedido com Itens de Produto ( múltiplos registros )

Para conseguir postar um cadastro com múltiplos registros segui este tutorial:
http://dotnetawesome.blogspot.com.br/2013/09/how-to-update-multiple-row-at-once.html

Conversei com o Cleyton Ferrari e ele sugeriu utilizar AngularJs ou knockoutJS. Eles tornam o serviço mais simples nas interações com os elementos/componentes HTML, principalmente pra ir adicionando itens em uma lista. O Cleyton me indicou este código fonte dele: https://github.com/cleytonferrari/SPAAngularJS?files=1

no meu primeiro teste utilizei a model:

namespace MultiplosIntes.Models
{
    public class Pedido
    {
        [Required(ErrorMessage = "Favor preecher o Número do Pedido!", AllowEmptyStrings = false)]
        public int NumeroPedido { get; set; }
        public IList Itens { get; set; }
    }

    public class ItensPedido
    {
        public ItensPedido()
        {
            this.Produto = "";
            this.Quantidade = 0;
            this.Valor = 0;
        }

        [Required(ErrorMessage = "Favor preecher o Produto!", AllowEmptyStrings = false)]
        public string Produto { get; set; }
        [Required(ErrorMessage = "Favor preecher a Quantidade!", AllowEmptyStrings = false)]
        public int Quantidade { get; set; }
        [Required(ErrorMessage = "Favor preecher o Valor!", AllowEmptyStrings = false)]
        public decimal Valor { get; set; }
    }

}

Controller:

namespace MultiplosIntes.Controllers
{
    public class PedidoController : Controller
    {        
        public ActionResult Cadastrar()
        {
            Pedido pedido = new Pedido(); 
            pedido.Itens = new List();
            pedido.Itens.Add(new ItensPedido { Produto = "", Quantidade = 0, Valor = 0 });

            return View(pedido);
        }

        [HttpPost]
        public ActionResult Cadastrar(Pedido model)
        {
            var teste = model;

            return View(model);
        }
    }
}

View:

@model MultiplosIntes.Models.Pedido
@{
    ViewBag.Title = "Cadastrar";
}

<h2>Cadastrar</h2>

@using (Html.BeginForm())
{
    <table id="dataTable">
        <tr>
            <td>Número</td>
            <td>@Html.TextBoxFor(a=&gt;a.NumeroPedido)</td>
            <td></td>
        </tr>        
        <tr>
            <td>Produto</td>
            <td>Quantidade</td>
            <td>Valor</td>
        </tr>
        @if (Model.Itens != null &amp;&amp; Model.Itens.Count &gt; 0)
        {
            int j = 0;
            foreach (var i in Model.Itens)
            {
                <tr style="border:1px solid black;">
                    <td>@Html.TextBoxFor(a=&gt;a.Itens[j].Produto) @Html.ValidationMessageFor(a=&gt;a.Itens[j].Produto)</td>
                    <td>@Html.TextBoxFor(a=&gt;a.Itens[j].Quantidade) @Html.ValidationMessageFor(a=&gt;a.Itens[j].Quantidade)</td>
                    <td>@Html.TextBoxFor(a=&gt;a.Itens[j].Valor) @Html.ValidationMessageFor(a=&gt;a.Itens[j].Valor)</td>
                    <td>
                        @if (j &gt; 0)
                        {
                            <a href="#" class="remove">Remove</a>
                        }
                    </td>
                </tr>
                j++;
            }
        }
        
        <tr>
            <td colspan="4"></td>
        </tr>
        <tr>
            <td colspan="4"></td>
        </tr>
        <tr>
            <td colspan="4"></td>
        </tr>
    </table>
}
Desconhecida's avatar

.Net Mvc C# – Trabalhando com Json com chamadas Ajax ($.getJSON e $.ajax)

Para trabalhar com Chamadas em Ajax e Json se faz necessário ter adicionado uma biblioteca Jquery.

Usando o Jquery você pode usar tanto a chamada $.getJSON quanto $.ajax, sendo que a primeira é um “resumo” da segunda.

Veja o Exemplo com $.getJSON :

function ConsultarStatusWs() {     
            $.getJSON("../ConsumoWS/JsonStatusWs", null, function (data) {   
                $("#Resultado").html("");
                $("#Resultado").append("<p>Transacoes=" + data.Result.Transacoes + "<br>Consumidas=" + data.Result.Consumidas + "<br>Saldo=" + data.Result.Saldo + "<br></p>");
            });
        }

Para que este exemplo funcione inicializar a função “ConsultarStatusWs()” e ter uma div “div id=”Resultado”/div”, alem é claro do de um include do jquery: “script src=”~/Scripts/jquery-2.0.3.js””

Um exemplo que possui um resultado exatamente igual ao anterior é com o uso do $.ajax:

function ConsultarStatusWsAjax() {
            $.ajax({
                dataType: "json",
                url: "../ConsumoWS/JsonStatusWs",
                success: function (data) {
                    $("#Resultado").html("");
                    $("#Resultado").append("<p>Transacoes=" + data.Result.Transacoes + "<br>Consumidas=" + data.Result.Consumidas + "<br>Saldo=" + data.Result.Saldo + "<br></p>");
                }
            });

Agora veja o Código do Controller ConsumoWS:

namespace STI.Associados.PortalWeb.Controllers
{
    public class ConsumoWSController : STIControllerBase
    {
        private IConsumoWsApp _consumoWsApp;

        public ConsumoWSController()
        {
            this._consumoWsApp = StructureMap.ObjectFactory.GetInstance<IConsumoWsApp>();
        }
        
        public ActionResult Index()
        {

            return PartialView("Index");
        }

        public JsonResult JsonListaConsumoPorMes()
        {
            IList<ConsumoWsDTO> consumo = this._consumoWsApp.GetWSTransacoesTotalisadasPorMes();
            return this.Json(new { Result = consumo }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult JsonStatusWs()
        {
            StatusDTO status = this._consumoWsApp.GetWSStatus();
            return this.Json(new { Result = status }, JsonRequestBehavior.AllowGet);
        }
    }
}

A Action JsonStatusWs retorna o seguinte json:

{"Result":{"Transacoes":1000000,"Consumidas":862,"Saldo":999138}}

E a Action JsonListaConsumoPorMes retorna o seguinte json:

{"Result":[{"Mes":"2","Ano":"2015","Total":190},{"Mes":"3","Ano":"2015","Total":467},{"Mes":"4","Ano":"2015","Total":209}]}

Algumas observações importantes:
1º É interessante sempre utilizar o tipo de result da action “JsonResult”, para que você tenha certeza que essa action retornará somente um código JSON.
2º No return tem o código JsonRequestBehavior.AllowGet que é necessário para que a action receba requisições de qualquer lugar. Sem esse comando é comum encontrar o erro: ” This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet. “.

Veja no Exemplo abaixo como tratar o caso da lista de resultados.
Exemplo:

function ConsultarConsumoWs() {
            $("#Resultado").fadeOut();
            $.getJSON("../ConsumoWS/JsonListaConsumoPorMes", null, function (data) {
                $("#Resultado").fadeIn(); $("#Resultado").html("");
                $.each(data.Result, function (index, valor) {                   
                    $("#Resultado").append("<p>Consumo em " + valor.Mes + "/" + valor.Ano + ": " + valor.Total + " </p>");
                });
            });
        }