-
Notifications
You must be signed in to change notification settings - Fork 17
/
Asp.net webform development=Dan Wahlin;Note=Erxin.txt
586 lines (552 loc) · 26 KB
/
Asp.net webform development=Dan Wahlin;Note=Erxin.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
Asp.net webform development=Dan Wahlin;Note=Erxin
# introduct to asp.net
- introduce to .net
- web platform installer
- visual studio
- compiling asp.net applications
+ could view the page from different browser
+ open website from the folder to open the existed website
- web forms
- different web project
+ web project just contain web relative files
+ web application is a solution contain the website and other projects could be resuable
- compile asp.net websites
+ web app, compile -> publish
+ web site, publish all the file in the folder directly
- webform is use the web behind post back to connect the cs logic with the webpage
- server control, start with asp: namespace
# Asp.net web forms features
- asp.net web forms
+ serve up to html automatic
+ oo
+ derive from the page class
+ display, collect and validate data using controls
- asp.net controls
security, data, navigation, web parts (sharepoint relative), ajax control
- asp.net key features
master pages, themes/skins, localization, adaptive UI (generate html base on the browser)
- asp.net services apis
membership, role manager, personalization, site navigation, caching, management
- Web form can contain different items
+ directives, it will config the asp.net page
<%@Page Language="c#" AutoEventWireup="True"%>
//one of the command directive
+ code blocks, suggest not use it!!!
<script language="c#" runat="server">...</script>
+ render blocks
<%=UserDetails%>
+ server controls
<asp:controlElement id="serverSideId" runat="server"/>
+ user control
<user_namespace:controlElement id="serverSideId" runat="server"/>
+ asp.net expression, use to pull out connect string from config file
<%$ ConnectionStrings: NorthwindConString %>
+ data bind expression, directly write the database field to webpage
<%# Eval("DBFieldName")%>
- code separations and page class, when create the aspx page could select separate the cs and html code
- page directive and attributes
+ page directives is added to the top of each asp.net page
<%@ Page Language="C#" %>
use page directive attribute control the page local and redirect behavior
+ features
* page's language
* maintain scrollbar position
* identify code file paths
* turn on or off tracing(logging)
* identify themes or master pages used by the page
* identify an error page
+ page directive attributes
* Async
* CodeFile, specify the associate cs or vb file
* EnableTheming, indicates whether themes can be applied to the page
* Language, target language, such as c# or vb
* Trace, turn tracing function on or off
if the attribute is true, the background trace info is displayed at bottom of the page when render
* MaintainScrollPositionOnPostback, will insert javascript to keep the scrollbar position after postback
* Theme, specify the name of the theme to use for the page
- introduction to web server controls
+ asp.net relies on web server controls to collect display and validate data
+ it's dynamic generate xhtml code on client
+ four basic types of server controls set
* web server control, strongly-typed programmable objects
* html server control, similar to regular html elements but add runat server attribute, the html control could manipulate on the server side. Most common use with hidden field to make it easy access from the code behind without need to check the post back
if the parent control already have the runat server attribute the child will inherite this
* validation controls, used to validate web form submission
* user control, custom controls such as header, footers and menus
+ bind data to asp.net server control's datasource
controlId.DataSource = IEnuableDataCollectionObject;
controlId.DataBind();
+ use the smart tag beside the html controls in the design view
+ server side comment
<%-- contents --%>
- validating user input, support client and server side validation, the client side valide could disable by change the validator's property
+ types
require entry
validating specific criteria, (value, range, etc.)
comparing control values (does text1 == text2)
range checking
pattern matching, (regular expression)
custom validation
+ use the validate control's Text property to overwrite the error message and let it display in the validate summary control
+ server side validate
Page.Valide();
if(Page.IsValide)
{
//...
}
- setting defaults
+ set the default button
<form defaultButton="btnId" runat="server">
+ panel can override the defaultButton
+ default focus
+ manually
container.SetFocus(control/controlId);
control.Focus();
- create user controls
+ reuse cross site
+ user controls can be registered and used in asp.net web form
+ login pages
+ headers or footers
+ repeating menus
+ create user controls, the file is saved as *.ascx extention
<%@Control Language="C#"%>
+ use the user control in page
* drag drop the user control into the page
* register user control by command
<%@ Register src="*.ascx" tagname="header" tagprefix="uc1"%>
* dynamic load user control
use the asp:placeHolder and add the control in the background
in the GUI
<asp:PlaceHolder ID="HeaderPlaceHolder" runat="server"/>
in the background cs file
var ctrl = Page.LoadControl("~/UserControls/*.ascx");
HeaderPlaceHolder.Controls.Add(ctrl);
the '~' means search the file from the root of the website
# Working with data source controls
- data binding in asp.net
+ data binding support is built into asp.net
+ data source controls
relational data
hierarchical data
custom objects and collections
+ data aware controls have a dataSourceID property that is used to bind to a data source control
+ data source configuration wizard
- data binding expression
+ asp.net data binding expressions
<%# Eval(...) %>, use read from datasource
<%# Bind(...) %>, could use both read and write
<%# XPath(...) %>, use to query xml data
+ ex.
<%# Eval("FieldName")%>
+ using data binding expressions
<asp:GridView id="gvCustomers" runat="Server">
<asp:TemplateColumn>
<ItemTemplate>
<%#Eval("ContractName")%>
</ItemTemplate>
</asp:TemplateColumn>
</asp:GridView>
- using the sqlDataSource
+ support four managed providers
+ can stream data (dataReader) or load it into memory (DataSet) by changing its DataSourceMode property
+ Supports filtering and sorting
+ Supports select, insert, update and delete commands
+ Provides built-in caching support
+ DataItem control contain a DataSourceID which used to specify the dataSource control's id
<asp:SqlDataSource
id="sqlCustomers"
runat="server"
//Access the connection string key in the web.config
ConnectionString="<%$ ConnectionString:ConnStr %>"
SelectCommand="GetCustomers"
SelectCommandType="StoreProcedure"/>
<asp:DataList id="dlCust" DataSourceID="sqlCustomers" runat="server">
<ItemTemplate>
<%# Eval("ContractName") %>
</ItemTemplate>
</asp:DataList>
- data source parameters types
parameter
ControlParameter
CookieParameter
FormParameter
ProfileParameter
QueryStringParameter
SessionParameter
+ ex. using the control parameter
<asp:SqlDataSource ID="sdsCustomerByCountry" runat="server"
SelectCommand="GetCustomerByCountry"
SelectCommandType="StoreProcedure">
<SelectParameters>
//Assign parameter data from DropDownList value
<asp:ControlParameter ControlID="dropDownListCountries"
Name="Country" PropertyName="SelectedValue"
Type="String"/>
</SelectParameters>
</asp:SqlDataSource>
- object datasource, support declarative data binding between objects and controls
+ supports binding to custom objects such as business objects
+ allows for N-Tier/N-Layer architecture that separate presentation, business and data layers
+ supports paging and sorting
+ support SIUD operations
+ provide built in cache support
+ ex.
<asp:GridView ID="gvCustomer" runat="server" DataSourceID="odsCustomers">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="ContactName"/>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="odsCustomers" runat="server" SelectMethod="GetCustomers" TypeName="DAL"/>
the type name represent the class should be called in the data access layer
selectMethod represent the method should be called do select statements
+ create the object source follow the wizard, it will automatic pick the property of the query method returned by set the object source property
DataTextField="specifyProprety" DataValveField="specifyProperty"
if just want to bind to the specify object such as string, these two properties are not needed.
don't forget to specify for the primary key for the binded control by set the property DataKeyName
+ linq to sql, ado.net, entity framework
* add a linq to sql class
* open the data explore
* drag the table want to query
* create the linq content ex.
using(var context = new NorthwindDataContext())
{
return (from c in context.Customers
select c.Country).Distinct().ToList();
}
- the entity data source control
+ generates linq queries against a data source
+ used in conjunction with EntityDataSource
+ add parameters and/or filters as needed
+ ex.
* add a ado.net entity data model item
* generate entity from database
* add entity data source control and follow the wizard select the specify entity data model
* specify the selected data field then it VS will automatic generate the code behind
<asp:EntityDataSource ID="SomeID" runat="server" ConnectionString="name=entifyClassName_DataEntities" DefaultContainerName="entifyClassName_DataEntities" EnableFlattning="True" EntitySetName="Customers" Select="[DISTINCT] it.[FieldName]">
<asp:EntityDataSource>
<asp:DropDownList ID="dropDownList1" runat="server" AutoPostBack="True" DataSourceID="SomeID" DataTextField="FieldName"/>
* the select 'it.' is added by the VS the entity datasource also could be added where or control parameters like the previous data source controls
+ using the query extender
* could be used with linq datasource and entity data source
* no explicit where clause required in the data source
* allows different views of data to be shown
* ex.
<asp:EntityDataSource ID="edsCustomers" runat="server">
</asp:LinqDataSource>
<asp:QueryExtender runat="server" TargetControlID="edsCustomers">
<asp:SearchExpression SearchType="Contains" DataField="ContactName">
<asp:ControlParameter ControlID="txtFilter"/>
</asp:SearchExpression>
</asp:QueryExtender>
# Entity Framework
- introduction to the entity framework, 4.0
+ schema first, database already exists
+ model first, convert the model into database table
+ code first, write the class first and convert it into database
- code first, relay on the the DbContext
+ create the base entity class
+ create a class derived from DbContext
* create property for each entity classes
* ex.
//reference
public class CustomDBContext:DbContext
{
public DBSet<EntityClassName0> EntityName0{get;set;}
public DBSet<EntityClassName1> EntityName1{get;set;}
...
}
+ add connection string into webconfig file, the name is default value equal to the DbContext class name in asp.net, the providerName could the several kinds of database, currently selected sql server
<connectionStrings>
<add name="CustomDbContext"
connectionString="server=.\SqlExpress;integrated security=SSPI;database=CreatedDatabaseName"
providerName="System.Data.SqlClient"/>
</connectionStrings>
+ switch to the DataConnection tab at the Solution Explore position or open it in the view menu, check the database connection to the datasource ok and the database is created
+ create repository class for each entity class
+ there is a additional metatable contain the hastable of entity tables to identify if the the table is changed
public class CustomDataModleRepository
{
CustomDbContext _context = new CustomDbContext();
public List<EntityClassName0> GetEntityNames()
{
return (from e in _context.EntityName0 select e).ToList();
}
}
- when classes change
+ add global application class
this class contains handler for app start, session start, app begin request and so on.
add these codes to handle the entity class changes whenever changes
protected void Application_Start(object sender, EventArgs e)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CustomDbContext>());
}
+ custom the DropCreateDatabaseIfModelChanges class behaviour by overwrite it's method in the subclass, the Seed method will
public class CustomDrop:DropCreateDatabaseIfModelChanges<CustomDbContext>
{
public overwrite Seed(DbContext context)
{
var List<EntityClass> ets = new {
new EntityClass{...},
new EntityClass{...}
};
ets.Foreach(e=>context.Add(e));
base.Seed(context);
}
}
- LINQ Queries and filter data
# Master pages
- working with master pages
+ define common page layout
+ master page is a special type user control
+ master page could be nested
+ has a *.master extension
+ can have a code behind file
+ ex.
<%@ Master%>
<html>
<body>
<asp:ContentPlaceHolder id="ph1" runat="Server"/>
</body>
</html>
- creating master pages
- creating content pages
+ content pages reference a master page and contain one or more content controls
<%@Page MasterPageFile="*.master"%>
<asp:content id="bodyContent" ContentPlaceHolderId="holderDefineInMasterPage" runat="server">
...
</asp:content>
+ create content page in the master page by right click and select add content page
+ add new item webform use master page
- changing master page
+ master pages can dynamically be changed using the page_preInit event handler
void Page_PreInit(object src, EventArgs e)
{
if(Request.QueryString["Print"] != null)
{
this.MasterPageFile = "~/CustomMasterPage.master";
}
}
# Asp.net ajax controls
- introduction to ajax technologies
+ terminology and acronyms
* postback operation, action triggered by an end user or by code in a web page that send data back to web server for processing
* partial-page updates, data in section of a page is updated rather than the entire page
* ajax, asynchronous javascript and xml
* xml
* json, javascript object notation
* dom
* rest, representational state transfer, identify resource from the URL from the server and spend the response back
+ what is ajax, asynchronous javascript and xml
* relies upon xmlHttpRequest object, javascript, css and json
* a technology for making asynchronous(parallel) call from a web page
* messages sent back and forth between web pages and server using XMLHttpRequest
* Result in minimal(or zero) page refreshes
* can integrate with web services or REST APIs
* works with all mainstream browsers
+ asp.net technology solution for ajax
* scriptManager
* updatePanel
* updateProgress
* scriptManageProxy
* timer
+ ScriptManager control is a key control in the asp.net ajax framework
* required in all asp.net ajax-enabled pages
* manages all framework and custom scripts used by a page
* used to reference custom scripts
* generates client-side web server proxy objects
* controls debug and release models for script debugging
* coordinates asynchronous operations
* using the scriptmanager control
all ajax-enable asp.net web pages require a scriptmangaer control
add a scriptmanager by
drage it to from the toolbox
manually coding it while in source view
<asp:ScriptManager id="sm" runat="server"/>
* checking for partial-page updates
the scriptManager's IsInAsyncPostBack property can be used to check when partial-page requests are made
* use IsInAsyncPostBack in combination with page.IsPostBack
the post back may be a normal post back cause by a form in the current page, use IsInAsyncPostBack to identify partial page request post back
* disabling partial-page updates
partial-page updates can be disabled using the scriptmanager's EnablePartialRendering property to help debugging
- asp.net ajax controls
+ add scriptmanager from the design view, it's a hidden control
+ support load custom script
<asp:ScriptManager ID="sm" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/Custom.js"/>
</Scripts>
</asp:ScriptManager>
+ script manager contain a pageLoad method to run any js code after DOM is ready
function pageLoad()
{
...
}
+ is post back is different with the standard page post back, page post back is the whole page post back, the script manager post back is async post back
Page.IsPostBack, objScriptManager.IsInAsyncPostBack
- using the scriptManager control
- using the updatePanel control
+ updatePanel requires scriptManager
- using the updateProgress control, wrap the controls need to use ajax call into the panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Lable ID="TimeLabel" runat="server"/>
<br/>
<asp:Button ID="SubmitButton" runat="server" Text="Get Time" onclick="submitButton_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
+ mix the fiddler with the web debug process
+ use disable the script manager's property EnableParialRendering to false to disable the ajax function. this will help to show the whole exception detail
+ if the request control is outside the update panel, it will not use the ajax function make the call by default. It need to use the property trigger collection of update panel to let it keep use the ajax function
* AsyncPostBackTrigger
* PostBackTrigger
- using the updateProgress control
+ provide end users with feedback about their requests
+ uses a progressTemplate to define progress indicator content during the ajax call
+ ex.
<asp:UpdateProgress ID="upProgress" runat="server" DynamicLayout="false" AssociatedUpdatePanelID="UpdatePanelCust">
<ProgressTemplate>
<img src="Image/progress.gif"/>
</ProgressTemplate>
</asp:UpdateProgress>
+ website for ajax load info image to help design the load view
http://ajaxload.info
# Security
- Introduction
+ authentication, who are you?
+ authorization, what actions are you allowed to perform?
+ impersonation, switch user accounts to perform specific actions, the login user does't have the right to connect the db but asp app run in a other higher level user to connect the db
+ Several built-in security modes
* forms authentication
login in throw a web page
automatically redirect anonymous users to a login page
authenticated users identified by an authentication token stored in a cookie in the URL
relies on the formsAuthentication class
configured in web.config
* windows authentication( basic, digest, ntlm, kerbers ), most use in Intranet
can be used in combination with basic, NTLM, digest, kerberos and more
user authenticated by iis
easiest of all to use
request flow: client request->iis authenitcates forward to asp.net->asp.net access request resource
- Using the asp.net configuration website
+ VS Project|Asp.net Configuration, will configure the asp.net
+ default asp.net web app will use the form authentication by default
+ the empty asp.net app will use the window authentication by default
+ every folder could define its own webconfig by manual or use the asp.net web configure tool from VS
- Using aspnet_reqsql, use to install
+ asp.net use a sql server express database to store membership
+ to create support for user membership storage
+ run the tool from the vs command prompt
+ shift the aspnet database to other sql instance
+ add item| add connection string to choose the sql instance
- Security Server Controls
+ login, simplifies authenticating users and can direct new users to a registration page
<asp:Login ID="login" runat="server" CreateUserUrl="RegisterUser.aspx" CreateUserText="Create a User Account"/>
+ loginView, shows different messages based upon the authentication status of the user
<asp:LoginView ID="LoginView1" runat="server">
<AnonymouseTemplate>
Please login below
</AnonymouseTemplate>
<LoggedInTemplate>
Welcome
<asp:LoginName ID="LoginName" runat="server"/>
</LoggedInTemplate>
</asp:LoginView>
+ passwordRecovery
+ loginStatus
+ loginName
+ CreateUserWizard, generates a user registration interface, supports custom wizard templates and steps
+ ChangePassword
# dynamic data
- what is asp.net dynamic data?
+ create data-driven applications without writing a lot of code
+ fully customizable
+ quickly build data-driven applications based on LINQ to sql or entity framework
+ key features of dynamic data
* automatic validate base on data model
* easily change the markup generated for fields in gridview and detailView controls
* support for many-to-many relationships
* field template and attributes
* data filtering
+ scaffolding in dynamic data
* automatic generation of dynamic data elements for each table in a database
* CRUD(create, read, update and delete) operations for each table are auto-generated for web pages
* scaffolding consists of page templates entity page templates, field page templates
- create a dynamic data project
+ could create a website with dynamic data template
+ global.asax
+ help generate CRUD operations
- create a data model, there are two options, linq to sql or entity framework
+ add an ado.net entity data model item
+ select the database to query for the wizard
+ select the tables views and stored procedures
+ add a item of asp.net code folder for the data model or create a wcf service for access the data model
- registering the data model
+ after create the data model need to register the data model for tye dynamic data project by Global.asax file
+ rename your data context type to the name you specified when creating the model
+ set scaffoldAllTables to true to allow each table to be added
DefaultModel.RegisterContext(typeof(CustomDataContextName_DataEntities), new ContextConfiguration(){ScaffoldAllTable=true});
+ we could also use attribute to control which table of the data model be scaffold if we don't want all the table are scaffold.
+ add a custom class for the table class which need to scaffold instead of directly add the attribute in the design class which will be automaticelly wrap out
namespace CustomDataEntityNamespace
{
[ScaffoldTable(true)]
public partial class CustomClassTable
{
}
}
- modifying dynamic data sites
+ customize the master page
+ customize the css
+ customize how page are rendered
+ customize page routes
+ customize fields
+ modify field template provides the ultimate in control over how data is rendered and captured
+ mix with jquery
* jquery.com
* jqueryui.com
+ reference the client side id for the asp.net server side control
$('#<%=ServerID.ClientID%>')
# Asp.net web deployment
- web deployment
hosting asp.net application with iis
+ test deploy website on local window first
+ turn on asp.net
+ use the powershell
+ switch to the .net installation folder such as
%windir%\microsoft.net\framework\v.4.0.xxx
+ search for asp.net relative console tool by 'ls asp*.exe'
+ regist asp.net for iis
aspnet_regiis.exe -i
- manually web deploy
msbuild-based deployment tool for asp.net applications
+ deploy by hand, just copy the web application folder under the web app project contain all the source code, without solution file
+ app pool, identity and security rights for the application
+ switch the app should running under identity, by finding app pool it's running in, mapping to the identity and security right for the given app
* Load User Profile, attribute in the advance setting
set it to True allowed local test
+ sql server configuration
+ security issues
- web deploy meet tool
+ package all web components
+ script IIS setting (including appPool)
+ SQL DB
+ IIS7 import
+ steps
* solution property|package/public web
* exclude files from the app_data folder
* need to open the visual studio in administration mode
* shift + click
- public sql, int the solution property
+ import from connection string in web.config
+ script schema and data
+ generate differential scripts with sql project
- configuration files, transformations and deployment
+ can create alternate web config for debug, release, test, etc
+ can define xlst-like differential xml for each deployment scenario
* specify only differences from main config file
* XDT syntax
* works with any xml content
+ register a ISP server follow the instruction after register
+ configuration file transmission
# glimpse diff with firebug and chrome developer tool
- help debug the asp.net code run on the server