lunes, 23 de junio de 2008

HOWTO: Allow file downloads (including .exe) on IIS 6.0

Variations of this question are asked of IIS 6 all the time. However, the answer is no different than for any other version of IIS other than the fact that IIS 6 gives you a distinct error code to troubleshoot. What is not clear to me is why users think that the newly introduced Web Service Extension concept has something to do with this misconfiguration... I hope someone can give me some rationale.

Question:
Hello,

What is the correct method to allow .exe files to be downloaded or run from a web site on an IIS 6.0 server?

I am currently receiving a 404.2 error message in my browser when I try to open/download the executable files, and I am not sure which Web Service Extensions configuration changes must be made to allow this.

Thanks in advance,

Answer:
Given the current phrasing of your question, there is no correct method. Downloading a .exe file is NOT the same as run from a website, as I will describe below. I'll give a short answer and then a more detailed answer.

Short Answer
Your error message indicates that you have "Scripts and Executables" enabled, so IIS is trying to execute the .exe file on the web server, and since the .exe is not allowed by any defined Web Service Extension, a 404.2 results. The corrective action depends on what you want to do.

If you want to allow .exe files to be downloaded as-is to the browser, then you must NOT have "Scripts and Executables" as Execute Permissions.
If you want to execute the .exe file on the server to generate a response that is sent to the browser (possibly interpreted as a download), then you MUST have "Scripts and Executables" as Execute Permissions, and you must enable a Web Service Extension for that .exe file.
Details
Whenever the user makes the browser request a resource like "http://server/myapp.exe", users usually want one of the following actions to happen:

Return the file contents of myapp.exe as-is to the browser (aka file download)
Execute myapp.exe on the web server to generate a dynamic response (aka execute CGI script)
Now, the web server controls which action should happen, and on IIS, this is controlled by the "Execute Permissions" property of the virtual directory containing the .exe file. If the permission is set to "Scripts and Executables", then IIS will do action #2. Otherwise, it will do action #1.

Prior to IIS 6.0, there were no further security checks against either action. On IIS 6.0, there is one additional security check, depending on the action:

For action #1, the file resource's extension (.exe in this case) must have a defined MIME Type or else a 404.3 occurs. .exe has a MIME Type of application/octet-stream by default, so file download should just work.
For action #2, there must be an enabled Web Service Extension for the full path to the .exe resource to allow IIS to execute it to generate a HTTP response or else a 404.2 occurs. For securety reasons, IIS 6 does not allow any resource to execute by default unless otherwise configured/allowed in Web Service Extension.



From: http://blogs.msdn.com/david.wang/archive/2005/07/11/Allow_file_downloads_on_IIS_6.aspx

jueves, 19 de junio de 2008

Detallitos de CSS en Themes de ASP.NET

Los descubrimientos descritos a continuación, surgieron de mi necesidad de cargar CSS dinámicamente si estar creando mumerosos temas dentro de una aplicación WEB ASP.NET.

En primera instancia: Toda página que referencie un tema, SIEMPRE cargará absolutamente todos los CSS incluidos en el mismo, independientemente de que en realidad los necesite, y del nivel de anidamiento en el que se encuentren ubicados. Poco eficiente no es así?

Como se sabe, los CSS finalmente son Links referenciados en el HEAD de la página que está referenciándolos. Entonces es cuestión de escribir dinámicamente allí la ruta del CSS que se desea cargar y listo.

Lo anterior se logra metiendo un ASP.NET literal control dentro del HEAD, y en el load de la página ajustarlo con el valor que se desea.

Y listo!!!
Verificando con Firebug, se observa que a pesar de que existan varios CSS en la misma ruta de aquel que está siendo referenciado, solo el referenciado se descarga.

Ventajas?
Tener organizados varios CSS y no solo uno gigantesco con todo.
En cuanto a ancho de banda, si los CSS se dejan dentro de temas, por más separados que estén si son cargados por medio de referencia al tema desde la página, siempre bajan todos la primera vez que se llamen (luego quedan en el caché y no vuelven a descargarse si no se borra el caché o si no cambian en el server).

Si se desea optimizar el tiempo de descarga, entonces es mejor no usar Themes para cargar los estilos, sino que estos se carguen independientemente usando el modelo de HEAD descrito anteriormente.

