<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bruno Soares &#187; ASP.NET</title>
	<atom:link href="http://blog.bsoares.com.br/category/aspnet/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.bsoares.com.br</link>
	<description></description>
	<lastBuildDate>Tue, 24 Aug 2010 02:39:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Operações binárias</title>
		<link>http://blog.bsoares.com.br/aspnet/operacoes-binarias</link>
		<comments>http://blog.bsoares.com.br/aspnet/operacoes-binarias#comments</comments>
		<pubDate>Tue, 26 May 2009 02:28:09 +0000</pubDate>
		<dc:creator>Bruno Soares</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ActionScript 3.0]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Electronics]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Matemática]]></category>
		<category><![CDATA[Open Hardware]]></category>
		<category><![CDATA[Techology]]></category>

		<guid isPermaLink="false">http://blog.bsoares.com.br/?p=340</guid>
		<description><![CDATA[Ultimamente tenho me deparado com muitos trechos de códigos que utilizam operações binárias, como chaveamento de multiplexador, extração de RGB a partir de um inteiro ou hexadecimal, bitshift para controlar LED Matrix, etc&#8230; E finalmente dei aquela estuda, agora vai ai um post sobre o que resultou o estudo.
Obs.: Os trechos de códigos deste post [...]]]></description>
			<content:encoded><![CDATA[<p>Ultimamente tenho me deparado com muitos trechos de códigos que utilizam <a href="http://en.wikipedia.org/wiki/Bitwise_operation" target="_blank">operações binárias</a>, como chaveamento de <a href="http://pt.wikipedia.org/wiki/Multiplexador" target="_blank">multiplexador</a>, extração de <a href="http://pt.wikipedia.org/wiki/RGB" target="_blank">RGB</a> a partir de um inteiro ou <a href="http://pt.wikipedia.org/wiki/Sistema_hexadecimal" target="_blank">hexadecimal</a>, bitshift para controlar <a href="http://blog.bsoares.com.br/tag/8x8-led-matrix">LED Matrix</a>, etc&#8230; E finalmente dei aquela estuda, agora vai ai um post sobre o que resultou o estudo.</p>
<p>Obs.: Os trechos de códigos deste post foram escritos em <a href="http://blog.bsoares.com.br/tag/as3">ActionScript</a>, mas pode ser aplicado a C, <a href="http://blog.bsoares.com.br/tag/cpp">C++</a>, Java, <a href="http://blog.bsoares.com.br/tag/processing">Processing</a>, <a href="http://blog.bsoares.com.br/tag/php">PHP</a>, entre outras linguagens.</p>
<hr />
• <a href="#introducao">Introdução</a><br />
• Bit Shift<br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-right-shift">Operador >> (bitwise right shift)</a><br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-left-shift">Operador << (bitwise left shift)</a><br />
• Operações Bitwise<br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-and">Operador &#038; (bitwise AND)</a><br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-or">Operador | (bitwise OR)</a><br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-xor">Operador ^ (bitwise XOR)</a><br />
&nbsp;&nbsp;&nbsp;• <a href="#bitwise-not">Operador ~ (bitwise NOT)</a><br />
• Exemplos<br />
&nbsp;&nbsp;&nbsp;• <a href="#extract-rgb">Extraindo o RGB de uma cor</a><br />
&nbsp;&nbsp;&nbsp;• <a href="#multiplexer-4051">Chaveando multiplexador 4051</a><br />
&nbsp;</p>
<hr /><a name="introducao"><strong>Introdução</strong></a><br />
Um operador binário, como o nome sugere, é um operador que trabalha com a representação binária do número, e como normalmente não sabemos a representação binária dos números de cabeça, vamos utilizar a tabela abaixo:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;"> -----------------------
|      BIN |  DEC | HEX |
|-----------------------|
|        1 |    1 |   1 |
|       10 |    2 |   2 |
|       11 |    3 |   3 |
|      100 |    4 |   4 |
|      101 |    5 |   5 |
|      110 |    6 |   6 |
|      111 |    7 |   7 |
|     1000 |    8 |   8 |
|     1001 |    9 |   9 |
|     1010 |   10 |   A |
|     1011 |   11 |   B |
|     1100 |   12 |   C |
|     1101 |   13 |   D |
|     1110 |   14 |   E |
|     1111 |   15 |   F |
|    10000 |   16 |  10 |
|    10001 |   17 |  11 |
|    10010 |   18 |  12 |
|    10011 |   19 |  13 |
|    10100 |   20 |  14 |
|-----------------------|
| 11111111 |  255 |  FF |
 ----------------------- </pre>
<p>A tabela lista os números de 1 à 20 e 255 em três bases diferentes:<br />
• <a href="http://pt.wikipedia.org/wiki/Sistema_bin%C3%A1rio_%28matem%C3%A1tica%29" target="_blank">Binário (BIN)</a><br />
• Decimal (DEC)<br />
• <a href="http://pt.wikipedia.org/wiki/Sistema_hexadecimal" target="_blank">Hexadecimal (HEX)</a></p>
<p>Analisando a tabela podemos concluir que 3d = 11b, 19d = 10011b (as letras d e b significam decimal e binário respectivamente). Lembrando que pode ser utilizada uma calculadora que opere em binário (como a do windows) ou uma alternativa de conversão de bases on-line como está: <a href="http://calculadoraonline.com.br/view/conversao-binario.php" target="_blank">&#8220;Conversão de número binário&#8221;</a>.</p>
<p>Então vamos <strong>deslocar</strong>, <strong>escorregar</strong>, <strong>escovar</strong> alguns bits para entender melhor.</p>
<p>
<hr /><a name="bitwise-right-shift"><strong>Operador >></strong></a><br />
Deslocamento de bits para a direita (bitwise right shift)</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>8 <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 1<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 4</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>8 <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 2<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 2</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>8 <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 3<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 1</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>8 <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 4<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 0</span></div></td></tr></tbody></table></div>
<p>Olhando os números na base decimal faz pouco sentido, ou talvez nenhum sentido, então passamos os números corretos para a base binária e tudo fica mais claro:<br />
8d = 1000b (8 decimal é igual a 1000 em binário), então:<br />
1000b >> 1 (deslocando uma casa para direita) temos o número:<br />
100b que em decimal é 4(dê uma olhada na tabela).</p>
<p>Agora ficou fácil não? Vamos deslocar o número 13:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>13 <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 1<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 6</span></div></td></tr></tbody></table></div>
<p>13 em binário é 1101, deslocando uma casa para a direita (ou removendo 1 bit), fica 110, e 110 é igual a 6 em decimal.</p>
<p>
<hr /><a name="bitwise-left-shift"><strong>Operador <<</strong></a><br />
Deslocamento de bits para a esquerda (bitwise left shift)</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>2 <span style="color: #000066; font-weight: bold;">&lt;&lt;</span> 1<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 4</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>2 <span style="color: #000066; font-weight: bold;">&lt;&lt;</span> 2<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 8</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>2 <span style="color: #000066; font-weight: bold;">&lt;&lt;</span> 3<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// 16</span></div></td></tr></tbody></table></div>
<p>Agora é só seguir o mesmo raciocino já utilizando anteriormente.<br />
Se 2 em base binária é igual a 10 e deslocarmos um bit para esquerda, vamos ganhar mais um zero, ficando com 100 que é igual a 4 em decimal.</p>
<p>
<hr /><a name="bitwise-and"><strong>Operador &#038;</strong></a><br />
AND binário (bitwise AND)<br />
O operador &#038; compara bit a bit os números a sua direita e esquerda, por exemplo o resultado de 10 &#038; 11 é 10:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1010
&#038; 1011
------
  1010</pre>
<p>A comparação bit-a-bit somente retorna True (1) quando os bits comparados são iguais a 1, caso contrário retorna False (0). Formando assim um novo número.<br />
Mais alguns exemplos para fortalecer:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
|14 &#038;  9|13 &#038; 11|20 &#038;  9|14 &#038; 10|89 &#038;  112|45  &#038;  77|255  &#038;  13|112 &#038;  255|
|       |       |       |       |         |         |          |          |
|  1110 |  1101 |  10100|  1110 |  1011001|   101101|  11111111|   1110000|
|&#038; 1001 |&#038; 1011 |&#038;  1001|&#038; 1010 |&#038; 1110000|&#038; 1001101|&#038;     1101|&#038; 11111111|
|  ---- |  ---- |  -----|  ---- |  -------|  -------|  --------|  --------|
|  1000 |  1001 |      0|  1010 |  1010000|     1101|      1101|   1110000|
|    8d |    9d |     0d|   10d |      80d|      13d|       13d|      112d|</pre>
<p>
<hr /><a name="bitwise-or"><strong>Operador |</strong></a><br />
OR binário (bitwise OR)<br />
O operador | tem a mesma função do operador OR comum (||) só que atua bit-a-bit, assim como os outros operadores binários. Vejamos um exemplo:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1010
| 1011
------
  1011</pre>
<p>Se um dos bits comparados forem iguais a 1 a expressão retornará 1, caso os dois bits comparados forem iguais a 0, a expressão retorna 0. Agora vamos refazer o exemplo anterior trocando apenas o operador &#038; (and binário) por | (or binário):</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
|14 |  9|13 | 11|20 |  9|14 | 10|89 |  112|45  |  77|255  |  13|112 |  255|
|       |       |       |       |         |         |          |          |
|  1110 |  1101 |  10100|  1110 |  1011001|   101101|  11111111|   1110000|
|| 1001 || 1011 ||  1001|| 1010 || 1110000|| 1001101||     1101|| 11111111|
|  ---- |  ---- |  -----|  ---- |  -------|  -------|  --------|  --------|
|  1111 |  1111 |  11101|  1110 |  1111001|  1101101|  11111111|  11111111|
|   15d |   15d |    29d|   14d |     121d|     109d|      255d|      255d|</pre>
<p>
<hr /><a name="bitwise-xor"><strong>Operador ^</strong></a><br />
OU exclusivo (bitwise XOR)<br />
A letra X na frente do OR significa Exclusive (Exclusive OR). Isso quer dizer que este operador faz a comparação binária de dois números e resulta os bits que são diferentes. Por exemplos, quais são os bits diferentes entre os números 10 e 11?</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1010
^ 1011
------
     1</pre>
<p>Vamos novamente trocar o operador do exemplo anterior para analisar os resultados:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
|14 ^  9|13 ^ 11|20 ^  9|14 ^ 10|89 ^  112|45  ^  77|255  ^  13|112 ^  255|
|       |       |       |       |         |         |          |          |
|  1110 |  1101 |  10100|  1110 |  1011001|   101101|  11111111|   1110000|
|^ 1001 |^ 1011 |^  1001|^ 1010 |^ 1110000|^ 1001101|^     1101|^ 11111111|
|  ---- |  ---- |  -----|  ---- |  -------|  -------|  --------|  --------|
|   111 |   110 |  11101|   100 |   101001|  1100000|  11110010|  10001111|
|    7d |    6d |    29d|    4d |      41d|      96d|      242d|      143d|</pre>
<p>
<hr /><a name="bitwise-not"><strong>Operador ~</strong></a><br />
Negação (bitwise NOT)<br />
O operador NOT inverte o sinal e complementa em um.<br />
Negando o número 168 (~168) teremos -169.</p>
<p>Alguns exemplos:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~</span>7<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> &nbsp; <span style="color: #009900; font-style: italic;">// -8</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~-</span>7<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> &nbsp;<span style="color: #009900; font-style: italic;">// 6</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~</span>14<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> &nbsp;<span style="color: #009900; font-style: italic;">// -15</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~</span>13<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> &nbsp;<span style="color: #009900; font-style: italic;">// -14</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~</span>255<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// -256</span><br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #000066; font-weight: bold;">~</span>112<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span> <span style="color: #009900; font-style: italic;">// -113</span></div></td></tr></tbody></table></div>
</p>
<p>&nbsp;</p>
<hr /><a name="extract-rgb"><strong>Extraindo o RGB de uma cor</strong></a><br />
Sabendo que uma cor no formato RGB utiliza dois dígitos hexadecimais para definir quanto existe de Vermelho, Verde e Azul (respectivamente), formando cores como: Vermelho (FF0000), Cinza (C0C0C0), Laranja (FF9900), etc. Temos ai a possibilidade de gerar 16.581.375 de cores com este código, é só fazer a conta para conferir: 255 * 255 * 255 ou FF * FF * FF.<br />
Vamos desmembrar um tom de azul (<strong><font color="#347BB7">#347BB7</font></strong>) para saber quanto esta cor tem de Vermelho, Verde e Azul (o valor dos canais RGB).</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900; font-style: italic;">// DEC: 3439543</span><br />
<span style="color: #009900; font-style: italic;">// BIN: 1101000111101110110111</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">color</span><span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = 0x347BB7<span style="color: #000066; font-weight: bold;">;</span><br />
<br />
<span style="color: #6699cc; font-weight: bold;">var</span> r<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000;">&#40;</span><span style="color: #004993;">color</span> <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> 16<span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">&amp;</span> 0xFF<span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> g<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000;">&#40;</span><span style="color: #004993;">color</span> <span style="color: #000066; font-weight: bold;">&gt;&gt;</span> &nbsp;8<span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">&amp;</span> 0xFF<span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">b</span><span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = &nbsp;<span style="color: #004993;">color</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">&amp;</span> 0xFF<span style="color: #000066; font-weight: bold;">;</span><br />
<br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Red:&quot;</span><span style="color: #000066; font-weight: bold;">,</span> r<span style="color: #000066; font-weight: bold;">,</span> <span style="color: #990000;">&quot;Green:&quot;</span><span style="color: #000066; font-weight: bold;">,</span> g<span style="color: #000066; font-weight: bold;">,</span> <span style="color: #990000;">&quot;Blue:&quot;</span><span style="color: #000066; font-weight: bold;">,</span> <span style="color: #004993;">b</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #009900; font-style: italic;">// Red: 52 Green: 123 Blue: 183</span></div></td></tr></tbody></table></div>
<p>Linha 5) Deslocando 16 bits para a direita temos:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1101000111101110110111 >> 16
=                 110100 (DEC: 52)</pre>
<p>Para o caso do vermelho não precisamos continuar a expressão (&#038; 0xFF),<br />
pois deslocando 16 bits para a direita já temos o resultado do vermelho,<br />
mas se a cor estivesse no formato ARGB (Alpha Red Green Blue), seria necessário.</p>
<p>Linha 6) Deslocando 8 bits para conseguir o verde:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1101000111101110110111 >> 8
=         11010001111011 (DEC: 13435)</pre>
<p>Só com o valor do deslocamentos não vamos conseguir a cor verde, então utilizamos o<br />
operador &#038; (AND) com o valor 255 (0xFF) para extrair a parte binária que nos interessa:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  11010001111011 (DEC: 13435)
&#038;       11111111 (DEC: 255, HEX: 0xFF)
  --------------
        01111011 (DEC: 123)</pre>
<p>Linha 7) Para extrair o azul não precisamos deslocar bits e sim pegar os últimos 8 bits:</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1101000111101110110111
&#038;               11111111 (DEC: 255, HEX: 0xFF)
  ----------------------
                10110111 (DEC: 183)</pre>
<p>Agora voltando para o hexadecimal:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #6699cc; font-weight: bold;">var</span> r<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000; font-weight:bold;">52</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> g<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000; font-weight:bold;">123</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">b</span><span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000; font-weight:bold;">183</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> <span style="color: #004993;">color</span><span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=uint%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:uint.html"><span style="color: #004993;">uint</span></a> = <span style="color: #000000;">&#40;</span>r <span style="color: #000066; font-weight: bold;">&lt;&lt;</span> 16<span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">|</span> <span style="color: #000000;">&#40;</span>g <span style="color: #000066; font-weight: bold;">&lt;&lt;</span> 8<span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">|</span> <span style="color: #004993;">b</span><span style="color: #000066; font-weight: bold;">;</span><br />
<br />
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #004993;">color</span><span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">toString</span><span style="color: #000000;">&#40;</span>16<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #009900; font-style: italic;">// 347bb7</span></div></td></tr></tbody></table></div>
<p>Linha 4) Deslocando 16 bits para a esquerda do número 52 (Vermelho):</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  110100 << 16
= 1101000000000000000000</pre>
<p>Deslocando 8 bits para a esquerda do número 123 (Verde):</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1111011 << 8
= 111101100000000</pre>
<p>Efetuando o OR (|) com o resultado das duas operações ((r << 16) | (g << 8)):</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1101000000000000000000
|        111101100000000
  ----------------------
  1101000111101100000000</pre>
