Flex AutoResizable Textarea

I’ve been quite busy those past weeks, working on some great projects and cool devices (Stay tune one will be available in all high tech shops soon).

Recently, I faced a very simple Flex problem. I had to work with a Textarea but I needed it to be autoresizable, and ALSO I had be able to set so constraints such as : maxchars displayed and maxheight. I had a quick look on the internet but I didn’t find a conponent fitting my needs. You may find some example using mx_internal properties but I try to avoid using this namespace…for many reasons.

Anyway, I crafted my own Autoresizable Textarea and share it to everyone who want to play with/improve/crash/burn/..etc it.


///////////////////////////////
// Author: Guillaume Nachury
//
//         Advanced Textarea
//
// -> Auoresize feature with
//             -> MaxChar limiter
//            -> MaxHeight limiter
///////////////////////////////

package
{
 import mx.controls.TextArea;

 public class AdvancedTextarea extends TextArea
 {

 private var _autoResize:Boolean =  false;
 private var _lineOffset:int = 5;
 public var fullText:String="";

 public function AdvancedTextarea(isAutoResize:Boolean=false)
 {
 super();
 _autoResize = isAutoResize;
 }

 //overrides        
 override public function set maxChars(i:int):void{
 super.maxChars = i;
 doValidations();
 }

 override public function set maxHeight(n:Number):void{
 super.maxHeight = n;
 doValidations();
 }

 override public function set text(s:String):void{
 //limit the number of chars if there's a limit
 fullText = s;
 if(super.maxChars>0 && s.length > super.maxChars){
 s = s.substring(0, super.maxChars)+"...";    
 super.text = s;
 }
 super.text = s;

 validateNow();
 doValidations();
 }

 private function doValidations():void{
 if(super.text != null && super.text.length >0){

 //limit the height if there's a limit
 if(!isNaN(super.maxHeight)){
 var textH:int = this.textField.measuredHeight+_lineOffset;
 if(textH > super.maxHeight && _autoResize == true){
 this.height = super.maxHeight;
 }
 else{
 if(_autoResize == true)    this.height = this.textField.measuredHeight+_lineOffset;

 }

 }
 else{
 if(_autoResize == true){
 this.height = this.textField.measuredHeight+_lineOffset;
 }

 }
 }
 }

 public function set autoResize(b:Boolean):void{
 _autoResize = b;
 doValidations();
 }

 }
}

Advertisements

[Pixel Bender] Bright Pass filter

I’m pretty sure you already heard about pixel bender, if not check Adobe’s  or Lee Brimelow’s website for awsome tutorials. 

Today I gonna share with you, my first pixel bender code ever, which is a bright pass filter. This filter set the dark pixels to black according a threshold value for the ‘darkness’.

