Este artículo tratará sobre algunos tips o cosas que de repente necesitamos en ciertos momentos y son algo escondidas o difíciles de encontrar en la web. La estructura será la siguiente
Pregunta-Respuesta
Espero les guste el estilo:
Pregunta
Cuando tengo un error en una página, el cual no pueda controlar, necesito que no aparezca esa pantalla amarilla que siempre aparece mostrándole al cliente un error que no entiende. ¿Cómo puedo hacer una página de error general para toda la aplicación?
Respuesta
Web.config, esa es la respuesta. Se necesita configurar este archivo con los siguientes tags:

Explicaré un poco esto:
defaultRedirect = Acá colocaremos la página hacia donde deseo que se redirija mi aplicación cuando ocurra un error en ésta. Tener mucho cuidado, pues si se coloca como default una página que intencionalmente tiene error, se puede quedar en un bucle infinito debido a que solicitaría a cada momento la página de error.
mode= El modo puede ser de 3 tipos:
- On à Habilita al tag CustomErrors para redirigirse a la página de error que uno indica en defaultRedirect.
- Off à Deshabilita los CustomErrors, de tal forma que si sucede un error, el cliente verá la clásica página amarilla.
- RemoteOnly à Este es el más interesante de todos. Permite mostrar al cliente los CustomErrors ante un error de la aplicación, sin embargo, los errores que ocurren son mostrados al localhost,
Pregunta
Muchas veces llego a escuchar en el trabajo “oe, lo he compilado como 40 veces durante el día y mi máquina ya está lenta, reinicio la PC, cierto?”
Respuesta
NO, para solucionar la limpieza de memoria luego de cierta cantidad de compilaciones que uno realiza a su aplicación, uno puede usar el web.config para esto, de la siguiente manera:
Creo que casi todos conocen lo que hacen las propiedades defaultLanguage y debug, así que no describiré estos, me iré directo al que nos interesa:
numRecompilesBeforeAppRestart = Lo que hace esta propiedad es setear la cantidad de veces que uno debe compilar previamente a que el Visual Studio limpie(libere) la memoria para que así la PC no la sientan tan lenta.
Pregunta
Muchos me han dicho que puedo controlar un evento de varios botones o componentes con un solo método, me averigüe que esto es cierto, pero no tengo idea de cómo saber qué botón fue el que levantó el evento.
Respuesta
Dentro de un evento, normalmente tenemos lo que son (object sender, EventArgs e), pues lo que buscamos está en el primer parámetro que no está por las puras ahí.
Ahora, supongamos que lo que tenemos son 3 botones, el procedimiento para saber cuál levantó el evento el siguiente:
//Obtenemos el elemento casteándolo
Button b = (Button)sender;
//Como sabemos, cada boton tiene un identificador único, entonces nos guiamos por eso
if (b.ID == “miBoton”) {…….}
Obviamente Uds se encargarán de llenar toda la lógica, eso no corresponde a este tutorial =P.
Pregunta
He visto muchas páginas web que pueden detectar tu sistema operativo, tu browser, su versión, si acepta cookies o no, entre otras cosas. Sé que se puede hacer por javascript, hay millones de códigos por toda la red, pero si deseo hacerlo por medio de C# o VB, es esto posible?
Respuesta
SI, para resolver este problema solo tenemos que usar la clase HttpBrowserCapabilities y obtener la propiedad Browser de Request. Es decir, algo así:
HttpBrowserCapabilities miBrowser = Request.Browser;
De esta forma podemos obtener
- Nombre del browser = miBrowser.Browser
- Version del browser = miBrowser.Version
- ¿Es una versión beta mi browser?= miBrowser.Beta
- Sistema operativo = miBrowser.Platform
- Soporte de cookies = miBrowser.Cookies
- Soporte de JavaScript = miBrowser.EcmaScriptVersion
Y pueden obtener muchísimos más datos, pero para este ejemplo, solo deseamos motrar esto.
Pregunta
Obtengo ciertos requisitos de mis clientes que me indican que el título de su página debe de variar según el usuario que ingresa, aparte de tener un diferente estilo de componentes según el usuario, existe alguna clase que me otorgue el .Net para esto?
Respuesta
Sí, para un caso como éste, tenemos una clase muy específica llamada Page, con esta clase podemos obtener varias cosas como el título, la hoja de estilos, el id anónimo del usuario, el queryString, etc. Todo lo que obtenemos podemos modificarlo de tal forma que sea dinámico y varíe según el usuario que ingrese a nuestra aplicación.
Page.Header.Title; //Obtenemos el título de la página y puede setearse
Page.Header.StyleSheet; // Obtenemos la hoja de estilos que va a tener
Page.Request.AnonymousID; // Obtenemos el id anónimo del usuario
Page.Request.QueryString; //Obtenemos el queryString
Resaltaré este último, pues con éste podemos obtener los parámetros que nos pasen por medio de la url, es decir, los parámetros que van luego del símbolo “?”. Como por ejemplo:
http://www.pucp.edu.pe/content/seccionweb_home.php?pIDSeccionWeb=23&pID=103
Eso es todo, espero les haya gustado estos pequeños tips que muchas veces los clientes pueden solicitar, o si deseamos un portal con un portlet con la información del browser del usuario o cosas por el estilo.
---------------ENGLISH----------------
In this article i’m going to show some tips o things that sometimes we need and they are hard to find in the Web.
The structure of the article will be like Question/Answer. I hope you like it:
Question
Sometimes my application have some errors, but i don’t want to show a “yellow page”, because that’s a bad practice. How can I redirect to a custom error page in my entire application?
Answer
Web.config is the answer. You need to configure this file with the next tags:

