Home
Home Page
In detail about Robots.txt
Safe programming on PHP
We write elementary rassylhhik
Use of HTML-tables for a conclusion of diagrams
What is dorvei? Whether Banjat for them?
How to learn{find out} on what searches find my site in search machines?
Cunnings of tabulared design. (we form a framework of the table)
The guest book on PHP
BB-codes
We hide counters
Use of patterns of design in ASP.NET
RSS the generator
Search optimization of a site
Metatags
Optimization for MSN
We
Cookies - fresh rolls
Superdynamical webs - interfaces
Links
 

Use of patterns of design in ASP.NET


The introduction


Let's not stop in detail on the idea of use of patterns, including the reader familiar with her (differently it is recommended in the beginning will familiarize with ideas FastTemplate for Perl or PHP, Smarty for PHP).


As patterns it is understood not that is patterns in terminology .NET, we shall consider old enough and it is good myself recommending in other languages of web - programming (PERL, PHP) technology of patterns of design. We shall name them further so - patterns of design to avoid mess.


So, one of the basic ideas of patterns of design is maximum full raznesenie a program code and his  html-performance. For example, when it is necessary to deduce{remove} a greeting to the user, we prepare a pattern of design:



<HTML>

<BODY>

<P> Welcome in system {{FIRST_NAME}} {{LAST_NAME}} </P>


<P> Last time you came to us {{LAST_LOGIN_DATE}} </P>

<P> Today {{NOW_DATE}} </P>

</BODY>

</HTML>


Also we use it  in obrabotchike patterns. We inform obrabotchiku patterns a file containing a pattern of design, value of variables (FIRST_NAME, LAST_NAME:) then mozhen to receive from him  the processed pattern. Processing can look, for example, so:



MyParserCalss _Parser = new MyParserCalss ();

_Parser. OpenTemplate ("c:\inetpub\wwwroot\template\templates\template.html");

_Parser. SetVariable ("FIRST_NAME", "xxxx");

_Parser. SetVariable ("LAST_NAME", "xxxx");

_Parser. SetVariable ("LAST_LOGIN_DATE", "2003-03-02");

_Parser. SetVariable ("LAST_NAME", Sysem. DateTime. Now. ToString ());

Response. Write (_Parser. ParseToString ());


In the elementary case processing of a pattern represents replacement of all variables in his  text on their values.


What gives use of a similar intermediate layer besides loss of resources of the server on additional processing?


Usually the basic advantages of such approach the following name:



?         Division of the programmer and the designer - they do not prevent to each other, can work in parallel above one page, thus probability of that they will bring in infringements to the code written by the friend - friend is shown to a minimum.

?         The programmer can not wait for development / the statement of design and at once start to work - he throws a draft copy of design of the page necessary to him (usually - only variable and some separators that variables did not merge) and works with it . Later, when for page the design will appear, verstal`hhik will adhere it  to this page (and the programmer can not know about it at all)

?         It is possible to appoint different design to the same page depending on the some people in parameter

?         It becomes much easier to accompany with system, to support her , to change design.


All these advantages are significant enough at job with Perl, PHP or ASP. Really, one division of a code and performance of page of that it is necessary - once having tried to apply patterns of design to this purpose, you cannot force to return any more yourselves to a usual mash of a code and elements of design (<sausage> as its{her} some programmers contemptiously name).


With arrival ASP.NET the situation was changed - this technology represents the ways of the decision of a problem raznesenija design and a code of page. For many programmers, before patterns of design successfully using technology, became very uneasy choice what to do{make} further - to continue her  to use (and by that to refuse many interesting opportunities in ASP.NET, conflicting with patterns), or, on the contrary, to refuse patterns for the benefit of innovations ASP.NET?


Nevertheless, there are areas where application of patterns of design is justified and now. We shall consider such two examples of such areas.



Opravka mails


Your site sends letters at registration of new users, restoration of the forgotten password or others? Undoubtedly, the answer - <yes>.


The text of the letter is tekstovka at which some elements - variables. Application here patterns of design obviously arises.


What is it will give?



?         Texts of letters will not be vkompilirovanny in dll a site - i.e. if us to be necessary to correct a grammatic mistake or to change the text of the letter, it is not necessary perekompilirovat` after that a site. You will simply correct a test file.