kernel BrightPassFilter
< namespace : "com.gun.uieffect.filter"; vendor : "Guillaume Nachury. https://proofofconcepts.wordpress.com/"; version : 1; description : "Set all the dark pixels to black. The dark threshold value can be modified."; >
{
input image4 src;
output pixel4 dst;

parameter float thresholdValue;

void
evaluatePixel()
{
float Mx;
float mn;
float l;

pixel4 p;
p = sampleNearest(src,outCoord());

/*———————————————————————–
Here are some formulas to get the lightness :
———————————————————————–*/

/*(1) This one gave the best results so far.*/
l = (240.0/255.0)*(0.239*p.r+0.686*p.g+0.075*p.b);

/*(2) Quite the same as above but a bit tweaked
l = (240.0/255.0)*(0.300*p.r+0.590*p.g+0.110*p.b);
*/

/*(3) This one requires some steps before getting the lightness
//Find which component is the highest
if((p.r > p.g) && (p.r > p.b)){
Mx = p.r;
}
else if((p.g > p.r) && (p.g > p.b)){
Mx = p.g;
}
else if((p.b > p.g) && (p.b > p.r)){
Mx = p.b;
}

//Find which component is the lowest
if((p.r < p.g) && (p.r < p.b)){ mn = p.r; } else if((p.g < p.r) && (p.g < p.b)){ mn = p.g; } else if((p.b < p.g) && (p.b < p.r)){ mn = p.b; } l = 0.5*240.0*( (Mx+mn)/255.0), */ /*Formula I found, but not sure of the result l = (240.0/255.0)*Mx; */ if(l

Skinning a Flex Slider

[a part II of this post is available here]
It’s been a long long time since my last post but I recently move to my new apartment and it ISP forgot to move my internet access…It was a bit annoying at the beginning since I could not work on the version of NURVE, but I had a lot of time to explore new Flex features and especially customizing/creating UI components. I had so much fun doing this that I gonna write few posts on it.

The first component I worked on was the Slider (actually HSlider), because I think it’s the component that can be used in numerous cases and also because most of the time it doesn’t fit our my UI needs. Sorry to all the GREAT developers that worked on Flex UI components but the default Slider is just ugly…

Fortunately they add a cool feature that allow everyone to  customize the look and feel. (I think it’s important to understand that some of the time it may be interesting to change the look but changing the feel is also really important.) I won’t talk about the styles we can apply via CSS, but instead, how to use the sliderThumbClass and the trackSkin from the Slider Object.

Before jumping into the code, lets have a look to the result :

As you can see, no more default UI and a ‘Tooltip’ more useful. I used this Slider in one of my project where I had to navigate thru archives.

Ok so as I said I used sliderThumbClass to modify the ThumbSlider UI and the trackSkin in order to change the track of the slider.

The track skin:

This part is really easy, we just have to create a UIComponent with the desired shape. So just Create a new Class that extends UIComponent and override updateDisplayList function with your code that draws the shape you want.

package com.GuN.UI.customUIComponent.slider
{
	import mx.core.UIComponent;

	public class SliderTrack extends UIComponent
	{
			override public function get height():Number{
	            return 20;
	        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            //create 2 circle that will act like round corners
            this.graphics.beginFill(0xFFFFFF,1);
            this.graphics.drawCircle(0,0,5);
            this.graphics.drawCircle(unscaledWidth,0,5);
            this.graphics.endFill();
            //create the line that represents the track
            this.graphics.moveTo(0,0);
            this.graphics.lineStyle(10,0xFFFFFF);
            this.graphics.lineTo(unscaledWidth,0);

        }

	}
}

I could use a drawRoundRect() aswell, but I will explain that on an other component customization post.
Ok now the track is now done, let’s have a look to the Thumb.

The slider Thumb

My Slider have a really simple thumb, it’s actually just a black circle. Like what we’ve done for the the track, we’ll do exactly the same for the Thumb. So create a class extends SliderThumb to inherit the behavior of a slider and override the updateDisplayList function.

package com.GuN.UI.customUIComponent.slider
{
	import mx.controls.sliderClasses.SliderThumb;

	public class CSpSliderThumb extends SliderThumb
	{

public function CSpSliderThumb()
		{
			super();
}

           override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
            super.updateDisplayList(unscaledWidth,unscaledHeight);
            this.graphics.beginFill(0x000000,1);
            this.graphics.drawCircle(2,-8,4);
           	this.graphics.endFill();
        }
     }
}

At this point you have a new slider without any cool effect. You can still continue using the default datatooltip but you can also create your very own datatooltip UI. On my slider I added a Sprite beneath the Thumb to display the data while sliding.

Here is the code for the datatip container :

package com.GuN.UI.customUIComponent.slider.sprites
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	public class CSpSprite extends Sprite
	{
		var lbl:TextField;
		var bkgColor:uint = 0x000000;
		var bkgAlpha:Number = .5;

		var textColor:uint = 0xFFFFFF;

		public function CSpSprite()
		{
			super();
			lbl = new TextField();
			drawShape();
			drawText();

		}

		private function drawText():void{
			lbl.x = -10;
			lbl.y = 3;
			lbl.autoSize = TextFieldAutoSize.CENTER;
            lbl.background = false;
            lbl.border = false;

            var format:TextFormat = new TextFormat();
            format.font = "Verdana";
            format.color = textColor;
            format.size = 9;
            format.underline = false;

            lbl.defaultTextFormat = format;
            addChild(lbl);
		}

		private function drawShape():void
		{

			this.graphics.beginFill(bkgColor,bkgAlpha);
			this.graphics.lineTo(35,0);
			this.graphics.lineTo(40,-9);
			this.graphics.lineTo(45,0);
			this.graphics.lineTo(80,0);
			this.graphics.lineTo(80,25);
			this.graphics.lineTo(0,25);
			this.graphics.lineTo(0,0);
			this.graphics.endFill();

			//Create a white border
			this.graphics.lineStyle(1, 0xFFFFFF, 1);
			this.graphics.moveTo(-1,-1);
			this.graphics.lineTo(34,-1);
			this.graphics.lineTo(39,-10);
			this.graphics.lineTo(44,-1);
			this.graphics.lineTo(79,-1);
			this.graphics.lineTo(79,24);
			this.graphics.lineTo(-1,24);
			this.graphics.lineTo(-1,-1);

		}

		public function setValue(v:String):void{
			lbl.text = v;
		}

	}
}

We can add our datatipcontainer to the SliderThumbClass we created before

package com.GuN.UI.customUIComponent.slider
{
	import mx.controls.sliderClasses.SliderThumb;

	public class CSpSliderThumb extends SliderThumb
	{

public function CSpSliderThumb()
		{
			super();
			initSprite();
			addChild(spr);

		}

private function initSprite():void{
			spr = new CSpSprite();
			spr.x = -(spr.width/2)+4;
			spr.y = 9;
		}

           override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
            super.updateDisplayList(unscaledWidth,unscaledHeight);
            this.graphics.beginFill(0x000000,1);
            this.graphics.drawCircle(2,-8,4);
           	this.graphics.endFill();
        }
     }
}

