Magicajax (v0.2.1) Source Code Analysis

Source: Internet
Author: User
Magicajax (v0.2.1) Source Code Analysis
Release:9 degree it
Registration: 2005-12-10
Senior Engineer
Magicajax. net is an open-source framework designed to make it easier and more intuitive for developers to integrate Ajax technology into their web pages, without replacing the ASP. net controls and/or writing tons of JavaScript code.

From www.magicajax.net

And other popularAjaxFramework, suchAjax.netAnd so on,MagicajaxThe design concept is very characteristic and also usedAjaxTechnology, which is very convenient and easy to use.

From the perspective of developersAjax.netUnder the framework, we need to register a class that is published to the client, then access it in the client script, and then control the client interface changes based on the data returned from the server, which is not very convenient to use. InMagicajaxIn the frameworkCodeThe web page is not refreshed, and the work in the browser is likeWinformTo provide users with a seamless experience, greatly simplifying the work of developers.

from the perspective of the design architecture, ajax.net framework reference prototype. JS This pure script Ajax framework, if you register a type in ajax.net , in the Script output to the client, ajax.net generated for you JavaScript object, developers use it just like calling a server object. In fact, scripts are used for simulation, it is a bit like remoting Object interception. Of course, if you want to display something, for example, you have to fill a drop-down box with your own Operations DHTML . However, magicajax is another way of thinking. Do we not need to refresh the page? OK , you only need to put the control that you want to execute server-side events in ajapanel , magicajax submit the data to be submitted on the page in the background, submit it to IIS and pass it to the ajaxmodule registered in the configuration file, he is responsible for returning the script statements parsed by the framework to reflect the changes caused by server operations, client eval . How to obtain the script statement to implement this change becomes the main task of the Code.

From an innovative perspective, by using the storage page configuration,MagicajaxAlmost changedWebThe Programming ModelProgramModelWebProgramming. After that, we will introduce the source code in detail.

The preceding description is just an outline. Now, we start to analyze it step by step.MagicajaxSource code.MagicajaxRecently released0.2.2Because the changes are not too large0.2.1As an analysis sample.

If you want to useMagixajaxIn additionDLLIn addition, we need to add the following in the configuration file:

/// < Httpmodules >
/// < Add Name = "Magicajaxmodule" Type = "Magicajax. magicajaxmodule, magicajax"   />  
/// </ Httpmodules >

We can refer to the following entry points:MagicajaxmoduleStart analysis.

MagicajaxmoduleImplementedIhttpmoduleInterface to implementIhtppmoduleOfInitMethod, bind the applicationHttpapplicationOfBeginrequest, Acquirerequeststate, EndrequestEvent.

InBeginrequestPhase,MaStores the current contextRequestAndResponseVariable, which is necessary for analyzing requests and output scripts. At this stageAjaxcallobject. js. aspxThe request is responded and OutputAjaxcallobject. jsScript.

The most important processing isAcquirerequeststatePhase. Considering whether the storage of pages leads to two completely different programming models, for ease of description, wePagestoreMethods are discussed separately.

First, for the analysis of this part of code, we press<Pagestore mode = "nostore">. In this section, if the request isGetOr notAspxThe page is not processed. IfPagesstore = nostore, Then letAsp.netThe framework generates a new page based on the submitted page:

Httpcontext. Current. handler. processrequest (httpcontext. Current );

According to the normal page lifecycle Magicpanel Output Html What will it be? The code after the preceding method is: _ Response. Flush ();
String Vsvalue = _ Filter. getviewstatefieldvalue ();
If (Vsvalue ! =   Null   && _ Request. Form [ " _ Viewstate " ] ! = Vsvalue)
{
Ajaxcallhelper. writesetfieldscript ("_ Viewstate", Vsvalue );
}
Ajaxcallhelper. End ();

Here Ajaxcallhelper Stored write Viewstate . You can viewAjaxcallhelper. End () Before the method is completed, Response The entire page code is still in the content output to the client. In Ajaxcallhelper. End () After execution, the output code is the part of the page content that changes Javascript Code. Ajaxcallhelper. End () The Code is as follows: Public   Static   Void End ()
{
If (_ Writinglevel >   0 )
Throw   New Magicajaxexception ( " Script writing level shocould be 0 at the end of ajaxcall. increasewritinglevel CILS do not match decreasewritinglevel CILS. " );

Writeendsignature ();

Httpresponse HR = Httpcontext. Current. response;

HR. Clear ();
Mergenextwritinglevelrecursive ( 0 );
HR. Write (_ sbwritinglevels [ 0 ] As Stringbuilder). tostring ());

Magicajaxcontext. Current. completedajaxcall =   True ;

HR. Flush ();
HR. End ();
}

We can see from the aboveResponseIt was replaced when the output was sent to the client! The output isSbwritinglevelsOneStringbuilder. If you haveResponse. WriteThe output text of the code is ineffective. Here,MaMaintainsStringbuilderBecause the order of the output scripts in the control on the server side is inconsistent with that of the scripts executed on the client side, you need to design the output script level. The level of execution on the client side is higher, the subsequent execution level is a little lower, so that the output order of each statement executed by the script content is determined through the output level.

There is a problem here.JSWhen is the statement generated? The answer is:Render ().

