Sunday, March 30, 2008

(ZT) Asp.Net State Management

1.Application:用于保存所有用户共用的数据信息。 在Asp.Net中类似的配置数据最好保存在Web.config文件中。如果使用Application对象,一个需要考虑的问题是任何写操作都要在 Application_OnStart事件(global.asax)中完成。尽管使用Application.Lock和 Application.Unlock方法来避免写操作的同步,但是它串行化了Application对象的请求,当网站访问量大的时候会产生严重的性能 瓶颈。因此最好不要用此对象保存大的数据集。

使用如下:
//存放信息
Application["UserNameID"]="1000";
//读取信息
String NameID=Application["UserNameID"].ToString();

2.Session:用于保存每个用户的专用信息。Session中的信息保存在Web服务器的内存中,保存的数据量可大可小。当Session超时或被关闭时将自动释放保存的数据信息。对于小量的数据Session对象保存还是一个不错的选择。

使用如下:
//存放信息
Session["UserNameID"]="1000";
//读取信息
String NameID=Session["UserNameID"].ToString();

3.Cookie: 用于保存客户浏览器请求服务器页面的请求信息,其有效期可以人为设置,而且其存储的数据量很受限制,因此不要保存数据集及其他大量数据。而且Cookie以明文方式将数据信息保存在客户端的计算机中,因此最好不要保存敏感的未加密的数据。

使用如下:
//存放信息
Response.Cookie["UserNameID"].Value="1000";
//读取信息
String NameID=Response.Cookie["UserNameID"].Value;

4.ViewState: 常用于保存单个用户的状态信息,可以保存大量的数据但是过多使用会影响应用程序的性能。所有Web服务器控件都使用ViewStat在页面回发期间保存自 己的状态信息。每个控件都有自己的ViewState,不用时最好关闭以节省资源。通过给@Page指令添加"EnableViewState= false"属性可以禁止整个页面的ViewState

使用如下:
//存取信息
ViewState["UserNameID"]="1000";
//读取信息
string NameID=ViewState["UserNameID"].ToString();

5.Cache:用于在Http请求间保存页面和数据。它允许将频繁访问的大量服务器资源存储在内存中,当用户发出相同的请求时服务器不再次处理而是将Cache中保存的信息返回给用户,节省了服务器处理请求时间。

使用如下
//存放信息
Cache["UserNameID"]="1000";
//存放信息
Cache.Insert("UserNameID","1000");
//读取信息
String UserNameID=Cache["UserNameID"].ToString();

6.隐藏域:Hidden控件属于Html类型的服务器控件,可以实现隐藏域的功能,他和其他的空间没什么区别只是不会在浏览器上显示,始终处于隐藏状态。

使用如下:
//存放信息
Hidden.Value="1000";
//读取信息
String UserNameID=Hidden.Value;

7.查询字符串:将传递的值连接在URL后面,然后通过Response.Redirect方法实现客户端的重定向。

使用如下
Response.Redirect("User.aspx?UserNameID=10000&LevelD=100");
执行上面的语句后在IE地址栏显示的URL的代码如下:
http://localhost/User.aspx?UserNameID=1000&LevelID=100
当跳转到User.aspx后,可以通过下面代码获得传递的信息:
String UserNameID,LevelD;
UserNameID=Request.Params["UserNameID"];
LevelD=Request["LevelD"];

================================================================================

Application

1. Application用来保存所有用户共用的信息

2. 在Asp时代,如果要保存的数据在应用程序生存期内不会或者很少发生改变,那么使用Application是理想的选择。但是在Asp.net开发环境中我们把类似的配置数据放在Web.config中。

3. 如果要使用Application 要注意的是所有的写操作都要在Application_OnStart事件中完成(global.Asax),尽管可以使用Application.Lock()避免了冲突,但是它串行化了对Application的请求,会产生严重的性能瓶颈。

4. 不要使用Application保存大数据量信息

5. 代码:Application[“UserID”]=”test”;

String UserName=Application[“UserID”].ToString();

Session

1. Session用来保存每一个用户的专有信息

2. Session的生存期是用户持续请求时间加上一段时间(一般是20分钟左右)

3. Session信息是保存在Web服务器内存中的,保存数据量可大可小

4. Session超时或者被关闭将自动释放数据信息

5. 由于用户停止使用应用程序之后它仍在内存中存留一段时间,因此这种方法效率较低

6. 代码:Session[“UserID”]=”test”;

String UserName=Session[“UserID”].ToString();

Cookie

1. Cookie用来保存客户浏览器请求服务器页面的请求信息

2. 我们可以存放非敏感的用户信息,保存时间可以根据需要设置

3. 如果没有设置Cookie失效日期,它的生命周期保存到关闭浏览器为止

4. Cookie对象的Expires属性设置为MinValue表示永不过期