Now that our Slider is almost done, we can create the mxml that will house the custom slider. Like I said I used this slider to navigate thru archives so used an array of values that contains all the months that had to work with.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundGradientAlphas="&#91;1.0, 1.0&#93;" backgroundGradientColors="&#91;#353535, #353535&#93;">
	<mx:Script>
		<!&#91;CDATA&#91;
			import com.GuN.UI.customUIComponent.slider.SliderTrack;
			import com.GuN.UI.customUIComponent.slider.CSpSliderThumb;

			var arrayValues:Array = &#91;"null","January '08", "February '08", "March '08", "April '08", "May '08", "June '08", "July '08", "August '08",
										"September '08", "October '08", "November '08", "December '08"&#93;;

		&#93;&#93;>
	</mx:Script>

		<mx:HSlider x="10" y="107"
		id="s"
		showDataTip="false"
		values="{arrayValues}"
		creationComplete="{s.value=1}"
		snapInterval="1"
		minimum="1"
		maximum="{arrayValues.length-1}"
		liveDragging="true"
		trackSkin="{SliderTrack}"
		sliderThumbClass="{CSpSliderThumb}"
		 width="502"/>

</mx:Application>

For more details you can have look to the sources my work, as usual you can freely reuse/hack my code. 
By the way, if you wanna see cool effects check Chet Haase’s ‘Codedependent’ Blog and especially the Spring is in the AIR? post which is really interesting.

Create HTTPs request with phpWebrequest

I received several emails about my phpWebRequest php class, asking how we can create HTTPs POST request. Before I answer this I think it’s important to understant the HTTP authentication mechanism.

There are 2 kinds of authentication: Basic and Digest. I gonna describe only Basic since it’s very is to use in the phpWebRequest class.