MaContainerAjaxPanelDerived from abstract base classesRenderedbyscriptcontrol,RenderedbyscriptcontrolOverloadedRenderMethod,RenderThe method is called.Writescript ()Write the script,Writescript ()The abstract method is also called.Renderbyscript (),RenderbyscriptThe method is actually composedAjaxPanelThe typical template mode. Since the control is placed inAjaxPanelSo in the output sub-control content stage,AjaxPanelThe sub-controlHtmlMark in a segment<Span>In the tag, once the output content of the sub-control changes, you only need to change the correspondingSpanMarkedInnerhtmlYou don't have to worry about the control output.HtmlThe content has changed.

We can focus fully on AjaxPanel Of Renderbyscript Now, let's take a look at how the sub-control content changes are identified and recorded: // If it's HTML Rendering fingerprint is the same, ignore it.
If (Htmlfingerprint ! = ( String ) _ Controlhtmlfingerprints [con])
{
Extendedwritesethtmlofelementscript (HTML, getajaxelemid (CON ));
_ Controlhtmlfingerprints [con]=Htmlfingerprint;
}

This code isAjaxPanelThe internal control content is output and compared with the control content on the previous page. If there is any difference, the script is output. The previous page control content is a hidden field passed when the page is submitted._ Control_fingerprints_ajaxpanel1. For example:"Dd9a4f13; button1 # d8b12665; maid # 7059016e; textbox1 #1505", It indicatesButton1, datagrid1, textbox1OfHashcodeValue, which can be configuredHashcode, MD5, fullhtml. In this way, the fingerprint of the control content can be compared to determine which values should be changed through the script statement.

From the code and analysis, we can see that,NostoreOfAjaxWell maintained the existingAsp.netProgramming Model, not likeAjax.netDestroys the program model. WhileStoreModeMagicajaxThenWebformProgram Model directionWinformIt has been brought closer in an unprecedented manner, and perhaps the change is ahead.

InStoreUnder the model, we can choose to save the page instance objects inSessionAndCache.AjaxRequest, fromSessionOrCacheInstead of executing a lifecycle of the page, you can change the temporary page object to a resident memory object.

Let's take a look at how the changed script code is obtained in this mode.SessionThe storage method is used as an example.

InAcquirerequeststatePhase.NostoreCallHttpcontext. Current. handler. processrequestTo process the page generated by the request.PagekeySlaveSessionTo obtain the storage page object:

_ Magicajaxcontext. storedpageinfo = Getstoredpageinfo (pagekey );

Then callProcessajaxcallMethod to process this page. InProcessajaxcallMethod, such as a buttonClick:

String Target = _ Request. Form [ " _ Eventtarget " ];
String Argument = _ Request. Form [ " _ Eventargument " ];
Raisepostbackeventinchild (page, target, argument );

RaisepostbackeventinchildThe method is simple.RaisepostbackeventIf it is a buttonClickEvent, if we have a bindingClickThe event method can implementDataGridBind a data source.RaisepostbackeventTheseAsp.netAll the work completed on the page isMagicajax.

Protected   Void Raisepostbackeventinchild (page, String Eventtarget, String Eventargument)
{
Control eventcontrol=Page. findcontrol (eventtarget );

If(EventcontrolIsIpostbackeventhandler)
(Ipostbackeventhandler) eventcontrol). raisepostbackevent (eventargument );
}

After the data is updatedInvokescriptwritersMethod entryMagicpanelOfRenderbyscriptMethodNostoreThe same pattern must be usedMagicpanelTo generate differentiated script code, which is also generated by comparing controlsHtmlContent fingerprint to identify changes.

The core process of the framework is the above. In order to clarify the description, I omitted some things. If you are interested, you can check the code by yourself,MagicajaxThe annotations are well written and easy to understand.

So why?StoreProgramming Model andWinformClose? Here I will borrow this leaf articleArticleHttp://wj.cnblogs.com/archive/2005/12/29/307704.html:

Private   Void Button#click ( Object Sender, system. eventargs E)
{
Hyperlink Link= NewHyperlink ();
Link. Text= "Hyperlink" +Ajaxpanel1.controls. count;
Ajaxpanel1.controls. Add (Link );
}

TheNostoreAndSessionThe mode has different effects.Asp.netPage,PanelThere will always be only oneHyperlinkWhile the latter will continue to increase newHyperlinkOn the page, be familiarWinformProgramming friends know that this is the same effect as form programming, because the currentWebformAndWinformIn the same way, the status is maintained in the memory. Each request is a modification of the content rather than a re-generation. The frontend and backend are similar.

Set the desktop program andWebThe unified programming model of the program is almost the dream of many developers. Now, the dream suddenly becomes clearer. Is there any problem with such a good thing? Of courseMagicajaxFrom its own perspective, useSessionStorage consumes server resources, and its storage method only supportsInprocIf other storage methods are supported, it is believed that the application will become mature. If the page can be stored on the client, it may be detonated.Web2.0OfRiaRevolution. In addition, letWebDeveloper RegressionWinfromThe development model of is definitely a challenge. Which programming model to follow will certainly confuse developers, and the problems that may be caused by not necessarily mature versions are alsoMagicajaxContinue to stay in the lab stage.

I believe that in the foreseeable future,MagixajaxAnd its ideas will influence the futureWebDevelopment brings a new development model. The Flash is a prelude to the Revolution. Let's wait and see!
I would also like to thank ye wj.cnblogs.com for providing me with help, so that I have a better understanding of magicajax!

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.