domingo, 7 de septiembre de 2014

A1 parametros AJAX contentType dataType, stringify


contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: jsonhtmltext, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
    datatype : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
    datatype : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});
One more - if you want to post:
name=John&age=34
Then don't stringify the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
    datatype : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});
share|edit

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
REFERENCIA:
http://stackoverflow.com/questions/18701282/what-is-content-type-and-datatype-in-an-ajax-request 

Parametros de llamada AJAX jquery bien explicado

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
4 down vote accepted
dataType:
The type of data that you're expecting back from the server.
contentType:
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
----
contentType is used to determine how the payload has to be sent to the server as request parameters or as request body.

dataType is used to tell jQuery what is the return type of the request - to determine how to process the response text before it is sent the the handler methods

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
*****************
From the documentation:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
and:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
http://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
*****************

1.1 Propiedades de los llamados Ajax.

La función Ajax de JQuery recibe un JSON el cuál posee varias propiedades que enumeraremos a continuación.
  • type: Tipo de llamada que se ejecutara por defecto es GET.
  • url: Ruta a la cual se le ejecutara la llamada.
  • data: Datos que se enviaran al servidor, se envía un string con formato de JSON.
  • contentType: Tipo de datos que van a ser enviara al servidor.
  • dataType: Tipo de dato que se espera recibir desde el servidor . Jquery lo interpreta con los MIME types que el soporta. Los valores válidos para esta propiedad son los siguientes: (xml,html,script,json,jsop,text)
  • success:  Función ejecutada cuando la llamada Ajax fue satisfactoria.
  • error: Función a ser ejecutada si la llamada Ajax no fue satisfactoria.
  • async: Propiedad que define si la llamada Ajax es asíncrona o no, por defecto esta propiedad es verdadera.
Estas definiciones serán utilizadas posteriormente y es importante conocer su significado.
- See more at: http://7sabores.com/blog/consumir-un-webservice-net-jquery#sthash.vEl1KKTC.dpuf

http://7sabores.com/blog/consumir-un-webservice-net-jquery
*******************
contentType Se usa cuando se mandan datos a los servidores a modo de encabezado. String: "application/x-www-form-urlencoded" funciona perfectamente
data Se usa para especificar datos a mandar. Estos tienen la siguiente forma: foo=bar&foo2=bar2;. Si los datos a enviar son un vector(array) jQuery los convierte a varios valores con un mismo nombre (si foo["alt1","alt2"], foo="alt1"&foo="alt2";) Array / String con la forma antes mencionada. (un objeto que yo sepa tambien)
dataType Indica el tipo de datos que se van a llamar (YO: que se resiben del servidor). Si no se especifica jQuery automaticamente encontrará el tipo basado en el header del archivo llamado (pero toma mas tiempo en cargar, asi que especificalo u_u)
  • "xml": Devuelve un documento XML.
  • "html": Devuelve HTML con texto plano, y respeta las etiquetas.
  • "script": Evalua el JavaScript y devuelve texto plano.
  • "json": Evalua la respuesta JSON y devuelve un objeto Javascript 
http://www.cristalab.com/tutoriales/ajax-en-jquery-c226l/
*******************
jQuery
Nuestro último cliente será jQuery y lo cierto es que el más sencillo de todos.
La ventaja de jQuery frente a ASP.NET AJAX es que puede consumir servicios que no estén en la solución actual y además tampoco es necesario ningún cambio en el servicio web, es decir, no es necesario descomentar la línea que sí tuvimos que descomentar para trabajar con ASP.NET AJAX.
Además, para proyectos de ASP.NET MVC sólo tenemos disponible está opción
$(document).ready(function () {
    var options = {
        type: "POST",
        url: "/WebService1.asmx/Saludar",
        data: "{ 'nombre': 'Sergio' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //do something...
        },
        error: function (jqXHR, textStatus, errorThrown) { //do something...
        }
    }
    $.ajax(options);
});

