martes, mayo 31, 2005

Obteniendo valores por QueryString

En el post anterior hablamos de zonas de riesgo y de que debemos verificar los datos que nuestra aplicación recibe de los usuarios. También mencionamos que es mucho el código adicional que debemos escribir si necesitamos verificar muchos datos y que deberíamos abstraer esa problemática. Pues bien, ahora vamos a ver un ejemplo de cómo hacer esto.

El problema que intentamos resolver es el siguiente. Nuestra aplicación presenta un listado en varias páginas y obtiene el número de página que debe mostrar a través del parámetro “pagina” pasado por QueryString. En un punto del código, necesito obtener un valor entero y en caso de no conseguirlo, el valor debe ser “1”, es decir, la primera página.


using System;
using System.Web;

namespace DWP.Web
{
/// Definimos la clase como sellada
/// para impedir la herencia

public sealed class Requester
{
/// Constructor privado para impedir
/// la creación de instancias.

private Requester(){}

/// Método estático para obtener
/// parámetros por QueryString

public static object FromQueryString(string key, object defaulValue)
{
/// Obtenemos el objeto Request actual
HttpRequest Request = HttpContext.Current.Request;
object o;
string val = "";

/// Verificamos si el valor existe
/// en el QueryString. Si no, devolvemos
/// el valor por default

if (Request.QueryString[key]!=null && Request.QueryString[key].ToString()!="") {
val = Request.QueryString[key].ToString();
} else {
return defaulValue;
}

/// Intentamos convertir el valor obtenido
/// al tipo de dato del valor default.
/// Si esto da error, devolvemos el
/// valor default.

try {
o = Convert.ChangeType(val, defaulValue.GetType());
} catch {
o = defaulValue;
}
return o;
}
}
}


Como podemos ver, el método “FromQueryString” tiene como tipo de retorno un object. Necesitamos que sea así porque vamos a devolver un objeto de tipo similar al valor por default. De esta forma, si estamos esperando un entero y por QueryString nos llegó un texto, el método devuelve el valor predeterminado, es decir, garantiza el tipo de dato devuelto.

Las siguientes son formas válidas de utilizar nuestra función:
///Esperamos un entero, si no, devuelve el valor 1.
int currPage = (int)Requester.FromQueryString("pagina",1);

///Esperamos una fecha, si no, 1 de enero de 2005.
DateTime currDate = (DateTime)Requester.FromQueryString("fecha", new DateTime(2005,01,01));


Les dejo a ustedes la tarea de crear los métodos que obtienen valores por Form y Cookies.

8 Comments:

At 7:34 PM, Blogger crisip26wlgribbel said...

Hot News From The Automotive Lending Industry!!

+++++++++Current Profile+++++++++
InterFinancial Holdings, Corp (IFLH)
Current Price $0.036
+++++++++++++++++++++++++++++

Is this an undiscovered gem priced to go higher!!
Please read the following Announcement in its Entirety and Consider the Possibilities�
Watch this One to Trade!

IFLH announces Senator David Cain has joined its Board of Directors!!

IFLH volume trading is beginning to surge with landslide Announcement. The value of this
stock appears poised for growth! This one should not remain on the ground floor for long.

BREAKING NEWS!!
InterFinancial Holdings, Corp. (OTC Pink Sheets: IFLH - News) announced that they have added
David Cain to their board of directors. David Cain is currently the Chairman of the advisory
board to TTI (Texas Transportation Institute). Senator Cain represented Senate District 2 for
eight years in the Texas Senate and Chaired the Senate State Affairs Subcommittee on
Transportation and served nine terms in the Texas House of Representatives for District 107.

During his twelve years as Chairman of the House Committee on Transportation, Senator Cain�s
efforts on behalf of the people of Texas have been widely recognized. He was named to Texas
Monthly Magazine�s list of Ten Best Legislators, the Dallas Morning News said he was one of
the outstanding legislators of the 73rd session, and the Texas Department of Transportation
awarded him the Russell H. Perry Award in 1995 for his efforts to gain public awareness of
the need for and benefits of transportation facilities in the State of Texas.

Jeffrey C. Bruteyn, Managing Director, stated, We at InterFinancial are proud to have such a
widely recognized Senator join our board and oversee out automotive lending division. His
affiliations and connections to the automotive industry will be invaluable to our company.
Senator Cain will be instrumental in expediting our approval to use a government issued Seller
Finance License.

Seller Finance Licenses are very difficult to obtain and are usually reserved for the Big Boys
with heavy lobbyists. These licenses are highly coveted because it allows the finance company
to collect the entire down payment, instead of paying a portion of it to the taxing authority.
This dramatically helps a finance company�s bottom line if the buyer defaults on the loan.

With the new GPS tracking systems being installed on every car to dramatically improve
repossessions and with Senator Cain on the Board of Directors, InterFinancial Holdings
is ready to take their business to the next level.

Conclusion:

The examples above show the Awesome, Earning Potential of little known Companies
That Explode onto Investor�s Radar Screens. This stock will not be a Secret for long.
Then You May Feel the Desire to Act Right Now! And Please Watch This One Trade!!
GO IFLH!