5. Cookie存储的数据量受限制,大多数的浏览器为4K因此不要存放大数据

6. 由于并非所有的浏览器都支持Cookie,数据将以明文的形式保存在客户端

7. 代码:Resopnse.Cookies[“UserID”]=”test”;

String UserName= Resopnse.Cookies [“UserID”].ToString();

ViewState

1. ViewState用来保存用户的状态信息,有效期等于页面的生命周期

2. 可以保存大量数据但是要慎用,因为会影响程序性能

3. 所有的Web服务器控件都是用ViewState在页面PostBack期间保存状态

4. 不需要则关闭 @page 里面设置EnableViewState=false

5. 代码:ViewState[”ID”]=”cc”;
String ID =ViewState[“ID”].ToString();

Cache

1. Cache用于在Http请求期间保存页面或者数据

2. Cache的使用可以大大的提高整个应用程序的效率

3. 它允许将频繁访问的服务器资源存储在内存中,当用户发出相同的请求后
服务器不是再次处理而是将Cache中保存的数据直接返回给用户

4. 可以看出Cache节省的是时间—服务器处理时间

5. Cache实例是每一个应用程序专有的,其生命周期==该应用程序周期
应用程序重启将重新创建其实例

6. 注意:如果要使用缓存的清理、到期管理、依赖项等功能必须使用Insert 或者Add方法方法添加信息

7. 代码:Cache[”ID”]=”cc”;或者Cache.Insert(“ID”,”test”);
String ID =Cache[“ID”].ToString();

Hidden

1. Hidden控件属于Html类型的服务器控件,始终处于隐藏状态

2. 每一次提交的时候它会和其他服务器控件一起提交到服务器端

3. 代码如下:Hidden.Value=”cc”;
string id=Hidden.Value; 要使用Runat=server

Friday, March 28, 2008

(ZT)ASP.NET Basics: Foundation of ASP.NET

 

This has been pooled together from a number of resources:

What is ASP.NET?

Microsoft ASP.NET is a server side technology that enables programmers to build dynamic Web sites, web applications, and XML Web services. It is a part of the .NET based environment and is built on the Common Language Runtime (CLR) . So programmers can write ASP.NET code using any .NET compatible language.

What are the differences between ASP.NET 1.1 and ASP.NET 2.0?

A comparison chart containing the differences between ASP.NET 1.1 and ASP.NET 2.0 can be found over here.

Which is the latest version of ASP.NET? What were the previous versions released?

The latest version of ASP.NET is 2.0. There have been 3 versions of ASP.NET released as of date. They are as follows :

ASP.NET 1.0 – Released on January 16, 2002.

ASP.NET 1.1 – Released on April 24, 2003.

ASP.NET 2.0 – Released on November 7, 2005.

Additionally, ASP.NET 3.5 is tentatively to be released by the end of the 2007.

Explain the Event Life cycle of ASP.NET 2.0?

The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :

PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.

Init – Each control in the control collection is initialized.

Init Complete* - Page is initialized and the process is completed.

PreLoad* - This event is called before the loading of the page is completed.

Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.

LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.

PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.

PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.

SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.

Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.

The events marked with * have been introduced in ASP.NET 2.0.

You have created an ASP.NET Application. How will you run it?

With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your pages. It functions as a local Web server. The only limitation is that remote machines cannot access pages running on this local server. The second option is to deploy a Web application to a computer running IIS version 5 or 6 or 7.

Explain the AutoPostBack feature in ASP.NET?

AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.

How do you disable AutoPostBack?

Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the controls of a page. AutoPostBack is caused by a control on the page.

What are the different code models available in ASP.NET 2.0?

There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.

Which base class does the web form inherit from?

Page class in the System.Web.UI namespace.

Which are the new special folders that are introduced in ASP.NET 2.0?

There are seven new folders introduced in ASP.NET 2.0 :

\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.

\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).

\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.

\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.

\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.

\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.

\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.

Explain the ViewState in ASP.NET?

Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.

You can disable viewstate by a control by setting the EnableViewState property to false.

What does the EnableViewState property signify?

EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.

There is an excellent article by Peter Bromberg to understand Viewstate in depth.

Explain the ASP.NET Page Directives?

Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:

@ Assembly - Links an assembly to the current page or user control declaratively.

@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).

@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.

@ Import - Imports a namespace into a page or user control explicitly.

@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.

@ MasterType - Defines the class or virtual path used to type the Master property of a page.

@ OutputCache - Controls the output caching policies of a page or user control declaratively.

@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.

@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.

@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.

@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.

This list has been taken from here.

Explain the Validation Controls used in ASP.NET 2.0?

Validation controls allows you to validate a control against a set of rules. There are 6 different validation controls used in ASP.NET 2.0.

RequiredFieldValidator – Checks if the control is not empty when the form is submitted.

CompareValidator – Compares the value of one control to another using a comparison operator (equal, less than, greater than etc).