lunes, 7 de abril de 2008

Table vs. DIV

I have a little story to tell about the webmaster who used a table with DIVs and the webmaster who didn't. The webmaster who didn't use a table had the higher paying job, a big house, a nice car, and a hot wife because he got all the good jobs for his tableless designs. The webmaster who used tables only to insert his DIVs was considered a second-rate bum and many believed he didn't even know how to position his DIVs. He made very little money. He lived in a rundown apartment. He had no car, and he had no wife.Then oneday the webmaster who had a classy job and the ever-so-popular tableless designs one day was sitting at his desk smoking a cigar talking on his cell phone about where to meet his buddies for lunch when his boss came running in all excited and out of breath."We just got a whole bunch of affiliate partners that want to place ads on our pages so they can make money and we can make commissions! We want an entire column added to the right side of every page!"Now the site had been around for several years and there were thousands of pages of content to add this column to, and the pages were all written in DIVs. So, the webmaster gasped and dropped his phone as the cigar fell from his mouth and he said, "Well, that is going to take some time, I got to place new DIV tags on every page to add one column of ads and that is no easy task!"The boss lamented this news, because not only would that mean he would not be making money off of his affiliates until the job was done, but he would have to hire someone else to assist the webmaster with his work until the site was updated. So, trying to save some money and not wanting to take a lot of time to hire someone on a contract, he hired the poor unsuccessful webmaster who always used tables to position his DIVs. The poor and destitude webmaster reluctantly decided he had no choice but to accept the tedious task, because he needed the money. So, for nearly a month he labored on inserting the appropriate DIVs on each page, copying and pasting many times into each page. When it was all said and done he went to the boss, and he shook his head and said, "You know it took a lot of copying and pasting to insert all them new DIV tags...If the site had been designed with a table I would have only had to copy and paste once into each page to insert the new column. You would have made a lot more money instead of having to hire someone else on, and it would have saved me from a lot of headaches going vertigo looking at code. I hope you never have to add a column again, for your sake and mine."The boss shook his head, and stopped the man before he could go. "Wait!" he said. "I could have been making tens of thousands of dollars a day all this time if you had done my site with tables?"The tired and frustrated impoverished webmaster nodded with a grim expression, and the boss threw up his hands and rolled his eyes. Racing out of his office, he motioned for the poor webmaster to follow after him as he charged into the rich webmaster's office. The rich webmaster was polishing his W3C Validation pin on his suit jacket as they entered and he smiled saying, "So, did the columns get added to all the pages?""Yes!" shouted the boss, "but you're fired! I got me a new webmaster right here who is going to make sure I never lose money adding a column of ads again!"Now, the poor webmaster is no longer poor, and the rich webmaster is no longer rich. He lost his big house. He lost his nice car. He lost his hot wife, because she only loved him for his money, and he is in the psyche ward for going nuts and breaking computers at a department store.

Like it is said: It all depends on the viewpoint. It exists another technique yet. The CSS positioning. It have its advantages and drawbacks too. So please try using all of this techiniques and acquire the experience. Then you will know which technique will be the best choice.

miércoles, 26 de marzo de 2008

Asignación dinámica de eventos a controles pertenecientes a controles compuestos.

Una dificultad que se tiene con controles compuestos cuando estos hacen parte de una colección dinámica, es asignarles eventos a los controles que los componen, ya que no se sabe de antemano cuántos van a ser.
Generalmente estos controles integrar un Repeater, que repite el control, por cada elemento dentro del DataBind de dicho Repeater.
Entonces basta con capturar el evento ItemCreated del Repeater. Cuando suceda, se busca el control compuesto y sus componentes. Y es en ese momento cuando ha de asignársele el evento a los sub controles que se deseen.

Generic Handlers