All statements made are our express opinion only and should be treated as such. We may own,
take position and sell any securities mentioned at any time. Any statements that express or
involve discussions with respect to predictions, goals, expectations, beliefs, plans,
projections, objectives, assumptions or future events or performance are not statements of
historical fact and may be "forward looking statements." Forward looking statements are based
on expectations, estimates and projections at the time the statements are made that involve a
number of risks and uncertainties which could cause actual results or events to differ materially
from those presently anticipated. This newsletter was paid four thousand dollars from a party
(IR Marketing). Forward looking statements in this action may be identified through the use of
words such as: "projects", "foresee", "expects". in compliance with Section 17(.b), we disclose
the holding of IF LH shares prior to the publication of this report. Be aware of an inherent
conflict of interest resulting from such holdings due to our intent to profit from the liquidation
of these shares. Shares may be sold at any time, even after positive statements have been made
regarding the above company. Since we own shares, there is an inherent conflict of interest in
our statements and opinions. Readers of this publication are cautioned not to place undue reliance
on forward-looking statements, which are based on certain assumptions and expectations involving
various risks and uncertainties that could cause results to differ materially from those set forth
in the forward- looking statements. This is not solicitation to buy or sell stocks, this text is
for informational purpose only and you should seek professional advice from registered financial
advisor before you do anything related with buying or selling stocks, penny stocks are very high
risk and you can lose your entire investment.

 
At 5:38 AM, Blogger louisfrie5883 said...

Make no mistake: Our mission at Tip Top Equities is to sift through the thousands of underperforming companies out there to find the golden needle in the haystack. A stock worthy of your investment. A stock with the potential for big returns. More often than not, the stocks we profile show a significant increase in stock price, sometimes in days, not months or years. We have come across what we feel is one of those rare deals that the public has not heard about yet. Read on to find out more.

Nano Superlattice Technology Inc. (OTCBB Symbol: NSLT) is a nanotechnology company engaged in the coating of tools and components with nano structured PVD coatings for high-tech industries.

Nano utilizes Arc Bond Sputtering and Superlattice technology to apply multi-layers of super-hard elemental coatings on an array of precision products to achieve a variety of physical properties. The application of the coating on industrial products is designed to change their physical properties, improving a product's durability, resistance, chemical and physical characteristics as well as performance. Nano's super-hard alloy coating materials were especially developed for printed circuit board drills in response to special market requirements

The cutting of circuit boards causes severe wear on the cutting edge of drills and routers. With the increased miniaturization of personal electronics devices the dimensions of holes and cut aways are currently less than 0.2 mm. Nano coats tools with an ultra thin coating (only a few nanometers in thickness) of nitrides which can have a hardness of up to half that of diamond. This has proven to increase tool life by almost ten times. Nano plans to continue research and development into these techniques due to the vast application range for this type of nanotechnology

We believe that Nano is a company on the move. With today�s steady move towards miniaturization we feel that Nano is a company with the right product at the right time. It is our opinion that an investment in Nano will produce great returns for our readers.

Online Stock trading, in the New York Stock Exchange, and Toronto Stock Exchange, or any other stock market requires many hours of stock research. Always consult a stock broker for stock prices of penny stocks, and always seek proper free stock advice, as well as read a stock chart. This is not encouragement to buy stock, but merely a possible hot stock pick. Get a live stock market quote, before making a stock investment or participating in the stock market game or buying or selling a stock option.

 
At 7:34 AM, Blogger travisdean9152 said...

I read over your blog, and i found it inquisitive, you may find My Blog interesting. My blog is just about my day to day life, as a park ranger. So please Click Here To Read My Blog

 
At 1:41 PM, Anonymous Rick J said...

I have been following a site now for almost 2 years and I have found it to be both reliable and profitable. They post daily and their stock trades have been beating
the indexes easily.

Take a look at Wallstreetwinnersonline.com

RickJ

 
At 9:40 AM, Blogger darreljackson4475647398 said...

While you read this, YOU start to BECOME aware of your surroundings, CERTIAN things that you were not aware of such as the temperature of the room, and sounds may make YOU realize you WANT a real college degree.

Call this number now, (413) 208-3069

Get an unexplained feeling of joy, Make it last longer by getting your COLLEGE DEGREE. Just as sure as the sun is coming up tomorrow, these College Degree's come complete with transcripts, and are VERIFIABLE.

You know THAT Corporate America takes advantage of loopholes in the system. ITS now YOUR turn to take advantage of this specific opportunity, Take a second, Get a BETTER FEELING of joy and a better future BY CALLING this number 24 hours a day.
(413) 208-3069

 
At 1:03 AM, Blogger Mike P. said...

Please read my blog or simply visit my site. My site is dedicated to product reviews:
Consumer Opinion on www.pissedconsumer.com
or you can visit my blog
Consumer Opinion on www.pissedconsumer.com

 
At 2:54 AM, Blogger Great Future said...

Unlimited Earnings Potential - http://1greatfuture.com

Our company is rapidly growing and offers you an extraordinary income helping others succeed. The primary requirement is to follow up on client inquiries and point them in the right direction. It is stress free, rewarding and straightforward work.

For complete details: http://1greatfuture.com


(Please feel free to delete this post if you don't want it on your blog. Thanks for the informative blog and opportunity to post.)

 
At 7:18 PM, Blogger Free Webmail Program said...

Webmail program for the major free email sites -
http://inovasphere.com/mmail.htm

My Mail 1.0 is configured to work with AOL, Gmail, Hotmail, Linuxmail, and Yahoo. With My Mail 1.0 you get the benefit of premium services without having to pay site fees. My Mail 1.0 completely automates the process of sending and receiving mail from the major sites, saving you time and trouble.

My Mail 1.0 eliminates the need to visit web sites to send and receive mail, which increases the speed of sending and receiving email by over 80%, even if they do not offer what is known as POP3, IMAP and SMTP. My Mail 1.0's look is also fully customizable. One you use it, you'll never want to go back to the web site again to get your mail.

For complete details: http://inovasphere.com/mmail.htm




(Please feel free to delete this post if you don't want it on your blog. Thanks for the informative blog and opportunity to post.)

 

Publicar un comentario en la entrada

<< Home