Visualizzazione post con etichetta Web Custom Control. Mostra tutti i post
Visualizzazione post con etichetta Web Custom Control. Mostra tutti i post

domenica 9 marzo 2008

EmbedVideo: a web control to embed video (FLV, WFV, ...) and Flash animations

CalSoft.EmbedVideo is a web custom control for ASP.NET. It is useful to put videos or Flash animations in your web pages.
It supports AVI, WMV and any other kind of formats supported by Windows Multimedia Player and FLV files on every Flash-enabled browser thanks to OS FLV, a free Flash 9 player and, finally, SWF files. The objects are embedded with a free javascript library, SWFobject that manages also browser differences and Flash versions.
Some interesting points are:
- thanks to the SWFobject it resolve EOLAS problems (the gray frame around the control and the need for an extra click to activate it) in IE.
- all the extra files (the two JavaScript libraries and the swf player) are embedded inside a single DLL.

Installation:
- download and unzip EmbedVideo20.zip (framework 2.0) or EmbedVideo30.zip (framework 3.0) or EmbedVideo35.zip (framework 3.5)
- create your web project in Visual Web Developer 2008 (or other Visual Studio products)
- right click on the toolbox window
- click on "Choose Items ..."
- click "Browse..." and select the EmbedVideo.dll just unzipped.

Now you are ready to use the control easily in your project: drag it in the page and set the properties (the meaning of each property is banal).


The icon of the control:


Note that the current version isn't compatible with ajax.net and was developed with Visual #C Express 2008.

The control is released under GPL license; please pay attention to the licenses of applications and libraries embedded consulting the respective sites.

Download the source
Download EmbedVideo DLL for framework 2.0
Download EmbedVideo DLL for framework 3.0
Download EmbedVideo DLL for framework 3.5
Sample here

Some useful links:
OS FLV
SWFObject
Pazera Free Video to Flash Converter

domenica 25 novembre 2007

An ASP.NET web control wrapping Google Maps API

I'm developing the new version of my real estate web site (http://www.vendercasa.it/) and I would to enrich it with the possibility of browsing the database trough a map, so I decided of interfacing my site with Google Maps; I think the best way to obtain it is to make a web control wrapping a sub-group of Google Maps APIs so I realised a web control, CalSoft.GoogleMaps, that offers methods, properties and events (at the end of the post you can find a reference) useful for interfacing to the Google Maps APIs.


How to use the control in an "ASP.NET Ajax-Enabled Web Site Project":
(note: the control works only in an Ajax project inside an update panel)

1 - Insert as first line of the HTML code the DOCTYPE tag: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

2 - Insert in the <HEAD> of the HTML code: <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=GOOGLE_MAPS_KEY" type="text/javascript"></script> where GOOGLE_MAPS_KEY depends on the URL of your site and you can get it here.

3 - Copy gmap.js in your web site space and insert in the <HEAD> of the HTML code: <script src="./gmaps.js" type="text/javascript"></script> where "gmaps.js" is the file with the javascript client library needed by the control

4 - In the body tag insert onload="GLoad()" onunload="GUnload()"

5 - Insert in your aspx page a ScriptManager and an UpdatePanel. Put outside the UpdatePanel a DIV control and fill it Id property (for example 'MYMAP') and set the dimensions of the control

6 - Add the CalSoft.GoogleMaps control to the toolbox (right click over the toolbox, 'choose items...' and browse the CalSoft DLL), insert a GoogleMaps control in the UpdatePanel, fill the Control property with the Id of the control where you want the map would appear (in previous example "MYMAP"). Set the other properties according to your needs.

Problems/To do:

PanTo doesn't work right
Setting "navigation map controls" properties doesn't work in runtime mode
Test multiple controls in a single page
Impossible to change the 'Control' property at runtime
Implement StringBuilder where possible and useful

Methods, properties and events reference

Methods:

SetCenter(Single sLat, Single sLng, int iZoom)

Set the centre of the map and the zoom factor.

PanTo(Single sLat, Single sLng, int iMillisec)