Un Generic Handler (GH) es otra clase de objeto que puede procesar http requests, sin necesidad de estar dentro del scope de una página (que está dirigida a presentar salidas de tipo HTML clásico). Un ejemplo de GH es el HTTP Handler. Como es bien sabido un http Handler se puede asociar a cualquier extensión de archivo (de acuerdo a lo permitido por el IIS). Los GH sin embargo, solo se pueden asociar a la extensión ASHX que está directamente soportada por los proyectos web en visual Studio 2005 y posteriores. Todos los Handlers implementan System.Web.IHttpHandler. Además, en IIS 7 se puede alojar cualquier Handler directamente.
El hecho que el GH pueda correr fuera del entorno de una página y aparte procesar HTTPRequests, lo hace una herramienta perfecta para ofrecer servicios de este tipo a otras aplicaciones, cuando no se han implementado como WebServices ya sea por requerimientos del negocio o requerimientos no funcionales.

Por qué puede no ser deseado un WebService?

Según la arquitectura y requerimientos de algunos clientes, es mejor recibir resultados a través de HTTPRequest "pelado", debido a que por ejemplo el llamado se hace desde una plataforma distinta a .NET desde la cual se hace bastante complejo crear un llamado a un WebService, tal vez porque la herramienta no puede manejar todos los tipos estándar en los WebServices (como sucede por ejemplo con PHP).

Entonces por qué no hacer una página Web Normal que responda a los llamados?

Si se crea una página aspx que responde a las peticiones se incurre en adicionales encabezados y todo el overhead adicional que genera la creación de una página completa (viewstate, etc), cuando en realidad solo se desea obtener una simple respuesta (una imágen un xml, etc).

Entonces para ganar performance y facilidad de administración en este tipo de funciones, es posible crear un Generic Handler sin dejar de atender al requerimiento de que la comunicación permanezca sencilla.

Entre los métodos obligatorios al estarse implementando IHttpHandler está ProcessRequest que es el que ejecuta el proceso requerido y por ende al fnal de su alcance habrá de tener un llamado a context.Response.Write o similar, que devuelva una respuesta http. Esta respuesta puede ser html, txt plano, imágenes, xml, etc.

Otra utilidad muy práctica es la de presentar objetos de memoria (entidades) en páginas WEB. La idea es tomar un objeto (serializable) en memoria que tenga representación XML. Se toma esta representación XML y se pasa por una transformación XSLT, produciéndose un HTML que representa a dicho objeto. Una de las aproximaciones para mostrar este HTML es grabarlo en un archivo y luego en otra página con un IFrame cargar dicho archivo. Pero como es obvio, el overhead de crear y borrar estos archivos físicos generados es absolutamente inaceptable. Otro enfoque es incluir en la página un control XML que muestre el objeto serializado y en el cual luego de hacer la transformación se vea el HTML como tal. Es una alternativa muy aceptable que a primera vista no tiene ninguna desventaja. Pero usando GH, se obtiene una control más directo sin el overhead que implica agregar un control XML a una página que además tendrá otros elementos que sumaran innecesariamente peso al resultado. Al crear un GH que tenga un tipo de respuesta XML, éste puede ser llamado (los GH se llaman como cualquier otra página aspx. Además también pueden aceptar parámetros: http://warnov.8m.com/miGH.ashx?param=valor;otroparam=otrovalor)a través de la su URL y el retorno obviamente será el HTML que representa al objeto deseado (siempre y cuando el XML incluya la directiva de transformación XSLT y el archivo XSLT se encuentre en la ruta que allí se especifica).
Como se observa, son muchas la aplicaciones que tienen estos objetos y es considerable la ganancia que se obtiene con su uso.

lunes, 18 de febrero de 2008

MediaMonkey extendido con C#


Es un opensource project que creé y subi a Google code, para probar. Aquí está el link https://mediamonkey-cs-tagger.googlecode.com/

Resultados de división en SQL: No se traen decimales por defecto?

Sujeto A: oiga una pregunta estupida de SQL
WarNov: a ver
Sujeto A:
DECLARE @Variable Float
SET @Variable = 170/100
SELECT @Variable

porque no me muestra decimaleS??
Sujeto A: alo??

WarNov: Hágala entonces más breve:
DECLARE @Variable FloatSET @Variable = 170.0/100.0
SELECT @Variable

Sujeto A: chambon
WarNov: CHAMBON SU * ahí no tiene nada de chambón
si ud no puede controlar los valores, entonces use:

DECLARE @Variable Float
SET @Variable = cast(170 as float)/cast(100 as float)
SELECT @Variable

contenta?