<p>Efetuando a última operação, o OR com o Azul (183)</p>
<pre style="font-family: 'Lucida Console', 'Courier New', 'Courier'; font-size: 10px; line-height: 10px;">
  1101000111101100000000
| 0000000000000010110111
  ----------------------
  1101000111101110110111</pre>
<p>O resultado agora ficou claro. O número 1101000111101110110111 (binário) é igual a 3439543 (decimal) e 347BB7 (hexadecimal).</p>
<p>&nbsp;</p>
<hr /><a name="multiplexer-4051"><strong>Chaveando multiplexador 4051</strong></a><br />
A tarefa de chavear um Multiplexador / Demultiplexador (MUX / DEMUX) 4051 é muito parecida com a extração dos canais RGB de uma cor. Você só precisa Ligar ou Desligar três pinos de seleção (select pins) para que o circuito interprete o valor gerado e transmita a voltagem da entrada desejada.<br />
Existe um gif animado do <a href="http://www.rogercom.com" target="_blank">RogerCom</a> muito didático que demonstra o funcionamento do CI 4051, <a href="http://blog.bsoares.com.br/wp-content/uploads/2009/05/animacd4051b.gif" rel="shadowbox[post-340];player=img;" target="_blank">gif animado CI 4051 aqui</a>.<br />
Por exemplo, para ler a entrada 3, precisamos desligar o pino de seleção 0, ligar o 1 e o 2, formando assim o número 011 (binário) que é igual a 3 em decimal. Veja no código (Escrito em Arduino / C++):</p>
<div class="codecolorer-container cpp mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666;">// Entrada desejada</span><br />
<span style="color: #0000ff;">int</span> count <span style="color: #000080;">=</span> <span style="color: #0000dd;">3</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #666666;">// Extração dos bits ativos</span><br />
byte s0 <span style="color: #000080;">=</span> &nbsp;count &nbsp; &nbsp; &nbsp; <span style="color: #000040;">&amp;</span> <span style="color: #208080;">0x1</span><span style="color: #008080;">;</span><br />
byte s1 <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>count <span style="color: #000080;">&gt;&gt;</span> 1<span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;</span> <span style="color: #208080;">0x1</span><span style="color: #008080;">;</span><br />
byte s2 <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>count <span style="color: #000080;">&gt;&gt;</span> 2<span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;</span> <span style="color: #208080;">0x1</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #666666;">// Ligando ou desligando os pinos de seleção</span><br />
digitalWrite<span style="color: #008000;">&#40;</span>2, s0<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
digitalWrite<span style="color: #008000;">&#40;</span>3, s1<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
digitalWrite<span style="color: #008000;">&#40;</span>4, s2<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<hr /><strong>Conteúdo relacionado:</strong><br />
• <a href="http://en.wikipedia.org/wiki/Bitwise_operation" target="_blank">Bitwise operation on Wikipedia</a><br />
&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bsoares.com.br/aspnet/operacoes-binarias/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JPEG Encoder (AS3) + FluorineFx .NET Flash Remoting Gateway</title>
		<link>http://blog.bsoares.com.br/remoting/jpeg-encoder-as3-fluorinefx-net-flash-remoting-gateway</link>
		<comments>http://blog.bsoares.com.br/remoting/jpeg-encoder-as3-fluorinefx-net-flash-remoting-gateway#comments</comments>
		<pubDate>Mon, 18 Feb 2008 05:14:48 +0000</pubDate>
		<dc:creator>Bruno Soares</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ActionScript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Remoting]]></category>
		<category><![CDATA[AMF]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FluorineFx]]></category>
		<category><![CDATA[JPGEncoder]]></category>
		<category><![CDATA[Techology]]></category>

		<guid isPermaLink="false">http://blog.bsoares.com.br/?p=27</guid>
		<description><![CDATA[
Vamos entender neste post como o flash cria um jpeg e o envia através do FluorineFx para o servidor para que o servidor possa trabalhar o dado binário e salvar como um arquivo .JPG.
Não vamos entrar em detalhes da instalação e nem da configuração básica de um site com FluorineFx, pois no próprio site do [...]]]></description>
			<content:encoded><![CDATA[<div>
<div>Vamos entender neste post como o flash cria um jpeg e o envia através do <a href="http://www.fluorinefx.com/" target="_blank">FluorineFx</a> para o servidor para que o servidor possa trabalhar o dado binário e salvar como um arquivo .JPG.</p>
<p>Não vamos entrar em detalhes da instalação e nem da configuração básica de um site com FluorineFx, pois no próprio site do FluorineFx existe um ótimo tutorial para esta configuração inicial (<a href="http://www.fluorinefx.com/docs/fluorine/vswizardnet20.html" target="_blank">FluorineFx Visual Studio 2005 Wizard</a>).</p>
<p>Em primeiro lugar, que fique entendido que a responsabilidade de gerar a imagem é do Flash, e o servidor deve apenas receber os binários para gravar em disco. Para gerarmos o código da imagem (<span style="font-weight: bold;">binário</span>), vamos utilizar a classe <span style="font-weight: bold;">JPEGEncoder</span>.<br />
Exemplo:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.display</span><span style="color: #000066; font-weight: bold;">.</span><a href="http://www.google.com/search?q=bitmapdata%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bitmapdata.html"><span style="color: #004993;">BitmapData</span></a><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.utils</span><span style="color: #000066; font-weight: bold;">.</span><a href="http://www.google.com/search?q=bytearray%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bytearray.html"><span style="color: #004993;">ByteArray</span></a><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #0033ff; font-weight: bold;">import</span> JPEGEncoder<span style="color: #000066; font-weight: bold;">;</span><br />
<br />
<span style="color: #6699cc; font-weight: bold;">var</span> bmpData <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=bitmapdata%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bitmapdata.html"><span style="color: #004993;">BitmapData</span></a> = <span style="color: #0033ff; font-weight: bold;">new</span> <a href="http://www.google.com/search?q=bitmapdata%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bitmapdata.html"><span style="color: #004993;">BitmapData</span></a><span style="color: #000000;">&#40;</span><span style="color: #004993;">width</span><span style="color: #000066; font-weight: bold;">,</span> <span style="color: #004993;">height</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
bmpData<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">draw</span><span style="color: #000000;">&#40;</span>MEU_MOVIECLIP<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> objJPEGEncoder <span style="color: #000066; font-weight: bold;">:</span> JPEGEncoder = <span style="color: #0033ff; font-weight: bold;">new</span> JPEGEncoder<span style="color: #000000;">&#40;</span>QUALIDADE<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #6699cc; font-weight: bold;">var</span> dadosEncode <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=bytearray%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bytearray.html"><span style="color: #004993;">ByteArray</span></a> = objJPEGEncoder<span style="color: #000066; font-weight: bold;">.</span>encode<span style="color: #000000;">&#40;</span>bmpData<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span></div></td></tr></tbody></table></div>
<p>Muito simples não? O método draw da classe <span style="font-weight: bold;">BitmapData</span> obtém a imagem atual do clip, criamos uma instância da JPEGEncoder já passando a qualidade (0 à 100) e por fim “encodamos” o BitmapData utilizando o método encode da nossa instância da JPEGEncoder, ele nos retorna um Array de Bytes (<span style="font-weight: bold;">flash.utils.ByteArray</span>).</p>
<p>Agora ficou simples, temos em mãos o array de bytes, podemos enviar ele para o servidor para que o mesmo possa fazer sua parte, que nada mais é que salvar estes bytes em um arquivo. Utilizando o FluorineFx fica fácil, veja o código abaixo:</p>
<div class="codecolorer-container csharp mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;height:500px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br /></div></td><td><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Drawing</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">FluorineFx</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">FluorineFx.AMF3</span><span style="color: #008000;">;</span><br />
<br />
<span style="color: #0600FF;">namespace</span> ServiceLibrary.<span style="color: #0000FF;">Imagem</span><br />
<span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #000000;">&#91;</span>RemotingService<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Comentário da classe&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span><br />
&nbsp; &nbsp;<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> JpegEncoder<br />
&nbsp; &nbsp;<span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Salvar<span style="color: #000000;">&#40;</span>ByteArray byteArray<span style="color: #000000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #008080; font-style: italic;">// Transfere de ByteArray para MemoryStream</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #FF0000;">uint</span> length <span style="color: #008000;">=</span> byteArray.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> bytes <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>length<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byteArray.<span style="color: #0000FF;">ReadBytes</span><span style="color: #000000;">&#40;</span>bytes, 0, length<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;MemoryStream stream <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> MemoryStream<span style="color: #000000;">&#40;</span>bytes<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #008080; font-style: italic;">// Cria a imagem</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Image image <span style="color: #008000;">=</span> Bitmap.<span style="color: #0000FF;">FromStream</span><span style="color: #000000;">&#40;</span>stream<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #008080; font-style: italic;">// Salva a imagem</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;image.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;HttpContext.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">Server</span>.<span style="color: #0000FF;">MapPath</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;_upload/JpegEncoder.jpg&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #008080; font-style: italic;">// Libera o espaço na memória</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;stream.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;image.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000000;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #000000;">&#125;</span><br />
<span style="color: #000000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Este código deve ser inserido dentro da ServiceLibrary que você criou para a sua Solution.</p>
<p>Repare na classe ByteArray, é uma implementação do ByteArray do Flash no servidor, provida pelo FluorineFx.AMF3.</p>
<p>Sua Solution Explorer deve se parecer um pouco com esta:</p>
<p><a href="http://4.bp.blogspot.com/_qLU3RxFHN9w/R7rKlsBl3WI/AAAAAAAAAF4/Kv8k9BKPfAs/s1600-h/SolutionExplorer.gif" rel="shadowbox[post-27];player=img;"><img id="BLOGGER_PHOTO_ID_5168666271182871906" src="http://4.bp.blogspot.com/_qLU3RxFHN9w/R7rKlsBl3WI/AAAAAAAAAF4/Kv8k9BKPfAs/s320/SolutionExplorer.gif" border="0" alt="" /></a></p>
<p>Deixei selecionadas as referências para System.Drawing e Web propositalmente, pois são referências necessárias para o funcionamento da nossa classe.</p>
<p>Agora vamos a parte do envio do ByteArray criado no Flash apartir da JPEGEncoder para a nossa classe la no FluorineFx, a ServiceLibrary.Imagem.JpegEncoder. No exemplo anexo ao post (mais ao fim do post tem um link para download) utilizei uma classe que criei a pouco tempo para trabalhar com AMF no geral (br.com.bsoares.net.Amf), ela vai tomar muito espaço no post, portanto vou demonstrar somente a utilização dela:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;height:500px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #3f5fbf;">/**<br />
* Função de callback para JpegEncoder.Salvar<br />
* @param resposta<br />
*/</span><br />
<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> baixarSusseco <span style="color: #000000;">&#40;</span>resposta <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=object%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:object.html"><span style="color: #004993;">Object</span></a><span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">:</span> <span style="color: #0033ff; font-weight: bold;">void</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp;UtilNet<span style="color: #000066; font-weight: bold;">.</span>navegar<span style="color: #000000;">&#40;</span>Config<span style="color: #000066; font-weight: bold;">.</span>URL_UPLOAD <span style="color: #000066; font-weight: bold;">+</span> <span style="color: #990000;">&quot;JpegEncoder.jpg&quot;</span><span style="color: #000066; font-weight: bold;">,</span> <span style="color: #990000;">&quot;_blank&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span><br />
<br />
<span style="color: #3f5fbf;">/**<br />
* Função de callback para JpegEncoder.Salvar<br />
* @param resposta<br />
*/</span><br />
<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> baixarErro <span style="color: #000000;">&#40;</span>resposta <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=object%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:object.html"><span style="color: #004993;">Object</span></a><span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">:</span> <span style="color: #0033ff; font-weight: bold;">void</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;--&amp;amp;lt; ERRO &amp;amp;gt;----------------------&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #0033ff; font-weight: bold;">each</span> <span style="color: #000000;">&#40;</span><span style="color: #6699cc; font-weight: bold;">var</span> o <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=object%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:object.html"><span style="color: #004993;">Object</span></a> <span style="color: #0033ff; font-weight: bold;">in</span> resposta<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span>o<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;<span style="color: #000000;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;--------------------------------&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span><br />
<br />
<span style="color: #3f5fbf;">/**<br />
* Retorna o ByteArray gerado pela JPEGEncoder<br />
* @return Byte Array<br />
*/</span><br />
<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> obterByteArray <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=bytearray%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bytearray.html"><span style="color: #004993;">ByteArray</span></a> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #6699cc; font-weight: bold;">var</span> bmpData <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=bitmapdata%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bitmapdata.html"><span style="color: #004993;">BitmapData</span></a> = <span style="color: #0033ff; font-weight: bold;">new</span> <a href="http://www.google.com/search?q=bitmapdata%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bitmapdata.html"><span style="color: #004993;">BitmapData</span></a><span style="color: #000000;">&#40;</span>_flvPlayer<span style="color: #000066; font-weight: bold;">.</span>msk<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">width</span><span style="color: #000066; font-weight: bold;">,</span> _flvPlayer<span style="color: #000066; font-weight: bold;">.</span>msk<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">height</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;bmpData<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">draw</span><span style="color: #000000;">&#40;</span>_alvoCaptura<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;<span style="color: #6699cc; font-weight: bold;">var</span> objJPEGEncoder <span style="color: #000066; font-weight: bold;">:</span> JPEGEncoder = <span style="color: #0033ff; font-weight: bold;">new</span> JPEGEncoder<span style="color: #000000;">&#40;</span>_qualidade<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">value</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;<span style="color: #6699cc; font-weight: bold;">var</span> dadosEncode <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=bytearray%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:bytearray.html"><span style="color: #004993;">ByteArray</span></a> = objJPEGEncoder<span style="color: #000066; font-weight: bold;">.</span>encode<span style="color: #000000;">&#40;</span>bmpData<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;<span style="color: #0033ff; font-weight: bold;">return</span> dadosEncode<span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span><br />
<br />
<span style="color: #3f5fbf;">/**<br />
* Chama o método Salvar da Classe JpegEncoder utilizando o FluorineFx.<br />
* Neste exemplo, criei uma classe chamada AMF para tratar a comunicação<br />
* com o FluorineFx (serve também para AMFPHP)<br />
* @param Evento<br />
*/</span><br />
<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> onBaixarClick <span style="color: #000000;">&#40;</span>e <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=mouseevent%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:mouseevent.html"><span style="color: #004993;">MouseEvent</span></a><span style="color: #000000;">&#41;</span> <span style="color: #000066; font-weight: bold;">:</span> <span style="color: #0033ff; font-weight: bold;">void</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #6699cc; font-weight: bold;">var</span> objAmf <span style="color: #000066; font-weight: bold;">:</span> Amf = <span style="color: #0033ff; font-weight: bold;">new</span> Amf<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;objAmf<span style="color: #000066; font-weight: bold;">.</span>URL = Config<span style="color: #000066; font-weight: bold;">.</span>URL_AMF_GATEWAY<span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;objAmf<span style="color: #000066; font-weight: bold;">.</span>onSusseco = baixarSusseco<span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;objAmf<span style="color: #000066; font-weight: bold;">.</span>onErro = baixarErro<span style="color: #000066; font-weight: bold;">;</span><br />
&nbsp; &nbsp;objAmf<span style="color: #000066; font-weight: bold;">.</span>executar<span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;ServiceLibrary.Imagem.JpegEncoder.Salvar&quot;</span><span style="color: #000066; font-weight: bold;">,</span> obterByteArray<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Pelo comentário de cada método já podemos perceber como funciona o envio do Array de bytes.</p>
<p><span style="font-weight: bold;">Dicas:</span><br />
• Neste projeto utilizei o <a href="http://osflash.org/flashdevelop" target="_blank">FlashDevelop</a>, que na minha opinião é um ótimo editor de Action Script.<br />
• Observe a estrutura de classes, para quem ainda não entende muito de POO (Programação Orientada a Objetos) este post é um bom exemplo de organização de Packages e Nomenclatura de Variáveis, Classes e Métodos. Vou tentar em um próximo post escrever mais sobre Programação Orientada a Objetos (POO) de uma forma mais avançada abrangendo Encapsulamento, Herança e Polimorfismo, o qual não é o objetivo deste post).</p>
<p><span style="font-weight: bold;">Observações de Configuração:</span><br />
Observe na imagem abaixo o projeto aberto no FlashDevelop:</p>
<p><a href="http://1.bp.blogspot.com/_qLU3RxFHN9w/R7pOa8Bl3UI/AAAAAAAAAFo/3KL2o4pvLv0/s1600-h/FlashDevelop_Project.gif" rel="shadowbox[post-27];player=img;" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img id="BLOGGER_PHOTO_ID_5168529747057433922" style="cursor: pointer;" src="http://1.bp.blogspot.com/_qLU3RxFHN9w/R7pOa8Bl3UI/AAAAAAAAAFo/3KL2o4pvLv0/s320/FlashDevelop_Project.gif" border="0" alt="" /></a></p>
<p>Clique com o botão direito do mouse sobre <span style="font-weight: bold;">JPEG_Encoder (AS3)</span>, vá em Properties, repare que na área <span style="font-weight: bold;">Project Classpaths</span> deve ser adicionado os dois diretórios (_Biblioteca_ e Classes).</p>
<p><span style="font-weight: bold;">Conclusão:</span><br />
Vimos como é possível o Flash gerar uma imagem (JPEG) utilizando a classe JPEGEncoder, como enviamos os binários do JPEG para o ASP.NET utilizando o FluorineFx e como o FluorineFx salva os binários em disco.</p>
<p>Por hoje é isso pessoal.<br />
Vocês podem fazer o <a href="http://blog.bsoares.com.br/articles/jpegencoder_fluorinefx/download.zip" target="_blank">download do projeto aqui</a>.</p>
<p><span style="font-weight: bold;">Links relacionados:</span><br />
• FluorineFx: <a href="http://www.fluorinefx.com/" target="_blank">http://www.fluorinefx.com/</a><br />
• FluorineFx download: <a href="http://www.fluorinefx.com/download.html" target="_blank">http://www.fluorinefx.com/download.html</a><br />
• FluorineFx Visual Studio: <a href="http://www.fluorinefx.com/docs/fluorine/vswizardnet20.html" target="_blank">http://www.fluorinefx.com/docs/fluorine/vswizardnet20.html</a><br />
• Live JPEG Encoder: <a href="http://www.bytearray.org/?p=26" target="_blank">http://www.bytearray.org/?p=26</a><br />
• PNG Encoder in AS3: <a href="http://www.kaourantin.net/2005/10/png-encoder-in-as3.html" target="_blank">http://www.kaourantin.net/2005/10/png-encoder-in-as3.html</a><br />
• FlashDevelop: <a href="http://osflash.org/flashdevelop" target="_blank">http://osflash.org/flashdevelop</a></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bsoares.com.br/remoting/jpeg-encoder-as3-fluorinefx-net-flash-remoting-gateway/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fluorine, uma alternativa de Flash Remoting com ASP.NET</title>
		<link>http://blog.bsoares.com.br/remoting/fluorine-uma-alternativa-de-flash-remoting-com-aspnet</link>
		<comments>http://blog.bsoares.com.br/remoting/fluorine-uma-alternativa-de-flash-remoting-com-aspnet#comments</comments>
		<pubDate>Sat, 02 Feb 2008 05:01:31 +0000</pubDate>
		<dc:creator>Bruno Soares</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ActionScript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Remoting]]></category>
		<category><![CDATA[AMF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FluorineFx]]></category>
		<category><![CDATA[JPGEncoder]]></category>
		<category><![CDATA[Techology]]></category>

		<guid isPermaLink="false">http://blog.bsoares.com.br/?p=20</guid>
		<description><![CDATA[Nos tempos em que o Flash ainda era da Macromedia, foi criada a especificação AMF (ActionScript Message Format), para facilitar a comunicação entre o ActionScript e as demais linguagens Server-side (Gateway, mais a diante vamos ver que o que controla a comunicação entre o ActionScript e o ASP.NET é com.TheSilentGroup.Fluorine.FluorineGateway). Temos hoje várias linguagem com [...]]]></description>
			<content:encoded><![CDATA[<p>Nos tempos em que o Flash ainda era da Macromedia, foi criada a especificação AMF (ActionScript Message Format), para facilitar a comunicação entre o ActionScript e as demais linguagens <a href="http://pt.wikipedia.org/wiki/Server-side">Server-side</a> (<a href="http://pt.wikipedia.org/wiki/Gateway">Gateway</a>, mais a diante vamos ver que o que controla a comunicação entre o ActionScript e o ASP.NET é com.TheSilentGroup.Fluorine.FluorineGateway). Temos hoje várias linguagem com alguma biblioteca que implemente AMF como por exemplo o PHP, Java, ColdFusion e também o ASP.NET. Existe uma alternativa de remoting muito boa para quem trabalha com PHP que é o <a href="http://www.amfphp.org/">AMFPHP</a>, para quem o conhece será fácil entender o funcionamento do <a href="http://fluorine.thesilentgroup.com/fluorine/download.html">Fluorine</a>. E para quem não o conhece tenho certeza de que vão encontrar muito material sobre ele na Internet.</p>
<p>Hoje em dia já estamos na versão 3 da AMF e a Fluorine também implementa bibliotecas para uso desta versão de AMF.</p>
<p>Vamos ao tutorial.</p>
<p>Nosso primeiro passo será o download do Fluorine no link a seguir: <a href="http://fluorine.thesilentgroup.com/fluorine/download.html">http://fluorine.thesilentgroup.com/fluorine/download.html</a><br />
Não vou dar detalhes da instalação porque é sempre a mesma coisa de Next, Next e Finish.</p>
<p>Após realizada a instalação do Fluorine, vamos abrir o Visual Studio e criar uma nova aplicação web<span id="0" class="transl_class" title="Click to correct">।</span> File -&gt; New -&gt; Web Site, selecione <span style="font-weight: bold;">Fluorine ASP.NET Web Application</span>, como mostrado na figura seguinte:</p>
<p><a rel="lightbox[roadtrip]" href="http://4.bp.blogspot.com/_qLU3RxFHN9w/R6PtUskUCAI/AAAAAAAAAEg/S-za1SwkKfk/s1600-h/Fluorine_01_new_web_site.gif"><img id="BLOGGER_PHOTO_ID_5162230537713354754" style="cursor: pointer;" src="http://4.bp.blogspot.com/_qLU3RxFHN9w/R6PtUskUCAI/AAAAAAAAAEg/S-za1SwkKfk/s320/Fluorine_01_new_web_site.gif" border="0" alt="" /></a></p>
<p>Sua <span style="font-weight: bold;">Solution Explorer</span> deve se parecer com esta imagem:</p>
<p><a rel="lightbox[roadtrip]" href="http://1.bp.blogspot.com/_qLU3RxFHN9w/R6PuK8kUCBI/AAAAAAAAAEo/H9K4iwXoCfo/s1600-h/Fluorine_02_solution_explorer.gif"><img id="BLOGGER_PHOTO_ID_5162231469721258002" style="cursor: pointer;" src="http://1.bp.blogspot.com/_qLU3RxFHN9w/R6PuK8kUCBI/AAAAAAAAAEo/H9K4iwXoCfo/s320/Fluorine_02_solution_explorer.gif" border="0" alt="" /></a></p>
<p>Abra o arquivo Sample.cs (dentro de App_Code), vamos utiliza-lo em nosso primeiro teste do Fluorine.<br />
Observe que a classe Sample está dentro do namespace www e que possui um método chamado Echo que retorna uma string e precisa de um parâmetro. O método pega a string do parâmetro (text), concatena com &#8220;Gateway echo: &#8221; e retorna.</p>
<div class="codecolorer-container csharp mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br /></div></td><td><div class="csharp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span><br />
<span style="color: #0600FF;">using</span> <span style="color: #008080;">com.TheSilentGroup.Fluorine</span><span style="color: #008000;">;</span><br />
<br />
<span style="color: #0600FF;">namespace</span> www<br />
<span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000;">&#91;</span>RemotingService<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Fluorine sample service&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span><br />
&nbsp; &nbsp; <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Sample<br />
&nbsp; &nbsp; <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF;">public</span> Sample<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span><br />
<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Echo<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> text<span style="color: #000000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Gateway echo: &quot;</span> <span style="color: #008000;">+</span> text<span style="color: #008000;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #000000;">&#125;</span><br />
<span style="color: #000000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Pressione F5 para rodar a aplicação, clique sob o arquivo Console.aspx, note que você foi redirecionado para Fluorine.aspx, o Service Browser do Fluorine, deve se parecer com a imagem seguinte:</p>
<p><a rel="lightbox[roadtrip]" href="http://3.bp.blogspot.com/_qLU3RxFHN9w/R6PuqckUCCI/AAAAAAAAAEw/50bC8AlRmS8/s1600-h/Fluorine_03_service_browser.gif"><img id="BLOGGER_PHOTO_ID_5162232010887137314" style="cursor: pointer;" src="http://3.bp.blogspot.com/_qLU3RxFHN9w/R6PuqckUCCI/AAAAAAAAAEw/50bC8AlRmS8/s320/Fluorine_03_service_browser.gif" border="0" alt="" /></a></p>
<p>Você pode clicar no link “<span style="font-weight: bold;">• www.Sample</span>” para ver a especificação dos métodos e também obter um exemplo de código em ActionScript 1 e 2 que já roda os métodos da classes Sample.</p>
<p>Para dizer ao Fluorine que você quer que determinada classe seja acessada por Flash é só você importar “com.TheSilentGroup.Fluorine” (using com.TheSilentGroup.Fluorine;), e colocar o atributo “[RemotingService("Descrição")]” na classe. Fique atento que feito isso, o Fluorine só vai mostrar no Service Browser os métodos <span style="font-weight: bold;">publicos </span>da classe, é claro que sem contar o construtor.<br />
Veja como o Service Browser detalha os métodos das classes e já deixa um exemplo de Script para utilizarmos no Flash:</p>
<p><a rel="lightbox[roadtrip]" href="http://1.bp.blogspot.com/_qLU3RxFHN9w/R6PwD8kUCDI/AAAAAAAAAE4/XRd9aTQi5RQ/s1600-h/Fluorine_04_service_browser_sample.gif"><img id="BLOGGER_PHOTO_ID_5162233548485429298" style="cursor: pointer;" src="http://1.bp.blogspot.com/_qLU3RxFHN9w/R6PwD8kUCDI/AAAAAAAAAE4/XRd9aTQi5RQ/s320/Fluorine_04_service_browser_sample.gif" border="0" alt="" /></a></p>
<p>Visto que o Service Browser já gera o código correspondente em ActionScript 1 e 2, vamos deixar o nosso tutorial mais interessante e mostrar uma forma de fazer as devidas chamadas em ActionScript 3.0. Abra o Flash, e cria um arquivo novo, no primeiro frame do Flash insira o código a seguir:</p>
<div class="codecolorer-container actionscript3 mac-classic" style="overflow:auto;white-space:nowrap;border: 1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="actionscript3 codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0033ff; font-weight: bold;">import</span> <span style="color: #004993;">flash.net</span><span style="color: #000066; font-weight: bold;">.*;</span><br />
<br />
<span style="color: #339966; font-weight: bold;">function</span> onResult<span style="color: #000000;">&#40;</span>responds<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=object%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:object.html"><span style="color: #004993;">Object</span></a><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;onResult: &quot;</span> <span style="color: #000066; font-weight: bold;">+</span> responds<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span><br />
<br />
<span style="color: #339966; font-weight: bold;">function</span> onFault<span style="color: #000000;">&#40;</span>responds<span style="color: #000066; font-weight: bold;">:</span><a href="http://www.google.com/search?q=object%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:object.html"><span style="color: #004993;">Object</span></a><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span> <span style="color: #000000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;fault &quot;</span> <span style="color: #000066; font-weight: bold;">+</span> responds<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">toString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<span style="color: #000000;">&#125;</span><br />
<br />
<span style="color: #6699cc; font-weight: bold;">var</span> responder <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=responder%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:responder.html"><span style="color: #004993;">Responder</span></a> = <span style="color: #0033ff; font-weight: bold;">new</span> <a href="http://www.google.com/search?q=responder%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:responder.html"><span style="color: #004993;">Responder</span></a><span style="color: #000000;">&#40;</span>onResult<span style="color: #000066; font-weight: bold;">,</span> onFault<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
<br />
<span style="color: #6699cc; font-weight: bold;">var</span> gateway <span style="color: #000066; font-weight: bold;">:</span> <a href="http://www.google.com/search?q=netconnection%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:netconnection.html"><span style="color: #004993;">NetConnection</span></a> = <span style="color: #0033ff; font-weight: bold;">new</span> <a href="http://www.google.com/search?q=netconnection%20inurl:http://livedocs.adobe.com/flex/201/langref/%20inurl:netconnection.html"><span style="color: #004993;">NetConnection</span></a><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
gateway<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">connect</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;http://localhost:2471/www/Gateway.aspx&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span><br />
gateway<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">call</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;www.Sample.Echo&quot;</span><span style="color: #000066; font-weight: bold;">,</span> responder<span style="color: #000066; font-weight: bold;">,</span> <span style="color: #990000;">&quot;Primeiro teste do Fluorine!&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span></div></td></tr></tbody></table></div>
<p>Fique atento quanto ao endereço do Gateway.aspx, pois no nosso exemplo estou utilizando o endereço que o próprio Visual Studio cria quando rodamos a aplicação, por isto que temos esta portar “maluca” (http://localhost:<span style="font-weight: bold;">2471</span>).</p>
<p>Depois que você rodar a aplicação no Visual Studio, pegar o endereço gerado por ele, colar o endereço dentro de ‘gateway.connect(&#8220;<span style="font-weight: bold;">ENDEREÇO</span>&#8220;);’ e exportar o flash, você deve receber a mensagem “onResult: Gateway echo: Primeiro teste do Fluorine!”. Se foi exatamente isso que aconteceu, uueebá! Você acabou de fazer o seu primeiro teste de Flash Remoting com ASP.NET utilizando Fluorine!!! Fácil não?</p>
<p><span style="font-weight: bold;">Agora vamos entender cada linha de código desse nosso ActionScript 3.0:</span><br />
<span style="font-weight: bold;">1ª – </span>Importamos todas as classes que nos ajudam a efetuar conexões do Flash com o “Mundo Externo”.<br />
<span style="font-weight: bold;">3ª à 9ª – </span>Criamos as funções de callback que vão receber as respostas da nossa requisição.<br />
<span style="font-weight: bold;">11ª – </span>Criamos um Responder para armazenar as nossas funções de respostas (onResult e onFault).<br />
<span style="font-weight: bold;">13ª – </span>Criamos o nosso gateway, responsável pela comunicação com o Fluorine.<br />
<span style="font-weight: bold;">14ª – </span>Conectamos o nosso gateway ao Serviço do Fluorine.<br />
<span style="font-weight: bold;">15ª – </span>Efetuamos a chamada para o método <span style="font-weight: bold;">Echo</span> da classe <span style="font-weight: bold;">Sample</span> que se encontra no namespace <span style="font-weight: bold;">www</span>, passamos como segundo parâmetro o Responder (criado na linha 11) e como 3º parâmetro passamos o uma string, pois o método Echo precisa de uma string para funcionar.</p>
<p>É isso ai pessoal, espero ter ajudado aqueles que precisam da combinação Flash + ASP.NET, como foi o meu caso, pois já conhecia o AMFPHP mas no meu trabalho atual utilizamos ASP.NET.</p>
<p>No próximo post vou mostrar como transferir um bitmap do Flash para o Fluorine, agora a coisa vai ficar boa :)</p>
<p>Link para download do projeto:<br />
<a href="http://blog.bsoares.com.br/wp-content/uploads/2009/03/20080202_projeto.zip" target="_self">http://blog.bsoares.com.br/wp-content/uploads/2009/03/20080202_projeto.zip</a></p>
<p><span style="font-weight: bold;">Links relacionados:</span><br />
• Fluorine: <a href="http://fluorine.thesilentgroup.com/fluorine">http://fluorine.thesilentgroup.com/fluorine</a><br />
• Fluorine download: <a href="http://fluorine.thesilentgroup.com/fluorine/download.html">http://fluorine.thesilentgroup.com/fluorine/download.html</a><br />
• Flash Remoting: <a href="http://www.adobe.com/devnet/flashremoting/">http://www.adobe.com/devnet/flashremoting/</a><br />
• AMF3: <a href="http://osflash.org/documentation/amf3">http://osflash.org/documentation/amf3</a><br />
• AMFPHP: <a href="http://www.amfphp.org/">http://www.amfphp.org</a><br />
• Gateway: <a href="http://pt.wikipedia.org/wiki/Gateway">http://pt.wikipedia.org/wiki/Gateway</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bsoares.com.br/remoting/fluorine-uma-alternativa-de-flash-remoting-com-aspnet/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