Pan the map to the specified position in the specified time (milliseconds).(at the moment doesn't work right)

Properties:

bool ZoomChanged
bool MapTypeChanged
bool CoordinatesChanged


These 3 read-only properties warn over a value change.
(respectively zoom, map type and coordinates)

bool GLargeMapControl
bool GSmallMapControl
bool GSmallZoomControl
bool GScaleControl
bool GMapTypeControl
bool GOverviewMapControl


They activate the visualization of the standard navigation controls on the map.
They are valid only at design time, changing them during runtime is useless.

int Zoom

Zoom level.

Single Latitude

Latitude of the centre of the map.

Single Longitude

Longitude of the centre of the map.

string Control

Id of the control (usually a DIV) where the map is displayed.

GMMapType MapType

Map type, the value is an enum:
enum GMMapType { Normal, Satellite, Hybrid, Default }

Single NELatitude
Single NELongitude
Single SWLatitude
Single SWLongitude


Latitudes and longitudes of the north-east and south-west corner of the map. They are read-only.

Events:

OnGMClick(object sender, Single lat, Single lng)

Fired every time the user click on the map.
Lat e lng are the coordinates (latitude and longitude) of the clicked point.

OnGMMove(object sender, string arg)

Fired when the map change (in position, appearance or zoom).
The properties reflect the changes of the map.(The 'arg' argument at the moment isn't implemented and give back only the string 'move').

You can download the control (with all the needed files - source, compiled dll and js library) by clicking here or test it here.

sabato 18 agosto 2007

LocationFinder: a web control findig places

Today a simple web custom control based on the Microsoft Virtual Earth APIs and that can search for places and/or business simply passing what and/or where, similarly to Live Local Search.

The control hasn't any property, but only a method and an event:

void Find(string what, string where, int start, int length)

Method that performs a what (business) search and/or a where (location) search (at least one of these two parameters is required)., for the answer you must wait for the event.

Parameters:
what: the business name, category, or other item searched for(es. "pizza")
where: the address or place name of the area searched for (es. "New York")
start: the beginning index of the results returned
length: the number of results to be returned (max. 20)

void LocationFinder_Found(object sender, VEFindResult[] results, VEPlace[] places, bool hasmore)

Event that returns a list of results and a list of places.

Parameters:
results: array of VEFindResult (list of results)
places: array of VEPlace (list of ambiguous places)
hasmore: true if there are others results (at the moment doesn't work!)

There are also two structures:

CalSoft.VEFindResult

Name
Description
Phone
IsSponsored
Latitude
Longitude

CalSoft.VEPlace

Name
Latitude
Longitude

(the function of each member is intuitive)

You can download the control by clicking here or test it here.
The zip contains the DLL (put it in the bin directory and add the control to the toolbox of Visual Studio) and the source (FadingImage.cs).
How to use the DLL in your WEB projects:
1 - put the DLL fille in the Bin directory of the site;
2 - if you want to add the control to Visual Studio toolbox, right-click on it, click on "Choose Items ..." and browse the project to add the DLL.
Note: if you want to modify the source remeber to add the right references (System.Web, System.Web.Extension, System.Drawing)
That's all.

sabato 4 agosto 2007

FadingImage: a web custom control fading between images

(note: this is my first post in English: I'm learning English, sorry for my mistakes and I will appreciate your kind corrections)

For an ASP.NET project I needed to fade between images, so I decided to write a web custom control: FadingImage.
Usage is easy: changing ImageUrl property the control fades between the previous image and the new one.
It derives from System.Web.UI.WebControls.Image and implements IPostBackEventHandler, I added one property and two events.

Increments
% increment of opacity every 50 milliseconds (for example setting this property to 5 makes images shading in one second). If you don't want fading set this property to 0.

onEndFading(object sender)
occurs each time a fading ends.

onClick(object sender, int t, int x, int y)
occurs for every mouse click over the control, t represent the mousekey (1 = left, 2 = right), x and y the coordinates relative to the control.

Compatibility:
I tested the control with IE7, Firefox 2 and 1.5, Opera 9.21, other visitors advise me that it works with IE6, but I want to compile a complete compatibility list:

Could you help me? Have a look at the image below:

What do you see (Uluru, Sydney skyline or both)? Which is your browser/version? Let me know! Thanks.

You can download the control by clicking here or test it here.
The zip contains the DLL (put it in the bin directory and add the control to the toolbox of Visaul Studio), the source (FadingImage.cs) and the javascript source (not needed by the program because the js code is integrated in the C# code, but I included it for an easier reading).

Note: don't forget to insert the DOCTYPE tag:



How to use the DLL in your WEB projects:

1 - put the DLL fille in the Bin directory of the site;

2 - if you want to add the control to Visual Studio toolbox, right-click on it, click on "Choose Items ..." and browse the project to add the DLL.

Note: if you want to modify the source remeber to add the right references (System.Web, System.Web.Extension, System.Drawing)

Good luck and let me know!

giovedì 2 agosto 2007

Creare un Web Custom Control - Codice completo e esempio

Finalmente il codice completo e un esempio Ajax scaricabile qui.

sabato 7 luglio 2007

Memory! 2000

Ho messo on line un giochino web che sfrutta Ajax, ci potete giocare cliccando qui.

Le regole sono molto semplici, si tratta di scoprire le 16 carte due a due cercando di abbinare le carte uguali. Al termine del gioco ci viene indicato in quante mosse abbiamo finito il gioco.

Potete scaricare qui lo user control da inserire nelle vostre pagine ASP.NET qui:
Download web control Memory! 2000

se siete interessati alla versione Windows per giocare off-line la potete scaricare qui:
Download Windows Memory! 2000
(Nota: é necessario che sia istallato il framework .Net 2.0).

Note tecniche
I programmi sono scritti in C# utilizzando Visual C# Express e Visual Web Developer Express scaricabili gratuitamente dal sito Microsoft (download Visual Studio 2005 Express).

Buon divertimento!

sabato 2 giugno 2007

Creare un web custom control - Parte 8

Integrare il controllo in un progetto ASP.NET con Ajax


Integrare un web custom control in un progetto Ajax è molto semplice: una volta installato il supporto Ajax a Visual Web Developer 2005 Express, è sufficente creare un nuovo "ASP.NET Ajax-Enabled web site":poi nella pagina aspx, come per ogni altra applicazione Ajax, è ncessario inserire un controllo ScriptManager e almeno un controllo UpdatePanel:

Per quanto riguarda il nostro web custom control non è necessario cambiare una sola riga di codice, tutto funzionerà magicamente: i programmatori della Microsoft hanno fatto proprio un bel lavoro!

sabato 21 aprile 2007

Creare un web custom control - Parte 7

Integrare il controllo in un progetto ASP.NET

Per integrare il controllo in un progetto di Visual Web Developer è necessario compilarlo per ottenere una DLL, copiarla poi nella cartella bin del progetto non è sufficiente perché significherebbe rinunciare alla possibilità di integrarlo all'interno dell'interfaccia offerta da Visual Studio, ma seguendo pochi semplici passi è possibile includerlo nel toolbox per poterlo poi utilizzare come un qualunque altro controllo:

1 - Aggiungere il controllo al toolbox cliccano con il tasto di destra sul toolbox stesso, selezionando poi la voce "Choose Items ..." e infine caricando la DLL appena compilata.

2 - Copiare il file .js con le funzioni necessarie al funzionamento del controllo all'interno della directory del sito e ricordarsi di referenziarlo all'interno dell'header di ogni pagina aspx nel quale intendiamo utilizzare il controllo:



E adesso è possibile iniziare ad utilizzare il controllo. Piazziamo il controllo sulla pagina e valorizziamo le proprietà principale, da codice creiamo l'array MenuItem che definisce le voci di menu e lo passiamo al controllo:

#using ExploWCC;

...

if (!IsPostBack)
{
MenuItem[] yv = new MenuItem[4];

yv[0].Title = "Menu numero 1";
yv[0].ToolTip = "Questo è il tooltip 1";

yv[1].Title = "Menu numero 2";
yv[1].ToolTip = "Questo è il tooltip 2";

yv[2].Title = "Menu numero 3";
yv[2].ToolTip = "Questo è il tooltip 3";

yv[3].Title = "Menu numero 4";
yv[3].ToolTip = "Questo è il tooltip 4";

MenuLeft.MenuItems = yv;
}

Poi è necessario gestire l'evento aggiungendo il seguente codice:

protected void MenuLeft_MenuChange(object sender, int e)
{
MenuLeft.Selected = e;
}

e valorizzare l'attributo OnMenuChange nel tag del controllo:

OnMenuChange="MenuLeft_MenuChange"

Fine, è tutto (o quasi, è evidente che per arricchire il controllo è necessario definire stili, aggiungere immagini ... ma questo è lavoro per il webdesigner. Nella prossima, ed ultima, puntata integrerò il nostro controllo in un progetto Ajax e infine renderò possibile per lo scaricamento il progetto completo sia del controllo che del sito che lo utilizza.

venerdì 20 aprile 2007

Creare un web custom control - Parte 6

Eventi

Per completare il controllo è necessario dotarlo della capacità, in corrispondenza del click su una voce di menu, di generare un evento lato client che scateni l'esecuzione di codice lato server.

La sequenza di operazioni che porta al raise di un evento all'interno dell'architettura ASP.NET è la seguente:
  1. javascript, in genere in risposta ad un evento DHTML, invoca la funzione __doPostBack con due argomenti: eventTarget con il nome del controllo che ha generato l'evento e eventArgument come variabile dove inserire dei parametri aggiuntivi.
  2. a questo punto l'esecuzione del comando è presa in carico dalle librerie javascript di ASP.NET che provvedono a passare i dati al server tramite un normale postback con ricaricamento della pagina in un tradizionale progetto ASP.NET o tramite la classe XMLHttpRequest nei progetti che ricorrono ad Ajax.
  3. il server elabora la richiesta eseguendo il codice necessario compreso il codice corrispondente all'evento e risponde al client rinviando i dati in formato XML oppure HTML a seconda che si stia lavorando in Ajax o meno.
  4. In un progetto Ajax è ancora la libreria ASP.NET client ad elaborare la risposta e ad aggiornare l'aspetto della pagina, in un progetto tradizionale è il browser che esegue il rendering della pagina.
Nel nostro progetto la funzione javascript che si occupa di eseguire un __doPostBack è YVChgBkgMnu come è possibile verificare nella libreria js riportata nel secondo articolo dove si può notare che come secondo argomento della funzione è passato l'indice (0 ... n-1) della voce di menu cliccata.

Decidiamo di chiamare il nostro evento con il nome di MenuChangeHandler, nel codice C# è necessario quindi dichiararlo:

public delegate void MenuChangeHandler(object sender, int e);

All'interno della classe dichiariamo il delegate MenuChange:

public event MenuChangeHandler MenuChange;

E inseriamo il codice di risposta all'evento:

public void RaisePostBackEvent(string
{
   if (MenuChange != null)
      MenuChange(this, Convert.ToInt16(eventArgument));
}

La nostra nuova classe Menu.cs può essere visualizzata cliccando qui.

lunedì 9 aprile 2007

Creare un web custom control - Parte 5

Il metodo Render

Il metodo Render si occupa di generare il codice HTML che rappresenta il controllo in base al valore delle delle proprietà e ad altri parametri come per esempio lo user agent.
Nel nostro caso si tratta di creare un nuovo metodo Render che sovrascriva quello standard del controllo e che si occupi di generare le sequenze di <div>, <table> e <img> che costituiscono il menu secondo la struttura indicata nel secondo articolo.

Il metodo Render non restituisce nessun valore e accetta in ingresso un parametro di tipo HtmlTextWriter.

Il listato del metodo Render è scaricabile qui


Per gestire i differenti meccanismi con i quali i principali browser gestiscono la trasparenza è stata introdotta la funzione opacity così definita:

private string opacity(int x)
{
if (Page.Request.UserAgent.Contains("MSIE"))
{
return "filter:alpha(opacity=" + x.ToString() +");";
}
else
{
string op = ((x + 1000).ToString()).Substring(1);
return "opacity:" + op.Substring(0, 1) + "." + op.Substring(1) + ";";
}
}
Nota: il metodo Render richiama anche dei metodi privati della classe il cui codice sarà presente nel download finale del progetto, ma che adesso è preferibile trascurare per semplicità. Inoltre per il corretto funzionamento di tutto il nuovo codice aggiunto è necessario includere i namespace System e System.Web.UI aggiungendo in testa al listato della classe le righe:

using System;
using System.Web.UI;

oltre ad aggiungere un riferimento agli assembly System.Drawing e System.Web.Extensions:

Creare un web custom control - Parte 4

Le proprietà di default e custom

Come ogni controllo, anche il nostro avrà una serie di proprietà, alcune ereditate dalla classe WebControl da cui è derivato, alcune create appositamente. Le proprietà entreranno in gioco in fase di rendering del controllo caratterizzando il codice HTML.

Le proprietà ereditate che gestiremo sono:

ID
Visible
Width
BorderStyle
BorderWidth
BackColor
BorderColor

mentre le nuove proprietà introdotte sono:

Opacity (int)
CssClassMenuOver (string)
CssClassMenu (string)
CssClassToolTip (string)
Selected (int)
Top (Unit)
Left (Unit)
ZIndex (int)
MenuItems (array di elementi di tipo MenuItem)

con MenuItem definito in questo modo:

public struct MenuItem
{
   public string Title;
   public string ToolTip;
   public bool Hidden;
   public string Style;
}

e definisce le caratteristiche di una singola voce di menu.

Quindi al codice della classe è necessario aggiungere le seguenti righe di codice:

#region Properties
private int _opacity = 20;
public int Opacity
   {
      set
      {
         _opacity = value;
         if (_opacity < 0)
            _opacity = 0;
         if (_opacity > 100)
            _opacity = 100;
      }
      get
      {
         return _opacity;
      }
   }
   private MenuItem[] _menuitems;
   public MenuItem[] MenuItems
   {
      set
      {
         _menuitems = value;
      }
      get
      {
         return (_menuitems);
      }
   }
   private string _cssclassmenuover;
   public string CssClassMenuOver
   {
      set
      {
         _cssclassmenuover = value;
      }
      get
      {
         return _cssclassmenuover;
      }
   }
   private string _cssclassmenu;
   public string CssClassMenu
   {
      set
      {
         _cssclassmenu = value;
      }
      get
      {
         return _cssclassmenu;
      }
   }
   private string _cssclasstooltip;
   public string CssClassToolTip
   {
      set
      {
         _cssclasstooltip = value;
      }
      get
      {
         return _cssclasstooltip;
      }
   }
   private int _selected;
   public int Selected
   {
      set
      {
         _selected = value;
      }
      get
      {
         return _selected;
      }
   }
   private Unit _top = 0;
   public Unit Top
   {
      set
      {
         _top = value;
      }
      get
      {
         return _top;
      }
   }
   private Unit _left = 0;
   public Unit Left
   {
      set
      {
         _left = value;
      }
      get
      {
         return _left;
      }
   }
   private int _zindex = 0;
   public int ZIndex
   {
      set
      {
         _zindex = value;
      }
      get
      {
         return _zindex;
      }
   }
#endregion

Nota: siccome abbiamo definito delle proprietà e delle variabili di tipo Unit è necessario includere anche il namespace System.Web.UI.WebControls aggiungendo in testa del file della classe la seguente riga di codice:

using System.Web.UI.WebControls;

Creare un web custom control - Parte 3

La classe Menu.cs


Finalmente è arrivato il momento di mettere mano al codice C#, quindi avviamo il Visual C# e creiamo un nuovo progetto di tipo "Class Library" e gli diamo il nome "ExploWCC" (Explobot Web Custom Controls).


Visual C# ci crea la struttura di progetto, compreso la classe Class1.cs che rinominiamo in Menu.cs.


La nostra nuova classe, siccome vuole essere un web control, eredita da System.Web.UI.WebControls.WebControl, assumendo quindi il seguente aspetto:

namespace ExploWCC
{
      public class Menu : System.Web.UI.WebControls.WebControl
      {
      }
}

Se proviamo a compilare questa semplicissima classe ci vengono segnalati una serie di errori che ci stanno ad indicare la necessità di inserire un riferimento all'assembly System.Web seguendo dei semplici passaggi:
  • click con il tasto di destra sul nome della libreria (ExploWCC) nel Solution Explorer
  • nel menu che compare selezionare la voce "Add Reference ..."
  • nella label ".NET" del pannello che compare fare doppio click su System.Web
A questo punto la compilazione può avvenire senza errori, quindi nel Solution Explorer, nella cartella References compare anche System.Web (nel mio caso sono presenti anche la System.Data e la SystemXml che ho rimosso perché al momento non mi servono):



giovedì 5 aprile 2007

Creare un web custom control - Parte 2

HTML e Javascript

Il controllo che vogliamo realizzare è un menu verticale in cui l'elemento selezionato viene evidenziato con due righe orizzontali sopra e sotto con uno sfondo di colore diverso con la prerogativa di poter settare il coefficiente di trasparenza; inoltre un'altra peculiarità è quella di poter mostrare dei baloon in corrispondenza dell'elemento sul quale si posiziona il mouse.

Il menu è stato ottenuto, a differenza dei menu CSS più recenti, non con i tag <UL> e <LI> (come spiegato qui per esempio), ma nel più tradizionale metodo con una serie di <DIV>, uno per ogni voce di menu oltre a uno per lo sfondo dell'elemento selezionato, uno per le sottolineature superiori ed inferiori sempre dell'elemento selezionato, uno per il contenuto del baloon e uno per l'ombra del baloon.
Il codice HTML di cui si compone un menu è quindi di questo tipo:

<DIV id=NomeMenu ... >
      <DIV ... >Menu 1</DIV>
      <DIV ... >Menu 2</DIV>
      ...
      <DIV id=NomeMenu_bkg ...></DIV>
      <DIV id=NomeMenu_border ...></DIV>
      <DIV id=NomeMenu_baloon ...>
      <DIV id=NomeMenu_ombra ...></DIV>
            <TABLE>
                  <TR>
                        <TD class=tooltip id=NomeMenu_text>&nbsp;</TD>
                  </TR>
            </TABLE>
            <IMG id=NomeMenu_freccia ... >
      </DIV>
</DIV>

Evidentemente, non facendo ricorso ad automatismi CSS, a corredo del controllo c'è una libreria di funzioni javascript che gestisce l'interazione utente<->browser<->server; clicca qui per visualizzare la libreria, oppure qui per scaricarla.
Altre funzioni javascript sono cablate all'interno del codice HTML nel momento in cui viene generato dall'evento Render del controllo, ma questo verrà visto in una prossima lezione.

sabato 31 marzo 2007

Creare un web custom control - Parte 1

Introduzione

ASP.NET permette l'utilizzo di controlli web personalizzati di 2 tipi differenti:

  1. User control
  2. Custom control
I web user control sono più semplici da realizzare e si ottengono assemblando controlli già esistenti, mentre con i web custom control il programmatore si deve occupare anche della generazione del codice HTML associato e quindi sono più complessi da realizzare, ma anche più versatili e permettono di ottenere risultati difficilmente ottenibili con i web user control.

In questa serie di articoli mi occuperò appunto dei web custom control, illustrerò come realizzare un menu ampiamente configurabile e con qualche effetto originale (come per esempio i baloon per le voci del menu o l'effetto trasparenza) questo mi permetterà di illustrare alcuni punti interessanti come la possibilità di generare un evento lato server utilizzando javascript, come generare codice HTML differente a seconda dello user agent, come utilizzare le proprietà standard dei controlli web standard (System.Web.UI.WebControls.WebControl) e come crearne di personalizzate e integrate con le funzionalità di intellisense e infine come integrarle in una pagine aspx illustrando come continui a funzionare egregiamente anche in un progetto ASP.NET con supporto Ajax.

Per poter seguire l'articolo e utilizzare il codice dell'esempio che fornirò è necessario aver installato almeno Visual Studio C# 2005 Express per realizzare il controllo, Visual Web Developer 2005 Express con estensioni Ajax per testarlo.

Se volete dare un'occhiata al risultato finale andate sul mio sito The Yellow Van.