Basic is the easiest authentication to setup, since it do not provide any encryption during the transmission of the HTTP request.
Here is what happens when you try to reach a secured page (on https://a.server.com/the/secure/page.dll)

Client:
GET /the/secure/page.dll HTTP/1.1
Server:
HTTP/1.1 401 Authorization Required
WWW-Authenticate: Basice realm="Basic Realm"

In the answer we have from the server, we can see that a Basic authentication is required. That means in our HTTP header we need to add a field called Authorization that contains the login and password to reach the secured page. In our case the login is myLogin and the password is myPasswrd . The new Authorization field value will be myLogin:myPasswd encoded as a base64 string so bXlMb2dpbjpteVBhc3N3ZCA=
We can now try to reach the page :

Client:
GET /the/secure/page.dll HTTP/1.1
Authorization: Basic bXlMb2dpbjpteVBhc3N3ZCA=
Server:
HTTP/1.1 200

Here is how to do that with the phpWebRequest class:

<?php
require_once('phpWebRequest.class.php');

$XMLString = '<?xml version="1.0" encoding="UTF-8"?><root><elems><e1>Element1</e1></elems></root>';

$rq = new PhpWebRequest();
$passwd =base64_encode("myLogin:myPasswd") ;

$rq->InitServer("256.256.256.256","/the/secure/page.dll");

$strSize = $rq->DataReaderFactory($XMLString);

$rq->InitRequest("POST");

$headerElements = array("Host" => "256.256.256.256",
						"Authorization" => "Basic ".$passwd,
                        "Connection" => "Close",
                        "Content-type" => "multipart/mixed",
                        "Content-length" => $strSize
                        );

$rq->CfgHeader($headerElements);

if($rq->SendRequest()){
    echo "Request sent !";
}
else{
    echo "ERROR";
}

?>

You can also have a look to the RFC2617 for more details on Basic and Digest.

Increase the traffic to your website :: Perl hack

I was about cleansing my old blog archives, and I discovered a post that I never publish. The post was about a hack used to increase the number of visit of an web page. 2 years ago, friends of mine were playing an online game which consisted in forwarding more people as they can, on a web page. The more people visited you page, the more your popularity increased. And of course the goal was to have the highest popularity.

On of my friend started few weeks after, and was obviously outdistanced by the others. So I wrote him this quick hack that increase the traffic to his page.

Of course the page vistors had to reach had ‘protections’:

  • Only real browser could accessed it
  • An IP can only access the page once a day.

I could use sockets and craft my own HTTP requests, but since I’m a lazy  developper I used another way to simulate a real Visitor. The solution was to automatically reach the page with Internet Explorer via a proxy that change at each access(I change the IE proxy.pac after every connection ).

I wrote the code in Perl and used IEAutomation API to control IE.

# ~*~ Cloak me ~*~
# This program will create cloaked connection san URL
# by using anonymous proxy servers all around the world.
# 07-2007
# v0.1
#
#HOW TO
# 1) Just replace MY_URL by the address you wanna reach, and change MY_OUTPUT_FILE by the path to your proxy.pac file
#2) Place your proxy list file in the cloak_me.pl ‘s directory.
#3) Change ie’s settings to use the proxy.pac file
#4) let’s run the program

use Win32::IEAutomation;
my $ie = Win32::IEAutomation->new();
$VERSION = “v0.1”;

print “[+] Starting ~*~Cloak me~*~\n”;
print “[+] Version : $VERSION\n\n”;

open(PROXY_LIST, ‘proxyList’)|| die (“[!] Cannot open proxy list\n”);
print “[+] Proxy list loaded\n”;
$i = 0;

while(){
chomp;
$content_text = “function FindProxyForURL(url, host){\nif(shExpMatch(url, ‘MY_URL’)){\nreturn ‘PROXY “.$_.”‘;\n}}”;
open(OUTFILE, “>MY_OUTPUT_FILE”);
print OUTFILE ($content_text);
close(OUTFILE);

print “[i] Using proxy : $_\n”;

$ie->gotoURL(‘MY_URL’);
$ie->WaitforDone;
$ie->closeIE();

$i++;
}

print “[+] Done \n”;
print “[+] Total cloaked access :”.$i.”\n”;

Notice that I do not provide any proxy list, you need to create / find one by yourself.
You can use this code to create cloaked connection to any site.

If you have any question just drop me an email.

T-SQL multi OUTPUT when using sp_executesql

One of my current professional dev project is to write an ETL from scratch using a lot of technologies. I had to play a lot with T-SQL (Transact-SQL) which was quite interesting to work with.

The code I will share today (not about RIA at all) is a cool trick when using sp_executesql. In some case, when you want to retreive only one record from a db, it could be interesting to have the result (the fields) or a part (some fields) of the result directly as variables instead of using another table to store the result and then re query to retreive the fields you want.

Imagine you have a Table called myContacts that have 6 columns:

id|Field1|Field2|Field3|Field4|Field5       <id as a primary key

And you want to query this table to retreive the record where id=4 and directly set some fields as variables, so you will be able to use them right after in you code.

Here is the trick :

declare
--The variables that will house the fields
   @myField1   int,
   @myField3   nvarchar(max),
   @myField5   nvarchar(max),

--query variables
   @sql						nvarchar(max),
   @ParamDef					nvarchar(max)

--The query
select @sql = 'select @myField1=Field1, @myField3=Field3, @myField5=Field5 FROM myContacts WHERE id = 4'

--The parameters
select @ParamDef = '@myField1 int OUTPUT, @myField3 nvarchar(max) OUTPUT, @myField5 nvarchar(max) OUTPUT'

--Execute de sql statement
exec sp_executesql @sql, @paramDef, @myField1 OUTPUT, @myField3 OUTPUT, @myField5 OUTPUT

Print 'Field #1 = '+convert(nvarchar,@myField1)+ ' Fields 3 & 5 : '+@myField3+',' +@myField5

OUTPUT : Field #1 = 1 Fields 3 & 5 : This is the Content 3, And this is Content 5

That’s an easy way to initiate variable on fly with from a sp_executesql result.
 

NURVE – Public alpha release

I’m pretty excited today since I’m releasing the first public alpha version of a project I’m working on, based on Adobe AIR/FLEX and Papervision3D , called NURVE.

NURVE is 3D, film trailers browser with an iTunes coverflow like navigation experience. NURVE allows you to browse the newest films trailers and watch them in HD quality on any, internet connected, OS that have AIR installed

Preview:

 

As my first shot with both FLEX and Papervision3D and since NURVE is still under development you may find some bugs/glitches or suggestions so please drop me an email or leave a comment here.

=> Download NURVE  (don’t forget to install Adobe AIR  )

Expected in the new release:

  • more 3D animations
  • film information displayed
  • some fix 
  • new icons
  • more films source

 

Like most of my works, I will release le source code as soon as most of the bugs are fixed;)