defaultRedirect = In this property we put the page where we want to redirect our application if we have an error. But, be careful, if you put a page with mistakes in this property, it will cause an infinite loop, because you have a mistake and it will redirect to your custom error page, again, and it will cause a redirect again, again, again….
mode= It have 3 configurations:
- On à Enable the CustomErrors tag to redirect to your Custom Error page.
- Off à It disable the CustomErrors tag, so the client will see the “yellow page” if there is an error.
- RemoteOnly à This is the most interesting configuration. With this configuration the client will see your custom error page, but, the error page will be showed at localhost.
Question
A lot of times i feel that my PC is really slow when I’ve compiled my application a lot of times, and I need to restart it to be ok. What should I do to don’t restart my PC?
Answer
You should clean your memory in automatic way. It can be done with a configuration in the web.config, you just should do:

I think that everybody knows the meaning of defaultLanguage and debug, so i will explain just numRecompilesBeforeAppRestart
numRecompilesBeforeAppRestart = With this property you will indicate to the application that it will clean the memory alter you have compiled “n” times your application. Of this way your PC won’t be slow.
Question
A lot of people tell me that I can control with just one method an event of a lot of components. I investigate it, and that’s true, but how can I know which component triggered the event.
Answer
When we declare a method of a event, it have two parameters (object sender, EventArgs e). Well, we have the answer in the first parameter. We know that our components have an unique Id, so, if we get the id of the component, we can know which component triggered the event. So, we need to do this:
//We get the element casting the sender
Button b = (Button)sender;
//Now, we get the id of the button to recognize which is the component
if (b.ID == “miBoton”) {…….}
Question
I’ve seen a lot of pages that detects your SO, the version of your browser, and other things. I know a way to do it with javascript, but, is there any way to do it with C# or VB?
Answer
Yes, we can do it with the class HttpBrowserCapabilities and we can get it from the property Browser of the class Request. Something like this:
HttpBrowserCapabilities miBrowser = Request.Browser;
Of this way we can get
- Browser’s name = miBrowser.Browser
- Browser’s version = miBrowser.Version
- ¿Is my browser a beta version?= miBrowser.Beta
- SO = miBrowser.Platform
- Support of cookies = miBrowser.Cookies
- Support of JavaScript = miBrowser.EcmaScriptVersion
Obviously you can get more information.
Question
Sometime my clients need to change the title of the page, because it depends of the user, and sometimes, even the style sheet depends of the user. Is there anyway to do this?
Answer
Yes, You can do it with the class Page, you can get and modify the style sheet, title, anonymous id of the user, etc.
Page.Header.Title; //Here we get the title
Page.Header.StyleSheet; // We get the style sheet
Page.Request.AnonymousID; // We get the anonymous Id
Page.Request.QueryString; //we get the queryString
The most important is the queryString, because whit it you can get the parameters of our url. The parameters are next to the symbol “?”. Like this:
http://www.pucp.edu.pe/content/seccionweb_home.php?pIDSeccionWeb=23&pID=103
I hope you enjoyed these little tips that sometimes we need in a little or big application.
Enjoy it =D
I'm waiting your comments =)
Estoy esperando sus comentarios =)
Shinji