5 myths Web of programming
In each area there are myths, each field of activity covered with some secret in which consequence{investigation} there are myths. I have tried to describe 5 myths most widespread in my opinion about Web programming.
Myth ¹1. C ++/Pascal ruljat the world.
Many think that, only such giants of programming as Straustrup can create ideal language. No, actually really on C it is possible to write everything, that only it is possible to realize as a logic chain of actions, but (!): I shall pay your attention to a word "to write". I.e. to write that it is possible, but how much it will demand efforts what price of a choice for the benefit of "ideal" language will be. We shall take, for example PHP. Everyone know (well now precisely all), that interpreter PHP to write on C. What this implies? And that for that what to write scripts for web on C as is easy and fast, will be necessary to write analogue PHP. All business in a problem{task} and "cost prices" of its{her} performance.
¹2. Web the programmer never will write a myth " anything serious ".
Under "serious" the scale project which takes away a heap of time of nerves usually is understood, but brings taki "worthy" compensation. OK, analogy from a life. The cabbage in the market costs{stands} N, in shop the same cabbage costs{stands} 1,25N, in a supermarket premium a class the same cabbage costs{stands} 5N, and on a market on rublevke the same cabbage costs{stands} 1000N. Also what, who here cuts cabbage (writes something serious)? And so, imkho, a question not in how to bring up cabbage (to write the program) and as her{it} to sell, and it already a question from area of marketing and programming (though on PHP though on C/Pascal) here at all and.
Myth ¹3. It is better to start to study from "complex{difficult}" languages.
Partly, yes. Only, as always the veil of secret, has brought in corrective amendments treatment of this phrase. Really what to understand essence elements of programming (types of the data, links,) it is better to start to study bases OOP that language where these elements are realized in the best way, but (!): Usually the phrase " is Better to start to study from "complex{difficult}" languages " is used in that context that the person taught{learnt} PHP is allowable cannot proceed{pass} allowabl on C. I shall be repeated PHP it is written on C and has inherited much from proraditelja. Means PHP it is similar on C, it is equal as much how much C it is similar on PHP. Why someone cannot proceed{pass} from simple to complex{difficult}, and from complex{difficult} to simple the same person can. I.e. not studying PHP you are capable to study C, and having mastered PHP you at once, on beconing a magic wand, lose property " I can study C ". Delirium!
Myth ¹4. Write from zero.
This myth often arises in itself in heads nachinakh coders. " Ah, how much the code, how long with it{him} to understand ": " better I shall write the analogue at which there will be only " that is necessary for me " ". Why it is a myth? First, if difficultly to understand, an another's code it does not mean yet that he bad. Second, we make the list " that that is necessary ", we compare with that, that is and we hammer on " write from zero ". It is better to write superstructures for managements of an exchange of links between 10 (100,1000 necessary to emphasize) forums, modules to everyones CMS at last. Other business if kodit` something unique by the nature, but in 99,99 % cases a phrase " write from zero " is used because of unwillingness to understand an another's code and to study as a whole. A psychological question, imkho. Certainly, it is possible kodit` from zero for " fastening of the gone material ", but besides it is stacked in those of 0,001 %.
Myth ¹5. All is already written.
Only it is not necessary to lower{omit} hands! Actually it is written so a little, that already [censored]! Other business if during training (practice) kodinga, there is a situation when is not problems{tasks} to which it is necessary " to apply{put} hands ". And here game enter "sruli". At them all is written, all is made, all places are borrowed{occupied}: it is time to go and it will be shot. That here it is possible to say. People, it not programming will think up problems{tasks} for a life, and the life gives I write (a slice khlebushka and a cup and ikorochkoj) to the programmer. Not there search for ideas. Really, nakodit` the that - string very hardly, and for example nakodit` parser, a news site is more complex, even more complex{more difficult, even more complex;more complex, ev} to improve it{him} and to make adjusted uvedomlenenija on e-mail, icq and sms. it is even more complex{difficult} to write system of tracking of copies of the text from a site (whether a little someone "only casually" has forgotten to put the link to you). Yes much that is possible to make.
Instead of the conclusion I shall say, that many myths it actually simple substitution of concepts, or any psychological barriers. Nobody can solve for you, that the truth is better, that and what to do{make}.
Statistics of a site - answers to questions and not only...
The statistics of a website was born from questions.
All begins with it.
It is interesting how to increase sale?
Absolutely shortly about the main thing.
The person sits at a computer and with the help of a browser looks through a website. The site will consist of files.
Interestingly, what files look through more often? And who looks through them?
Hardly is more detailed about a subject.
The website will consist of set of files - hypertext documents, pictures of registration, the data. The hypertext contains actually text information, links to other documents, links to elements of registration, a rule of a marking of the document for correct display of the information to the screen of a computer. Websites usually contain links against each other, thus it is possible to pass from a site to a site.
At viewing a website we see the webs - pages including the text and a picture is a result of processing by a browser of commands of a hypertext, for example, to write a fat font this text, or to load this picture.
Except for people sites sometimes "look through" special useful programs, such as search machines, webs - archives, validatory. Still your site can interest bad, harmful programs.
Interestingly, and from what sites pass to my site? And why? And when? And who goes to my site - people or robots? Whether index search machines my site? And what pages? And why not all pages index? And what is this the animal has visited my site?
The resume.
On these interesting questions, and also on weight of others not less interesting the statistics of a website can answer.
Development of searches
The connected subrequests and associations.
Subrequest name search SELECT which is included in other search as parameter or expressions. They are usually used to generate value or a set of results which are used in conditions of the main search.
The correlated subrequest is unique difference between recordings for the main search as only he depends on values which vary from recording to recording. Interbase carries out such subrequest many times, on time for each recording a parental subrequest. Calculation of each recording is the big loss in productivity in relation to a untied subrequest. Interbase optimizes untied subrequests outside of a cycle, executes them only once, using then results as a separate data set.
Example of the connected subrequest:
SELECT *
FROM DEPARTMENT D
WHERE EXISTS
(SELECT *
FROM EMPLOYEE E
WHERE E.EMP_NO = D.MNGR_NO
AND E.JOB_COUNTRY = 'England')
And an example of identical search with use of association:
SELECT D.*
FROM DEPARTMENT D JOIN EMPLOYEE E ON D.MNGR_NO = E.EMP_NO
WHERE E.JOB_COUNTRY = 'England'
The plan of performance of search. The plan describes the script on which optimizator has decided to execute search. For some types of searches optimizator be not capable to choose really optimum plan. The person can analyse various plans and, having chosen necessary to block him{it} the plan chosen optimizatorom. Result can be tremendous increase in speed at some types of searches. In the most started cases it is possible to reduce execution time 15-ti minute search about three seconds.
The opportunity to specify the plan of search has been added in GPRE and DSQL/ISQL. Thus, the direct instruction{indication} of the plan of search will work in a body of viewing (View), stored{kept} procedure or the trigger.
More in detail this method is considered here.
Preparation of searches and parameters of search
Interbase supports searches with parameter in DSQL for those cases when the specified search will be carried out some times with various values. For example, filling of the table with the data can demand a series of INSERT commands with values for each recording. Application parametrizovannykh searches directly increases productivity as Interbase stores{keeps} internal performance of search and his{its} optimized plan after unitary preparation of search.
Use parametrizovannykh searches in Delphi occurs the following steps:
Place the named parameter in search about a place of a constant. Interbase does not support parameters anywhere, except for as in constants, tables and names of fields cannot be described by parameter.
Prepare search, using for this purpose method Prepare of component TQuery. Delphi prepares search if he is not prepared yet each time before performance. After performance of search his{its} preparation is automatically removed. Thus, preparation of search beforehand prevents senseless preparation and a cancellation of preparation at kazhdim a call of search.
Appropriate{Give} parameters. For example, for component TQuery use for this purpose method ParamByName.
Execute search. Expressions SELECT should open method Open, and INSERT, UPDATE and DELETE should be activated metom ExecSQL.
If necessary to repeat items{points} 3 and 4.
To cancel preparation of search. It is done{made} by method Unprepear of component TQuery.
In some real cases including repeating actions, use parametrizovannykh searches increases productivity by 100 %
Job with the data in Web
And what here such, you ask? That's just the point, that job with the data in web-applications demands other approach, than described in all clauses{articles} and tutorials a method of job with use of typified data sets. It speaks first of all requirements to productivity of system that plays far from being last role as projected software product. And if at a spelling of desktop applications some aspects of productivity could be neglected, in web-applications such neglect is fraught with serious problems.
In clause{article} we shall in detail consider an example of the application, stopping on the key moments, explaining advantages of the chosen method before others existing.
So:
As system of databases we shall choose the well-known server of databases MS SQL. About his{its} advantages and about his{its} contribution to the general{common} productivity of the developed application here speech will not go, considering de facto his{its} merits and demerits before other systems.
As a test database it is possible to use standard base Northwind, but for <cleanliness of experiment> we shall create the database. We shall name her{it} DemoBase.
And now attention - the first condition for construction of the normal application. For manipulation with the data in our base we shall use stored{kept} procedures. Not pressing in details, we shall say so, that their their main advantage consists that they are stored{kept} on the server in already otkompilirovannom a kind while the simple transferred{handed} set of Transact-SQL commands passes through such stage <compilations>. Besides they as though <inkapsulirujut> in itself structure of a database that provides the big flexibility of designing of this base.
Our procedures will carry out four elementary actions with the data in table Users (Select, Update, Delete and Insert). And Update and Insert we shall unit one procedure.
Procedure of sample of the data:
CREATE PROCEDURE dbo. SelectUsers
(
@UID int = 0
)
IF @UID = 0
SELECT * FROM Users
ELSE
SELECT * FROM Users WHERE UID = @UID
Procedure of addition of new recording and editing existing:
CREATE PROCEDURE dbo. [SetUser]
(
@UID int = 0,
@Name varchar (50),
@Comments varchar (100)
)
IF @UID = 0
INSERT INTO Users (Name, Comments) VALUES (@Name, @Comments)
ELSE
UPDATE Users SET Name = @Name, Comments = @Comments WHERE UID = @UID
Procedure of removal{distance} of recording:
q
CREATE PROCEDURE dbo. DeleteUser
(
@UID int
)
DELETE FROM Users WHERE UID = @UID
And procedure, calculation of quantity{amount} of recordings in the table. On its{her} example we shall see, how from procedure to receive scalar sizes as result of their job:
CREATE PROCEDURE dbo. UsersCount
(
- OUTPUT speaks us that this parameter returned.
@Count int OUTPUT
)
AS
SELECT @Count = Count (*) FROM Users
The base is ready. Now we shall be accepted to development of our web-application. For this purpose we shall use package Visual Studio .NET. But all steps will be accompanied by detailed comments that described people which are not using for whatever reasons above mentioned IDE could reproduce all in practice.
After some manipulations with a mousy and the keyboard, we have created C */ASP.NET project DemoApplication.
First of all we shall take care of connection to our database. We shall store{keep} a line of connection in configuration file Web.config. For this purpose we shall add special section:
<configuration>
<system.web>
........
</system.web>
<appSettings>
<add key = "ConnectionString"
value = " server=localhost; datasource=DemoBase; login=sa "> </add>
</appSettings>
</configuration>
Besides the copy of class SqlConnection will be necessary for access to the server of a DB (why not OleDbConnection, see a cycle of clauses{articles} <Job with the data yesterday, today, tomorrow>) for us. For maintenance of unification of process of creation of connection, we shall add to our project a class, with static attribute of the type necessary to us:
using System. Data. SqlClient;
namespace DemoApplication
{
public class DataBase
{
public static SqlConnection Connection
{
get
{
return new SqlConnection (
System. Configuration. ConfigurationSettings.
AppSettings ["ConnectionString"]);
}
}
}
}
Now we can start development of a visual part of our application, at last.
For the beginning we shall pass to a code of the form, and we shall make some changes a standard pattern:
For the beginning we shall place on the form copy SqlCommand, and we shall name it{him} SelectCommand. Then we shall pass to a code of the form, and we shall make to a standard code some changes:
using System;
using System. Data;
using System. Data. SqlClient;
using System. Web. UI.WebControls;
namespace DemoApplication
{
public class WebForm1: System. Web. UI.Page
{
private SqlConnection _connection;
private SqlConnection Connection
{
get
{
if (_connection == null)
{
// Here we also shall use
// Our static class
_connection = DataBase. Connection;
}
return _connection;
}
}
private void Page_Load (object sender, System. EventArgs e)
{
if (! IsPostBack)
{
CreatePage ();
}
}
private void CreatePage ()
{
}
*region Web Form Designer generated code
override protected void OnInit (EventArgs e)
{
InitializeComponent ();
CustomInit ();
base. OnInit (e);
}
private void InitializeComponent ()
{
this. Load + = new System. EventHandler (this. Page_Load);
}
*endregion
private void CustomInit ()
{
}
}
}
All initialization of our components will be carried out by method CustomInit (). Basically, owners VS.NET can rely entirely in initialization of many properties on IDE, but we shall go in other way to not deprive at whom such tool no.
Nevertheless, that is connected with display of the data will occur in CreatePage ().
First of all, we need to choose the data from base and to display them on the form. For this purpose we shall create copy SqlCommand, and we shall name it{him} SelectCommand. We shall initialize all his{its} basic properties in CustomInit ():
private void CustomInit ()
{
/ **
* The type of the command specifies, that we shall use stored{kept} procedure.
* This parameter influences how Asp.net will generate search for ms sql the server
**/
SelectCommand. CommandType = CommandType. StoredProcedure;
/ **
* Actually, the name of procedure
**/
SelectCommand. CommandText = "[SelectUsers]";
/ **
* For initialization of connection we shall use
* Private property of a class of page (is (see higher)
**/
SelectCommand. Connection = this. Connection;
/ **
* We shall create parameter through which we shall be perdavat` arguments to procedure
**/
SelectCommand. Parameters. Add (new SqlParameter ("@UID", SqlDbType. Int));
}
Now we shall place on the form copy DataGrid:
<asp:DataGrid id = "UsersDataGrid" runat = "server"
AutoGenerateColumns = "False" DataKeyField = "UID">
<Columns>
<asp:TemplateColumn HeaderText = "Name">
<ItemTemplate>
<asp:Label id=Label2 runat = "server"
Text = ' <% * DataBinder. Eval (Container, " DataItem. Name ") %> '> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox id=NameTextBox runat = "server"
Text = ' <% * DataBinder. Eval (Container, " DataItem. Name ") %> '> </asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText = "Comments">
<ItemTemplate>
<asp:Label id=Label1 runat = "server"
Text = ' <% * DataBinder. Eval (Container, " DataItem. Comments ") %> '> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox id = CommentsTextBox runat = "server"
Text = ' <% * DataBinder. Eval (Container, " DataItem. Comments ") %> '>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton id = "LinkButton1" runat = "server"
CommandName = "edit"> to correct </asp:LinkButton>::
<asp:LinkButton id = "LinkButton2" runat = "server"
CommandName = "delete"> to remove </asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton id = "LinkButton3" runat = "server"
CommandName = "update"> to accept </asp:LinkButton>::
<asp:LinkButton id = "LinkButton4" runat = "server"
CommandName = "cancel"> to cancel </asp:LinkButton>
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Now we shall pass to method CreatePage (). In him we also shall make that magic gesture after which on our form the data from base will flaunt:
private void CreatePage ()
{
// Before executing the command, it is necessary to open soednenie
SelectCommand. Connection. Open ();
/ **
* As a source of the data for ours grida we shall specify a data set,
* Returned to us the command as SqlDataReader.
* It is the fastest way to obtain the data from base.
**/
SqlDataReader reader = SelectCommand. ExecuteReader ();
UsersDataGrid. DataSource = reader;
// We execute svjazyvaenie
UsersDataGrid. DataBind ();
/ **
* After everything, we need to close ours SQlDataReader, because
* He possesses property exclusively to borrow{occupy} connection with base.
* It is especially actual, when one copy of connection is used
* For several operations.
**/
reader. Close ();
// Well, also we close connection
SelectCommand. Connection. Close ();
}
For addition of new recordings, we shall place on the form two TextBox-?, having named them NameTextBox and CommentsTextBox accordingly, and the button, on pressing on which we shall add the data. For this purpose we shall use drugoim copy SqlCommand which will be adjusted to corresponding procedure. Same command we shall edit the data:
SetCommand. CommandText = "[SetUser]";
SetCommand. Connection = DataBase. Connection;
SetCommand. CommandType = CommandType. StoredProcedure;
SetCommand. Parameters. Add (new SqlParameter ("@UID",
System. Data. SqlDbType. Int));
SetCommand. Parameters. Add (new SqlParameter ("@Name",
System. Data. SqlDbType. NVarChar));
SetCommand. Parameters. Add (new SqlParameter ("@Comments",
System. Data. SqlDbType. NVarChar));
Now we will address to obrabotchiku pressing the button:
private void Button1_Click (object sender, System. EventArgs e)
{
/ **
* We shall specify to the command, with what values of parameters to carry out procedure
**/
SetCommand. Parameters ["@Name"] .Value = NameTextBox. Text;
SetCommand. Parameters ["@Comments"] .Value = CommentsTextBox. Text;
/ **
* We execute the command without returning resulting sample
**/
SetCommand. Connection. Open ();
SetCommand. ExecuteNonQuery ();
SetCommand. Connection. Close ();
/ **
* And now we "shall draw" page with the new data
**/
CreatePage ();
}
By the same principle there is a removal{distance} and editing of the data. Not pressing in details of realization to not repeat, I shall result only a code obrabotchikov UpdateCommand and DeleteCommand:
private void UsersDataGrid_UpdateCommand (object source,
System. Web. UI.WebControls. DataGridCommandEventArgs e)
{
SetCommand. Parameters ["@UID"] .Value =
UsersDataGrid. DataKeys [e. Item. ItemIndex];
SetCommand. Parameters ["@Name"] .Value =
((TextBox) e. Item. FindControl ("NameTextBox")) .Text;
SetCommand. Parameters ["@Comments"] .Value =
((TextBox) e. Item. FindControl ("CommentsTextBox")) .Text;
SetCommand. Connection. Open ();
SetCommand. ExecuteNonQuery ();
SetCommand. Connection. Close ();
UsersDataGrid. EditItemIndex =-1;
CreatePage ();
}
private void UsersDataGrid_DeleteCommand (object source,
System. Web. UI.WebControls. DataGridCommandEventArgs e)
{
DeleteCommand. Parameters ["@UID"] .Value =
UsersDataGrid. DataKeys [e. Item. ItemIndex];
DeleteCommand. Connection. Open ();
DeleteCommand. ExecuteNonQuery ();
DeleteCommand. Connection. Close ();
CreatePage ();
}
And now we shall use our procedure of calculation of quantity{amount} of recordings in the table and we shall see, as from procedure to receive any scalar sizes. For this purpose we shall add on the form one more copy SqlCommand, having named it{him} CountCommand and we shall initialize his{its} parameters as follows:
CountCommand. Parameters. Add (new System. Data. SqlClient. SqlParameter ("@Count",
System. Data. SqlDbType. Int))
CountCommand. Parameters ["@Count"] .Direction = arameterDirection. Output;
We have initialized property Direction, having specified, that parameter this returned. And now we shall make some changes to method CreatePage (), having added a mentioned below code before closing connection to display result of job of this command:
/ **
* To not create one more copy of connection, we shall use
* Already available
**/
CountCommand. Connection = SelectCommand. Connection;
CountCommand. ExecuteNonQuery ();
CountLiteral. Text = CountCommand. Parameters ["@Count"] .Value;
Thus we have developed the elementary application "correctly working with the data. After all vyshenapisannogo, let's sum up our job:
1. For data processing on the server of a DB it is necessary to use stored{kept} procedures.
2. For data processing at a level of the application it is necessary to use to straight lines vypolenniem commands which, in our case, return either a simple data set, or the scalar data, or return nothing.
3. Well and a classical rule <borrow{occupy} resources as it is possible later and release{exempt} as soon as possible> with reference to connection with a DB.
Some structural neoptimal`nost` applications is extremely consequence of desire to make it{him} more nagljadnym.\

|