RangeValidator – Checks whether a value falls within a given range of number, date or string.

RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a regular expression. Eg: Email validation.

CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled by the built in validators.

ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot or in a message box.

How do you indentify that the page is post back?

By checking the IsPostBack property. If IsPostBack is True, the page has been posted back.

What are Master Pages?

Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.

How is a Master Page different from an ASP.NET page?

The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.

How do you attach an exisiting page to a Master page?

By using the MasterPageFile attribute in the @Page directive and removing some markup.

How do you set the title of an ASP.NET page that is attached to a Master Page?

By using the Title property of the @Page directive in the content page. Eg:

<@Page MasterPageFile="Sample.master" Title="I hold content" %>

What is a nested master page? How do you create them?

A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.

What are Themes?

Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.

What are skins?

A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:

<asp:button runat="server" BackColor="blue" BorderColor="Gray" Font-Bold ="true" ForeColor="white"/>

Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.

What is the difference between Skins and Css files?

Css is applied to HTML controls whereas skins are applied to server controls.

What is a User Control?

User controls are reusable controls, similar to web pages. They cannot be accessed directly.

Explain briefly the steps in creating a user control?

· Create a file with .ascx extension and place the @Control directive at top of the page.

· Included the user control in a Web Forms page using a @Register directive

What is a Custom Control?

Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.

What are the differences between user and custom controls?

User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.

User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.

A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.

A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.

User controls are good for static layout whereas custom controls are good for dynamic layout.

Where do you store your connection string information?

The connection string can be stored in configuration files (web.config).

What is the difference between ‘Web.config’ and ‘Machine.config’?

Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.

Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.

There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.

What is the difference between Server.Transfer and Response.Redirect?

Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.

Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.

Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.

Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

What method do you use to explicitly kill a users session?

Session.Abandon().

What is a webservice?

Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

BuzzNet Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

Technorati Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

del.icio.us Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

IceRocket Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

LiveJournal Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

43 Things Tags: ASP.NET Basics, ASP.NET, ASP.NET2.0, CLR, MSIL, Web

Published Thursday, March 20, 2008 2:07 AM by mikedopp

Filed under: ASP.NET 2.0, ASP.NET

Thursday, March 20, 2008

(ZT) Effective C#

第1章  C#语言元素        1
条款1:使用属性代替可访问的数据成员        1
条款2:运行时常量(readonly)优于编译时常量(const)        12
条款3:操作符is或as优于强制转型        17
条款4:使用Conditional特性代替#if条件编译        25
条款5:总是提供ToString()方法        31
条款6:明辨值类型和引用类型的使用场合        38
条款7:将值类型尽可能实现为具有常量性和原子性的类型        44
条款8:确保0为值类型的有效状态        51
条款9:理解几个相等判断之间的关系        56
条款10:理解GetHashCode()方法的缺陷        63
条款11:优先采用foreach循环语句        70
第2章  .NET资源管理        77
条款12:变量初始化器优于赋值语句        82
条款13:使用静态构造器初始化静态类成员        84
条款14:利用构造器链        87
条款15:利用using和try/finally语句来清理资源        93
条款16:尽量减少内存垃圾        100
条款17:尽量减少装箱与拆箱        103
条款18:实现标准Dispose模式        109
第3章  使用C#表达设计        117
条款19:定义并实现接口优于继承类型        118
条款20:明辨接口实现和虚方法重写        125
条款21:使用委托表达回调        129
条款22:使用事件定义外发接口        131
条款23:避免返回内部类对象的引用        137
条款24:声明式编程优于命令式编程        142
条款25:尽可能将类型实现为可序列化的类型        148
条款26:使用IComparable和IComparer接口实现排序关系        156
条款27:避免ICloneable接口        163
条款28:避免强制转换操作符        167
条款29:只有当新版基类导致问题时才考虑使用new修饰符        172
第4章  创建二进制组件        177
条款30:尽可能实现CLS兼容的程序集        181
条款31:尽可能实现短小简洁的函数        186
条款32:尽可能实现小尺寸、高内聚的程序集        190
条款33:限制类型的可见性        194
条款34:创建大粒度的Web API        198
第5章  使用框架        205
条款35:重写优于事件处理器        205
条款36:合理使用.NET运行时诊断        208
条款37:使用标准配置机制        213
条款38:定制和支持数据绑定        217
条款39:使用.NET验证        224
条款40:根据需要选用恰当的集合        229
条款41:DataSet优于自定义结构        237
条款42:利用特性简化反射        246
条款43:避免过度使用反射        253
条款44:为应用程序创建特定的异常类        258
第6章  杂项讨论        265
条款45:优先选择异常安全保证        265
条款46:最小化互操作        270
条款47:优先选择安全代码        277
条款48:掌握相关工具与资源        281
条款49:为C# 2.0做准备        284
条款50:了解ECMA标准        293