KiMoGiGi 技术文集

不在乎选择什么,而在乎坚持多久……

IT博客 首页 联系 聚合 管理
  185 Posts :: 14 Stories :: 48 Comments :: 0 Trackbacks
P.S.
在页面获取Session、Request Param等值的一个有趣的方法,有点意思……

摘自:http://www.jigar.net/articles/viewhtmlcontent261.aspx

Read Asp.net Request Param and Session dynamically into properties

Download Source CodeRun Sample

Article shows how you can use Attributes and Reflection to dynamically populate property with value from param, session or context without writing any addition code.  I have used this technique in past and I hope you will also find it useful.

Why do I need this?

I am a lazy programmer, I won’t write a code that I do not have to, I also believe that amount of mistakes that I make while writing code is directly proportional to number of lines of the code that I write.

Why would I write following code?
publicint id;
publicstring userName;
void Page_Init(object sender, EventArgs e){
if (!string.IsNullOrEmpty(Request.QueryString["id"])){
id =int.Parse(Request.QueryString["id"]);
}
if(Request.Cookies["userName"] !=null &&
Request.Cookies["userName"].Value !=null){
userName = Request.Cookies["userName"].Value;
}
}
If I can just write following.
[PageProperty]
publicstring id;
[PageProperty(ReadFrom=DictionaryType.Cookie)]
publicstring userName;

Lets define what are we interested in reading

Most common place where we need to read data is query string dictionary but we will also read from additional places like Form, Session, Cookie, Headers and Dictionary that comes with Context. We will create flag that will define places that we can read data from.
[flags]
public enum DictionaryType
{
QueryString = 1,
Form = 2,
Session = 4,
Context = 8,
Cookie = 16,
Header = 32
}

Next step will be to create Attribute class for our properties and fields.


Attributes provide a powerful method of associating declarative information with code. We need two properties in our attribute
  1. Key which we need to pass to read data from dictionary, If user do not provide this key then we will assume that name of property/field is key.
  2. Enumeration that defines dictionary to read data from which will default to query string.
publicclass PageProperty : Attribute {
private DictionaryType readFrom = DictionaryType.QueryString;
privatestring key;
publicstring Key {
get { return key; }
set { key = value; }
}
public DictionaryType ReadFrom {
get { return readFrom; }
set { readFrom = value; }
}
}

Once we have above class we can tag fields in our page with above attribute.

[PageProperty(ReadFrom = DictionaryType.Cookie)]
publicint userId;

Reading attributes using reflection and populating values.

  1. We will use reflection to inspect page class to find all property or public fields with PageProperty Attribute. 
  2. Next step will be to get key and DictionaryType.
  3. And once we know source and target to populate and we will get information from appropriate dictionary and populate it.
We will warp this logic into a small static class with static Read method which takes reference of page object.

publicstaticvoid Read(object pageObject)
{
// read for all fields.
      FieldInfo[] fields = (pageObject.GetType()).GetFields();
foreach (FieldInfo fieldInfo in fields)
{
object[] attributes
= fieldInfo.GetCustomAttributes(typeof(PageProperty), false);
if (attributes.Length > 0)
{
PageProperty pageProperty = attributes[0] as PageProperty;
string key = pageProperty.Key;
if (key == null) key = fieldInfo.Name;
object val = getValue(key, pageProperty.ReadFrom);
if (val !=null)
{
fieldInfo.SetValue(pageObject
, changeType(val, fieldInfo.FieldType));
}
}
…….


Retriving value from Dictionary.

Since we are using flags user might specify more than one place to read from, for example user might specify following
[PageProperty(ReadFrom = DictionaryType.QueryString | DictionaryType.Cookie)]
To handle this we will go through all selected enumerations and return first with value, so in above mentioned example if query string value was present it will return query string value, otherwise it will return value from cookie.
privatestatic object getValue(string key, DictionaryType readFrom){
if ((readFrom & DictionaryType.QueryString)
== DictionaryType.QueryString &&
HttpContext.Current.Request.QueryString[key] !=null)
{
return HttpContext.Current.Request.QueryString[key];
} elseif ((readFrom & DictionaryType.Form)
== DictionaryType.Form &&
HttpContext.Current.Request.Form[key] !=null)
{
return HttpContext.Current.Request.Form[key];
}
…..

How to use Property Reader in your web page.

  1. Drop Jigar.Web.PagePropertyReader.dll in to bin directory of your web project
  2. In your Page class add following line in Pre_Init Event.
    PropertyReader.Read(this);
    Alternatively you can also create PageBase class by inheriting from System.Web.UI.Page and override PreInit event.
  3. Finally in your page just create public property or field with PageProperty Attribute and you are done.

Source code includes sample web application which shows usage of PropertyReader. It also includes test page with different senerios.

What about performance cost associated with reflection?

Reflection is definitely going to add some performance cost to your application, you will have to analyze value vs. cost analysis for your application and decide best for you.

Instead of reflection you might also want to try using Reflection.Emit to improve performance.
posted on 2007-12-02 16:02 KiMoGiGi 阅读(786) 评论(1)  编辑 收藏 引用 所属分类: ASP.NET

评论

# re: 洗车机[未登录] 2008-11-04 14:15 金龙
<a href="http://www.flyingcarwash.cn/xiche/xicheji.htm">洗车机</a> 传统清洗设备的冲击动能与清洗的介质都来自同一种物质—水。要想达到更好的清洁效果需要浪费更多的水。而真正有效的用水量只占总喷量的10%~20%,<a href="http://www.flyingcarwash.cn/xiche/zidongxicheji.htm">自动洗车机</a>绝大部分被蹦跑了,流失了。
  微水环保洗车成功的关键:改变了现有单相流、单介质的清洗原理,创造了高速气流配合水硬雾两相流清洗新概念:(模拟自然界暴风雨的现象—雨点把脏东西打掉,风把它带走。)
  微水环保洗车机分为两大部分:强力涡旋气流发生器每分钟产生3立方米、压力达12公斤力的高速气流,能更好地实现清洗冲击的动能;水硬雾喷射器将水以高速喷出,气、水混流过程中发生碰撞,依靠喷射、加温<a href="http://www.flyingcarwash.cn/xiche/xicheshebei.htm">洗车设备</a>、旋涡与空气磨擦等多重作用,使水直接雾化,并且水温升至20~30度,<a href="http://www.flyingcarwash.cn/xiche/diannaoxicheji.htm">电脑洗车机</a更容易进行汽车表面的清洗,实现节约用水。
  回复  更多评论
  

只有注册用户登录后才能发表评论。