Lo más relevante del este código es:
  • Se utiliza JSON para la llamada según indica el parámetro contentType.
  • Se pasan los datos en la propiedad data, de nuevo como un objeto JSON pero en una cadena.
  • El nombre del parámetro es case-sensitive, así que nombre funcionará pero Nombre fallará.
  • Se espera que la respuesta sea en formato JSON según indica el parámetro dataType.
Si quisiéramos llamar al método SaludarPersona que recibe un objeto del tipo Persona, habría que escribir lo siguiente en la propiedad data:
data: "{ 'persona' : { 'Nombre' : 'Sergio' , 'Apellidos' : 'León' } }",

http://panicoenlaxbox.blogspot.com/2011_12_01_archive.html
**************************

http://www.programacionweb.net/articulos/articulo/ajax-en-jquery/

Parámetros de $.ajax()

En el ejemplo vemos una llamada a $.ajax que utiliza el parámetro url, vamos a explicar este y algunos más:
async - Define si es una petición síncrona ( true ) o asíncrona ( false ), por defecto es asíncrona.
data - Los parametros enviados al servidor por POST o GET ( según type ). Puede recibir una cadena de caracteres del tipo "param1=123&param2=456" o un objeto JSON { param1 : 123, param2 : 456 }
type - Define cómo se envían los parámetros del data, puede tener valor GET y POST. Por defecto es GET
url - URL a obtener en la petición.

ArribaFunciones de $.ajax()

Despues de los parametros, se llaman las funciones de $.ajax, en este ejemplo done(), vamos a explicar esta y otras funciones:
always - Función que será llamada al recibir la respuesta correctamente o incorrectamente.
done - Función que será llamada al recibir la respuesta correctamente.
fail - Función que será llamada al producirse un error

http://blog.caplin.com/2012/01/13/javascript-is-hard-part-1-you-cant-trust-arrays/
http://stackoverflow.com/questions/7833806/create-a-single-value-array-in-javascript

llamada ajax interesante pero no funciona

var a = function(callback)
{
    $.ajax({
          url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=immaulikvora&count=1&page=1&include_entities=1&callback=?',
          dataType: 'json',
          async: false,
          success: callback
        });  
};


a(function(data) {
    console.log(data);
    alert(data);
});

sábado, 6 de septiembre de 2014

vsvim


Entendible
http://bencrowder.net/files/vim-fu/

*******************
http://visualstudiomagazine.com/articles/2012/04/09/write-faster-code-by-adding-vim-to-visual-studio.aspx


Simpler Searching
Everything flows from these conventions. VsVim also includes part of VIM search capabilities. When in normal mode, type '/' followed by what you're looking for and press Enter.
A simple example of relocating a method:
  • Start with your cursor at or before the current method
  • Press 'v' to enter visual mode (used for selected ranges of text)
  • Press '}' to move past this block of text (end of the method)
  • Press 'd' to delete (cut)
  • Press '{' twice to move up two methods
  • Press 'p' to paste the method
To start learning VsVim (and VIM), don't start with empty documents. Print off a cheat sheet with commands and read a couple of articles on VIM. Then start programming with VIM. If you don't know how to do something, look it up, execute the command, and try to use it again.
***********

http://en.kioskea.net/faq/982-vi-vim-finding-a-word

[VI/VIM] Finding a word

To find a word in VI / Vim, just type "/" or "?", followed by the word you're searching for. 

Pressing the n key, will allow you to go directly to the next occurrence of the word. 

Another feature is to launch a search on the word where the cursor is positioned. Place the cursor over the word to search for, then press * or # to to look it up.

**************
http://nickmeldrum.com/blog/vsvim-plugin-for-visual-studio
http://www.viemu.com/vi-vim-cheat-sheet.gif
**************

Could I live without it? Easily.
Is it useful? Yes.

Reasons for Learning

  • vi is guaranteed to exist on all Unix systems and exists on most Linux ones as well. That kind of broad coverage makes learning it worth it.
  • It's much quicker to use vi for a sudo edit:
    $ sudo vi
  • Also, GMail uses vi-ish commands for selecting & moving emails around!
