About contexts (context)/2 (Transfer ms)

Source: Internet
Author: User
Tags error handling integer log

[Visual Basic]

<script language= "VB" runat= "Server" > Sub page_load (sender as Object, E as EventArgs) {If user.identity.i sauthenticated Then welcome. Text = "Welcome" + User.Identity.Name Else is not signed in, add a link to the login page welcome. Text = "Please log in!" "Welcome. NavigateUrl = "signin.aspx" End If end sub</script><asp:hyperlink id= "Welcome" runat= "Server" maintains Tate= "false" ></asp:HyperLink>

[C #]

<script language= "C #" runat= "Server" > void Page_Load (object sender, EventArgs e) {if (User.Identity.IsAut henticated) {welcome.        Text = "Welcome" + User.Identity.Name; else {//not logged in, add a link to the login page welcome. Text = "Please log in!"            "; Welcome.        NavigateUrl = "signin.aspx"; }</script><asp:hyperlink id= "Welcome" runat= "Server" maintainstate= "false" ></asp:HyperLink>
Context.items Introduction
Hopefully, the above example illustrates how easy it is to write a WEB application with the only contextual information at hand. Well, wouldn't it be nice if you could access some of the contexts that are unique to your application in the same way?
This is Context.itemsThe purpose of the collection. It saves the application's request-specific values by using methods that are available in the parts of the code that participate in processing the request. For example, the same piece of information can be used in Global.asax, ASPX pages, user controls within pages, or by the business logic of page calls.
Consider the IBuySpy Portal application example. It uses a simple homepage desktopdefault.aspx to display portal content. The content that is displayed depends on the selected tab and the user (if authenticated) role.

Figure 2:ibuyspy Home
The query string contains the Tabindedx and TabID parameters of the tab that is being requested. This information is used throughout the process of processing the request to filter the data to be displayed to the user. http://www.ibuyspyportal.com/DesktopDefault.aspx?tabindex=1&tabid=2 (English)
To use a query string value, you need to first make sure that it is a valid value, and if not, do some error handling. It's not a bunch of code, but do you really want to copy it in every page and component that uses that value? Of course not! In the Portal example, even more is involved, because once we know tabid, we can preload other information.
The Portal uses the query string value as a parameter to construct a new portalsettingsobject, and adds it to the Global.asax beginrequestOf the event Context.itemsIn Because a start request is executed at the beginning of each request, the value associated with the tab is available in all pages and components of the application. When the request is complete, the object will be discarded automatically-very neat!

[Visual Basic Global.asax]

      sub Application_BeginRequest (sender as [Object], E as EventArgs)                    dim TabIndex as Integer = 0         dim tabid as Integer = 0                    ' Get tabindex  from query string         if Not (Request.params ("TabIndex") are nothing) then             tabindex = Int32.Parse (Request.Params ("TabIndex"))          end if                    ' Get tabid       from query string    if Not (Request.params ("TabID") are nothing) then             tabid = Int32.Parse (Request.params ("TabID"))           end if                   context.items.add ("Portalsettings", _new portalsettings (TabIndex, tabid))        end Sub

[C # Global.asax]

void Application_BeginRequest (Object sender, EventArgs e) {             int TabIndex = 0;    int TabID = 0;    //fetch from query string TabIndex& Nbsp;   if (request.params["TabIndex"]!= null) {                        tabindex = Int32.Parse (request.params["TabIndex"]);    }                     //gets tabid    if from the query string ( request.params["TabID"]!= null) {                       tabid = Int32.Parse (request.params["tabId");     }    context.items.add ("Portalsettings", New Portalsettings (TabIndex, tAbid));} 

Desktopportalbanner.ascx user Controls from ContextRequests the Portalsetting object to access the name and security settings of the Portal. In fact, this module is in operation ContextA typical synthesis example. To illustrate this point, I have simplified the code and marked the HTTP or application-specific ContextAll the places that have been visited.

[C # Desktopportalbanner.ascx]

<%@ import namespace= "aspnetportal"%><%@ import namespace= "System.Data.SqlClient"%><script language=    "C #" runat= "Server" > public int tabIndex;    public bool ShowTabs = true;    protected String Logofflink = ""; void Page_Load (Object sender, EventArgs e) {//Gets portalsettings from the current context portalsettingsportalsettings =(portalsettings)context.items["Portalsettings"];Dynamically populate portal site name Sitename.text =portalsettings.        Portalname; If the user is logged in, the custom welcome information if (request.isauthenticated= = True) {Welcomemessage.text = "Welcome" +Context.User.Identity.Name+ "!            < "+" span class=accent "+" >|< "+"/span "+" > "; If the authentication mode is a Cookie, provide a logout link if (Context.User.Identity.AuthenticationType= = "Forms") {Logofflink = "<" + "span class=\" accent\ ">|</span>\n" + "<a href=" +Request.applicationpath+ "/admin/logoff.aspx class=sitelink> cancellation" + "</a>"; }///Dynamic Display Portal tab bar if (ShowTabs = = true) {TabIndex =portalsettings.            Activetab.tabindex;            Generate the options to display to the user tabs ArrayList authorizedtabs = new ArrayList ();            int addedtabs = 0; for (int i=0 i <portalsettings. Desktoptabs.count; i++) {TabstripdetailsTab= (tabstripdetails)portalsettings.                Desktoptabs[i]; if (Portalsecurity.isinroles (Tab. Authorizedroles)) {Authorizedtabs.add (Tab);                }                 if (AddedTabs = = TabIndex) {                     tabs. SelectedIndex = addedtabs;                 }                 addedtabs++;            }                       // Fills the tabs//list             tabs at the top of the page with an authorized tab. DataSource = Authorizedtabs;            tabs. DataBind ();         }    }</script><table width= "100 % "cellspacing=" 0 "class=" headbg "border=" 0 ">    <tr valign=" Top ">    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TD colspan= "3" align= "right" >             <asp:label id= "Welcomemessage" runat= "Server"/>              <a href= "<%=Request.applicationpath%> ">portal home </a><span class=" accent "> |</span> <a href=" <%=Request.applicationpath %>/docs/docs.htm ">                 portal Document </a>            <%= Logofflink%>                       </td>    </tr>    &NBSP;&LT;TR&GT;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TD width= "Ten" rowspan= "2" >                      &NBSP;&LT;/TD&GT;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TD height= ">    "         <asp:label id= "SiteName" runat= "Server"/>   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;/TD&GT;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TD align= " Center "rowspan=" 2 ">               </td>     </tr>    <tr>         <td>            <asp:datalist id= " Tabs "runat=" Server >                <ItemTemplate>                     <a href= ' <%= Request.applicationpath   %>/desktopdefault.aspx?tabindex=<%# container.itemindex%>&tabid=<%# ((TabStripDetails) Container.DataItem). TabID%> ' ><%# ((tabstripdetails) Container.DataItem). TabName%></a>                  </ItemTemplate>                 <SelectedItemTemplate>                                       <span class= "SelectedTab" ><%# ( tabstripdetails) Container.DataItem). TabName%></span>                  </SelectedItemTemplate>             </asp:datalist>        </td>    </tr></ Table>

You can use Visual Basic and C # to browse and run the full source files of the IBuySpy Portal online in http://www.ibuyspy.com (English), or to run them after downloading. Summary
Contextis another "keep improving" function in the asp.net. It extends the already good context support of the ASP to add two hooks to the new run-time functionality of ASP.net. Also adds a Context.itemsAs a new state mechanism for short-term values. But for developers, the biggest benefit of this feature is that it's more compact and easy to maintain, and we all understand this context.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.