?         Everybody can change the text of letters, not only the programmer. The owner of a site can do{make} it even.

?         You can have in the library of a code ready obrabotchiki patterns of design for often meeting pis`m (for example, restoration of the password) and simply to add them in the project, it is required to bring in changes only to the text of the letter.


Such approach appears in a result, is very convenient, both in programming, and in use. Superimposed expenses for expenses of additional resources of the server are scornfully small (especially if you use optimized obrabotchik the patterns, competently written, kehshirujuhhij, etc.)



One contents, some kinds of performance


Present a situation when at you on page of a site some contents (for example, the analytical report) are displayed. And these contents, besides simple display to page, it is necessary, first, to be able to present in the kind optimized for a seal, second, to be able to export in Excel. I do not know, how at you, and in my practice such problems{tasks} meet constantly.


As a matter of fact, there is one obrabotchik and three kinds of performance of results of his  job.


Such problem  very simply is solved application of patterns of design - you simply have three (4, 5:) different a pattern. And if then you ask to add to this page also the link <to send the friend>, it will not cause in you nervous reactions.


Let's write idle time obrabotchik patterns for this problem



Idle time obrabotchik patterns


So, we shall write idle time obrabotchik patterns of design which it will be simple to replace variables in a pattern with their values and it is more than anything.


At a class obrabotchika will be three methods:



?         OpenTemplate - opens a file containing a pattern of design

?         SetVariable - sets value of a variable

?         ParseToString - parsit all pattern at line


Class very simple, therefore we shall simply result his  code:



///

/// A class being obrabotchikom of patterns of design

///

public class Parser

{

  ///

  /// The tag - terminator of a variable (okryvajuhhij)

  ///

  public const string TagOpen = " {{";


  ///

  /// The tag - terminator of a variable (okryvajuhhij)

  ///

  public const string TagClose = "}} ";


  ///

  /// A way to a file containing a pattern of design

  ///

  private string TemplateFile = " ";


  ///

  /// Here we shall store{keep} values pronicializirovannykh variables

  ///

  private Hashtable Variables;


  ///

  /// We open a file containing a pattern of design, in passing checking his  existence

  ///

  ///

  public void OpenTemplate (string TemplateFullPath)

  {

    if (File. Exists (TemplateFullPath))

    {

      TemplateFile = TemplateFullPath;

}

    else

    {

      TemplateFile = " ";


      throw new Exception (String. Format (" Parser. OpenTemplate: the file {0} does not exist ", TemplateFullPath));

}

}


  ///

  /// Installation of value of a variable in a pattern of design

  ///

  /// The name of a variable

  /// Value of a variable

  public void SetVariable (string VariableName, object VariableValue)

  {

    Variables [VariableName] = VariableValue. ToString ();

}


  public string ParseToString ()

  {

    StreamReader _SR = new StreamReader (TemplateFile);


    StringBuilder _SB = new StringBuilder ();

             

    // We try to read contents of a file of a pattern of design

    try

    {

      _SB.Append (_SR.ReadToEnd ());

}

    catch

    {

      // Can access no, and can, the disk with hot replacement was...

      throw;

}

    finally

    {

      _SR.Close ();

}


         

    // We shall replace all variables in a pattern with their values

    foreach (string VariableName in Variables. Keys)

    {

     _SB.Replace (Template. Parser. TagOpen+VariableName+Template. Parser. TagClose, Variables [VariableName] .ToString ());

}


    return _SB.ToString ();

}


  ///

  /// The designer, initializes necessary variables

  ///

  public Parser ()

  {

    Variables = new Hashtable ();

}

}




Now we shall prepare three patterns - for display of usual contents, the version for a seal and for export in Excel. The first pattern is trivial:



<HTML>

<HEAD>

  <TITLE> </TITLE>

</HEAD>

<BODY>

  <TABLE ID = "Table1" CELLSPACING = "0" CELLPADDING = "0" WIDTH = " 100 % " BORDER = "0">

    <TR>

      <TD WIDTH=203> Report * {{NUMBER}} </TD>

      <TD COLSPAN = "2">

        <P align=right> Type * {{TYPE}} </P>

      </TD>

    </TR>

    <TR>

      <TD> Periode </TD>

      <TD> {{DAT_START}} </TD>

      <TD> {{DAT_END}} </TD>

    </TR>

    <TR> <TD COLSPAN = "3"> <HR> </TD> </TR>

    <TR> <TD COLSPAN = "3"> {{TEXT}} </TD> </TR>

    <TR> <TD COLSPAN = "3"> <HR> </TD> </TR>

    <TR>

      <TD COLSPAN = "2"> </TD>

      <TD> Verify {{MANAGER}} </TD>

    </TR>

  </TABLE>

</BODY>

</HTML>


The second pattern (the version for a seal) differs from the first insignificantly, we shall not result it  (you can see it  in materials to clause{article}).


The third file (the version for export in Excel) represents the certain interest. Since Office 2000, Microsoft has entered in Excel very interesting format - Excel XML. He is interesting to those, what is it idle time XML a file with the certain marking, hence, from our point of view this simply next performance of design. In general, to prepare a pattern for this file, it is necessary to understand structure Excel XML, but as truly lazy programmers we shall go easier (and in the optimum way):). We shall open Excel and we shall simply type{collect} in him it is necessary a kind the text. After that we shall choose in menu File Save As command and we shall specify at preservation of a file what to save it  it is necessary as Excel XML. That's all - the pattern is ready.


Further we shall write page which will open and process these patterns:



///

/// Page above which we shall put experiments

/// On an input{entrance} we accept number{room} of a pattern (? Template =):

/// 1 - usual

/// 2 - the version for a seal

/// 3 - Excel the version (for opening demands Excel 2000 or XP)

///

public class Default: System. Web. UI.Page

{

  ///

  /// Not Page_Load - what for to us these lishnii initialization, all the same it is not used.

  /// Here in general the question at issue, whether costs{stands} from System. Web. UI.Page to be inherited

  ///

  ///

  override protected void OnInit (EventArgs e)

  {

    string UseTemplateNumber = "1";


    // We read - out number{room} of a file templejtov which to us needs to be opened, just in case having checked up

    if (Request. QueryString ["Template"]! = null)

    {

      UseTemplateNumber = Request. QueryString ["Template"] .ToString ();

             

      if (UseTemplateNumber! = "1" ** UseTemplateNumber! = "2" ** UseTemplateNumber! = "3")

        UseTemplateNumber = "1";

}


    Trace. Warn (" Have started to work with templejtami ");


    // We open ours parser and the file containing a pattern of design is fed to him

    Parser _Parser = new Parser ();


    _Parser. OpenTemplate (String. Format (" {0} Templates/default _ {1} .htm ",

                 AppDomain. CurrentDomain. BaseDirectory, UseTemplateNumber));



    // We set values of variables

    _Parser. SetVariable ("NUMBER", "2347687");

    _Parser. SetVariable ("TYPE", "234-234-DD-9");

    _Parser. SetVariable ("DAT_START", "2003/01/01");

    _Parser. SetVariable ("DAT_END", "2003/03/03");

    _Parser. SetVariable ("TEXT", " something clever, with schedules, diagrams, without mistakes ");

    _Parser. SetVariable ("MANAGER", "Takoj T.O.");



    // If we want, that the file was open at once Excel-em, podkrrektiruem zagolovoki

    if (UseTemplateNumber == "3")

    {

      Response. ContentType = "application/vnd.ms-excel";

      Response. AddHeader ("Content-Disposition", " attachment; filename=Template_3.xls ");

}


    // Also we deduce{remove} in reply to search

    Response. Write (_Parser. ParseToString ());


    Trace. Warn (" Have stopped to work with templejtami ");

}

}


Let's see, as far as effectively it works - we shall switch on trasert and we shall note down the time jobs written obrabotchika - 0.0004 sek - good result. Certainly, at use of volumetric files of patterns, filling of their information from a DB, use of more complex  obrabotchikov patterns time of parsing will increase, but as shows an operational experience with real projects, this overhead charge for processing of files of patterns are scornfully small.



Conclusions


Technology of patterns of design completely not excessive in ASP .NET, her  it is possible and it is necessary to apply. And its{her} application not instead of the mechanisms offered{suggested} ASP .NET, and together with them is the most effective, supplementing them and facilitating the decision of routine problems{tasks}.