You don't have to be a master.
Just learn

The basics:

  • How to switch from command mode to insert mode i
  • How to switch from insert mode to command mode Esc
  • How to navigate up a line in command mode k
  • How to navigate down a line in command mode j
  • How to navigate left a character in command mode h
  • How to navigate right a character l
  • How to save a file :wEnter (write)
  • How to exit without saving (in command mode) :q!Enter
  • How to Undo u
  • How to Redo Ctrl+r
  • You can combine writing and quitting (in command mode): :wqEnter
From there the rest will just make you faster.
--------------
9
This is how I learnt it. Start with the minimum and build a little on it each day. Take the time to learn a slightly better way of achieveing a task. See the "7 habits of highly text editing" for inspiration. –  Ben Mar 1 '09 at 12:42
20
[:][X][Enter] is the same as [:][W][Q][Enter] –  Vitalii Fedorenko May 6 '10 at 14:13
*****************

Comandos "vi" ("vim") de uso frecuente



ESCAbandonar el modo de inclusión de texto para volver
al modo de comandos; también se usa para cancelar
comandos. (Usarlo en caso de duda)
Cntl-FAvanzar una pagina hacia adelante
Cntl-BAvanzar una pagina hacia atrás
Cntl-LRefrescar la pantalla
GCursor al final del fichero
1GCursor al principio del fichero
$Cursor al final de la linea
0 (cero)Cursor al principio de la linea
.
aAñadir texto a continuacion del cursor [TEXTO]
iInsertar texto en la posicion del cursor [TEXTO]
AAñadir texto al final de la linea [TEXTO]
IInsertar texto al principio de la linea [TEXTO]
oAñadir una linea debajo de la del cursor [TEXTO]
OAñadir una linea encima de la del cursor [TEXTO]
uDeshacer el último cambio realizado
:redRehace los cambios deshechos con ''u'' o '':u''
xBorrar un caracter (y ponerlo automaticamente en el ALMACEN)
DBorrar el resto de la linea (a la derecha del cursor)
dwBorrar una palabra (hasta el primer blanco a la dcha. del cursor)
ddBorrar la linea entera
8xBorrar 8 caracteres
2dwBorrar 2 palabras
7ddBorrar 7 lineas
pPoner el contenido del ALMACEN temporal a continuacion del cursor
PPoner el contenido del ALMACEN temporal antes del cursor
sSubstituir un caracter por texto [TEXTO]
15sSubstituir 15 caracteres por texto [TEXTO]
rSubstituir un solo caracter por otro nuevo, sin entar
en modo de TEXTO
RSobreescribir [TEXTO]
JUnir la linea del cursor y la siguiente
i[ENTER]Romper una linea en dos
.Repetir el último cambio realizado
yyPoner la linea presente en el almacen temporal
5yyPoner cinco lineas en el almacen
:wGuardar en el fichero que se esta editando los cambios realizados
(Aconsejable ejecuarlo de vez en cuando)
:w!Idem, forzandolo si fuese necesario.
:w FicheroGuardar en el fichero "Fichero"
:wqGuardar y salir de "vi".
:wq!Idem, forzandolo si fuese necesario.
NOTA: Cada vez que se borra texto, el texto borrado pasa a un ALMACEN temporal, de donde elimina lo que estuviese almacenado previamente.

button en toolbar de data grid kendo

http://www.telerik.com/forums/custom-command-button-in-toolbars
http://jsbin.com/uqalag/1/edit
http://www.telerik.com/clientsfiles/381378_Grid-Good-Buttons.png?sfvrsn=0
http://stackoverflow.com/questions/13364744/how-to-create-custom-delete-destroy-button-command-in-kendo-ui-grid
lado del servidor
http://blog.longle.net/2012/04/13/teleriks-html5-kendo-ui-grid-with-server-side-paging-sorting-filtering-with-mvc3-ef4-dynamic-linq/


remover filtros
http://www.telerik.com/forums/remove-filters-from-data-source