Thursday, August 25, 2016

Server Control and Custom Control

  • Building block of the GUI
  • E.g. Textbox, Button , drop down list ...
  • E.g. Validation, Security , Master Page and data manipulation.
5 Type of Control :
  • HTML controls
    • <a>,<button>,<input type>
  • HTML server controls
    • HTML control with runat=server
    • Able run in ASP.NET
  • ASP.NET server controls
    • Validation control
    • Data source control - data binding
    • Data view control - list and table from data source
    • Personalization control - personalization of page based on user information
    • Login and security control
    • Master Page
    • Navigation control
    • Rich control - file upload and calendar control
  • ASP.NET AJAX server controls
  • User controls

Custom Control
  • Compile into DLL and used as any other ASP.NET server control.

Different Custom Control and User Control
  • Custom control are compiled into assembly (.dll), user control are not.
  • Custom control can add into toolbox, user control cannot.
  • Custom control are difficult to create, it has no designer, and everything done by code; user control are easier to create as similar to creating web pages.
  • Single copy of custom control can be used in multiple application (just browse to the location); A separate user control is required in each application

Wednesday, August 24, 2016

Security

Authentication - who can request the page ?
Authorization - what page can request ?
  • Form authentication
    • setup in used for internet web application, relies on configuration in web.config.
    • First time user access to protected resource, ASP.NET will redirect user to login page.
    • If login is successful, ASP.NET will give authentication ticket (cookies) to user.
    • The expiration time of ticket can be configure.
    • different web config in folder can be configure different set of access.
    • authorization deny user=? , put in main page, so anonymous users cannot access.
    • authorization allow user=* , put in register so everyone can in.
    • authorization allow role="admin", deny user=* , except admin all cannot access.
  • Windows Authentication
    • identifies and authorizes users based on the server's user list
    • Suitable for intranet web application.
    • Don't force users who already logged in to Windows and log in again.
    • Good For in house use and behind firewall.
      • Cannot work through firewalls.
      • Not for internet use. 
  • Passport Authentication
    • Rely on a centralized authentication service provided by Microsoft
    • Install and Configure .NET Passport SDK.  
    • email address and password
    • Google account can login youtube, blogger , gmail
  • When enable impersinate (true)
    • To use existing Windows user permission, user identity as the account you logged in.
    • False = IIS APPPOOL\DefaultAppPool
    • True = Dk\oby
    • user must authenticated by IID
    • To give each web application different permissions
      • No matter what user access the application, it will become the preset specific account
Authorization

<location path="HRpages">
  <system.web> 
    <authorization>
      <allow roles="HR" />
      <deny users="*" />
    </authorization>
   </system.web>
</location>

<location path="salesPages">
  <system.web> 
    <authorization>
      <allow roles="sales" />
      <deny users="*" />
    </authorization>
   </system.web>
</location>
<deny users="?" /> <!-- Allow all users -->

IIS

  • IIS is a web server to deliver web pages to clients using HTTP
  • run type"inetmgr" to check IIS is installed.
  • Worker process 
    • ASP.NET run under a process, it responsible for all request and response processing.
    • w3wp.exe
  • Application pool 
    • Allow run a group of web sites, web application or web services.
    • 1 App Pool Container of 1 worker process.
    • Web applications run separate processes to isolation between them.
  •  WAS 
    • Manage Application pools and worker processes for HTTP and non-HTTP request. 
    • Determine worker process is running or not. if not, it will start a worker process. 
    • spawns worker processes, monitors their health, recycles them if necessary and makes sure none of them consume more resources than specified AppPool configuration. 
    • WAS is also the arbiter and collector for run-time and state data, e.g. performance counters, site and Application Pool state.
  • HTTP.sys (Hypertext Transfer Protocol Stack)
    • Implement at Kernel Mode.Without switch to user mode.
    • Listen HTTP request from network, pass request to ISS process and return response to client browser.
    • http.sys know which app pool handle the request, because new app pool ID will registered with http.sys
    • Kernel mode request queuing. request cause less overhead in context switching. If no worker process available to accept request, the kernel mode request queue will hold the request until a worker process pick it up.
    • Request pre-processing and security filtering.
  • IIS 5.0 all app domains are hosted by a ASP.NET worker process.
  • IIS 5.0 run on windows 2000 or XP
  • IIS 5.0 single process host all application, if killing this process, all other application will restart.
  • IIS 5.0 do not have App Pool.
  • IIS 5.0 single aspnet_wp.exe. (All request are dispatched by ISAPI extension hosted in inetinfo.exe, and pass to aspnet_wp.exe)
  • IIS 6.0 no use aspnet_wp.exe, it use worker process (w3wp.exe) which is not single, it can be many instance.
  • IIS 6.0 no use inetinfo.exe to forward HTTP request to ISAPI extensions.
  • IIS 6.0 handle Incoming request at lower kernal level (http.sys) insteal of user mode and route to the app pool. IIS 5.0 request is received by user mode (inetinfo.exe)
  • IIS 6.0 run on windows server 2003
  • IIS 6.0 allow application run inside different copy of a new worker process, w3wp.exe. Each app pool can contain mutiple App Domain and is hosted in single copy of worker process.
  • IIS 6.0 keep a single copy of metabase in global process (intelinfo.exe).
  • IIS 7.0 no use metabase and use XML Configuration files that located alongside Web content. Each worker process loads a unique copy of configuration.
  • XML config file can read by human
  • IIS 7.0 run on Windows 2008
  • IIS 7.0  URL Rewrite
  • IIS 7.0 Better UI
  • IIS 7.0 has 40++ module (basic, anonymous, windows authentication, logging, FTP)
  • IIS 7.0 has Classical and Inegrated mode. Classical is back to IIS 6.0

Classical Mode / Integration Mode

  • Classic mode
    • the only mode in IIS6 and below
    • IIS (request/response) pipeline is separate with ASP.NET pipeline.
    • Is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. IIS treat ASP.NET as an external plugin implemented in ISAPI and only give out the request to ASP.NET. when it's needs.
  • Integrated mode
    • Integrate IIS request pipeline and ASP.NET request pipeline. ASP.NET is no longer treated as an external plugin.
    • HttpModules have power as an ISAPI filter  and  HttpHandlers have power as an ISAPI extension. ASP.NET is a part of IIS.
    • Unified process model, eliminates steps that previously duplicated in IIS and ASP.NET. E.g. Authentication and authorization.
    • Enable manage to all content types (images, text files, HTML), that’s why HttpHandler and HttpModule can handle it.


IIS 6.0 Process Model

Request  > Http.sys (kernel mode) > (user mode)WAS > App Pool  > w3wp.exe = asp.net_isapi.ddl create HTTPRuntime object process the request via HTTPModule and HTTPHandler > Page Life Cycle

Web Service

  • Communication platform between different or same platform applications that allow to use the web method.
  • Standardized XML messaging system. (Send and Response using XML)
  • Not tied to any OS and programming language. (Java can talk to C#, Windows can talk to Linux)
  • Visual studio using information of WSDL to create Proxy class to help (steps) :
    1. Serialize the parameters 
    2. Prepare SOAP request message 
    3. Send to Web Service.
    4. Web Service execute the method and return SOAP response message to proxy.
    5. Proxy deserialize soap message and hands in the application.
Component of Web Services
  • SOAP (Simple Object Access Protocol)
    • is a communication protocol between applications
    • is independent language and platform.
    • is an XML based messaging protocol for exchange information
  • UDDI (Universal Description, Discovery and Integration)
    • Is a specification for a distributed registry of web services.
    • create a standard platform enable company or application easy to find the web service.
    • Use WSDL to descrive the interfaces to web services.
  • WSDL (Web Services Description Language).
    • Standard format for describing web service
    • Describe all methods, parameters and return type.
    • A client program connecting to a web service can read WSDL to determine what functions available.
    • E.g. Operations, Type (Data Type), Binding, 
How Web Service Work
  • XML to tag the data
  • SOAP to transfer a message.
  • WSDL to describe the availability of service.
Windows Communication Foundation (WCF)
  • .NET 3.0
  • Use for distributed application ( Web Server + Web Service Server)
  • 1 Web service and configure many endpoint as support all client needs. (HTTP/TCP) (XML,Binary)
  • Serialization : Process of convert an object into XML
    • [Serializable] put in class , all property will be serialize. You cannot control only 1 property need to serialize.
    • [DataContract]  you can control which property need to include/exclude in serialization, and each of the property add [DataMember] - (you can define name, order, required
  • DataControl very limit control the SOAP message, MessageContract give full control.
  • MessageContract 
    • Use to tweak the structure of the soap XML Message.
    • include custom information in the SOAP header E.g. User Credential, license key, session keys and etc.
    • Change name of the wrapper element in SOAP Message.
    • Encrypt message and paramater. Use ProtectionLevel named parameter.

Tuesday, August 23, 2016

Javascript, JQuery, CSS

Javascript 
  • Program behavior of web pages, web browser.
  • Interpreter language (no need compile). [C# is Compiled Language]
  • Case Sensitive
  • Use Client side processor to execute.
  • Faster, not require to process in the web server and sent back with server bandwidth. 
  • Reduce Load on servers.
  • Disadvantage :
    • Security issue, the java script can exploit by user.
    • Many version, different version may have different result. and also different browser too.
JQuery - Make it easier to use Javascript on your website

CSS 
  • Describe how HTML element should display.
  • Development faster, Low maintenance, no need change in every page.
  • Disadvantage : 
    • Fragmentation, different dimensions with each browser and also device (PC and mobile)
  • select all p elements inside a div element? div p
  • select elements with class name "test"? .test
  • select an element with id "demo"?  #demo
  • border-width:10px 1px 5px 20px; (Top, Right , Bottom, Left)

XML, XHTML, XPath, XSLT

XML (Extensible Markup Language)
  • A computer language which use mark up and is capable to being extend.
  • XML was designed to store and transport data
  • Markup : Notation or Symbol used to correct in marking up text and indicate how text should be display (<, >, ^,?,/)
  • Extensible : Capable to expend or add by Developer.
  • XML Element 
    • Case Sensitive : Open and Close Tag but be same. E.g. <chap>
    • Not overlap
    • XML Document should have 1 root Element e.g. book
  • XML attributes 
    • single or double quotation (' or ")
    • Good for html
  • XML Declaration  (prolog)
    • optional, but if has, it must 1st line and no other content.
    • version + character encoding used in document
    • version is mandatory and encoding is optional (Support UTF-8 or UTF-16.)


Avoid using XML attributes
  • attributes cannot contain multiple values (child elements can).
  • attributes are not easily expandable (for future changes).
  • attributes cannot describe structures (child elements can).
  • attributes are more difficult to manipulate by program code.
  • attribute values are not easy to test against a DTD.
When use XML attributes and element
  • Element is store part of the data, attribute is not (ID, counter or unique identifier)
  • Element store data itself, attribute is store metadata.
XML VS HTML
  • XML was designed to carry data - with focus on what data is.
  • HTML was designed to display data - with focus on how data looks.
  • XML tags are not predefined like HTML tags are.
  • XML has rule, HTML no rule.
XHTML
  • newer version of HTML, strict rules.
  • Consist 3 parts : DOCTYPE, Head and Body.
  • All Tags closed
  • <!DOCTYPE html-is Document Type Definition (DTD), specifies what type of document is this (XHTML)
  • <html xmlns="http://www.w3.org/1999/xhtml"> - specifies the namespace, tell browser all tags contained within <html> belong to CHTML namespace as definesd by the W3C
  • <meta> tag is used to specify keywords that describe a document's contents (name & content)
  • Example: <strong><p><br /><h1>
HTML
XHTML
No closing tag <br>
Tag are extensible <br />
Tags are not case-sensitive <Body>
Tags only allow lowercase <body>
Attribute optional be quoted <a href=index.html>
Attribute must be quoted <a href="index.html">
Overlapping tags <b><i></b></i>
No overlapping tags <b><i></i></b>

XPath
  • Language for define parts of an XML document. It Is a major element in XSLT.
  • uses path expression to navigate in XML.(allow condition)
  • E.g. /bookstore/book[price>35]
  • E.g. /root_tag/element_a/element_b
  • Selection and addressing elements and attributes in an XML document. E.g. Select node
XSLT
  • eXtensible Stylesheet Language
  • Transformation of XML document into HTML, XHTML (become XHTML got tables or line that match with XML) E.g. people.xml + people.xls
  • XPath identifies the parts of an XML document that should be transformed, and XSLT says how the transformation should be done

XML vs JSON vs CSV

YAML
Most easily understood as an extension of JSON. Has a notion of aliases that allow object graphs of arbitrary complexity to be created. Has a concept of metadata like tags that can be used for proper typing.

Advantages:
  • XML - Lots of libraries, Devs are familiar with it, XSLT, Can be easiily Validated by both client and server (XSD, DTD), Hierarchical Data
  • JSON - easily interpreted on client side, compact notation, Hierarchical Data
  • CSV - Opens in Excel(?)
Disadvantages:
  • XML - Bloated, harder to interpret in JavaScript than JSON
  • JSON - If used improperly can pose a security hole (don't use eval), Not all languages have libraries to interpret it.
  • CSV - Does not support hierarchical data, you'd be the only one doing it, it's actually much harder than most devs think to parse valid csv files (CSV values can contain new lines as long as they are between quotes, etc).

Partial Classes

  • ASP.NET use partial class to designer and code behind, so button can found in code behind.
  • A single classstruct or interface divide to multiple source code files.
  • Code Generators / designers to separate with user edit to the files, clean framework
  • 2 Developer can work in different source code for a single class.
  • Inherit 2 Interfaces , 1 partial class handle 1 interface.
  • When writing the code, it will have intellisense to not allow you to make duplicate or find the properties in this 2 files.
  • At compile time , these multiple files get combined into a single class.
  • Partial methods
    • private and must have partial keyword.
    • must void.
    • implementation is optional
    • can ref param but not out param

Page Directives


  • Set up the environment for the page to run.
  • Import namespace, assembly and register custom control to the page.
<%@  [Directive_name] [Attribute] %>
  • Application
    • Define application-specific attributes (Language)
  • Assembly
    • Link assembly to the page or application.
  • Control
    • Use for User Control (.ascx)
  • Implements
    • must implement .NET framework interfaces.
  • Import 
    • import namespace
  • Master
    • a page file be the master page
  • MasterType
    • assign a class name to the master property of page.
  • OutputCache
    • control the output caching policies.
  • Page
    • define the attributes specific to the page.
  • PreviousPageType
    • assign a class to a page
  • Reference
    • another page or user control should be compoiled and linked to the current page.
  • Register
    • register custom server controls and user controls to your page.

Web.Config and Machine.Config

  • Manage settings at application level.
  • XML Format
  • Visual Studio create we.config for each project (by default).
  • Application can execute without web.config, but debug cannot.
  • Changes in web.config, no need reboot the web server.
  • Sub Folder web conig can be overwrrite main web config.
  • Able to reference another config <appSettings configSource="appSettings.config" />
  1. Config Sections
    • Handle configuration section.
  2. Application Settings
    • Storing application-wide name-value pairs for read only access.
  3. Connection Strings
  4. System.Web
    • Authentication
    • Authorization
    • Caching
    • CustomErrors
    • Deployment
    • HostingEnvironment
    • Identity
    • Membership
    • Pages
    • URL Mappings
    • Web Controls
    • Web Services
    • ......
Machine.Config
  • Master configuration file on your system with a lot of default settings. 
  • The settings of Machine.config file are applied to the whole asp.net applications on your server.
  • Web.config is the file for the local settings to be applied for a website or application.
  • Each .NET Framework version has only one machine.config file , at the same time, each web application has its own web.config file.
  • The machine.config file is at the highest level in the configuration hierarchy while Web.config file is to override the settings from the machine.config file.
  • Get the Machine Config Path Response.Write(ConfigurationManager.OpenMachineConfiguration().FilePath);
  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config

Sunday, August 21, 2016

Global.asax

Application Level Logic and event handling.

The events of the Global.asax file are:
  1. Application_Start() :  invoked when first application domain is created.
  2. Session_Start() : Invoked every time a session is start.
  3. Application_BeginRequest() : invoked when every request for the web.
  4. Application_AuthenticateRequest() : It checks to determine whether or not the user is valid.
  5. Application_Error() : Whenever an unhandled exception occurs then this event will be called.
  6. Session_End() : When a user session is ended and all the data related to a specific user is cleared then the Session_End() event is called.
  7. Application_End() : This method is called before the application ends. This can take place if IIS is restarted or the application domain is changing.
  8. Application_Disposed() : This event is called after the application will be shut down and the .NET GC is about to reclaim the memory it occupies. Although this is very late to perform any clean-up but we can use it for safety purposes.

Application State

Application State is stored in the memory of the the server and is faster than storing and retrieving information in a database.
  • Use for Global Access and need for entire time. E.g. Track user online
  • are multi-user global data. (Session is Single-user global data)
  • Available across all pages and across all sessions. (Session is for specific session)
  • Stored on the web server. Not shared across a Web Farm. 
  • No Expired period. application object end when the worker process restart. 
  • Not thread safe (Lock), got Application.Lock()
  • Not For send data from 1 web form to another, because will stay in memory long time and other user can change it.

Friday, August 19, 2016

Cookies

  • is a client side storage of your variables. 
  • It stored on client machine by browser physically. It's scope is machine wide.
  • Use for authentication, shopping cart content
  • Cookies cannot carry virus or install malware, but can be spyware to track user's browsing activities.
  • set expires to .addDays(-1) to delete cookies
Limitation of Cookies
  • Size of cookies is limited to 4096 bytes.
  • Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
  • End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.
  • If user clear cookie , we cannot get back
    • Persistent Cookies
      • Remain in client computer, even after browser is closed, you can configure how long the cookies expires.
    • Non-Persistent Cookies
      • is set when you don't set expires property, it will remain in memory until the browser is closed.
      • Good for public computer
Because of this :

1.    You should not store sensitive data on cookie.
2.    Cookie has no effect on server resources.
3.    Cookie expires at specified date by you.

Request.Browser.Cookies to check the browser support cookies.
Check Browser Cookies enable or disabled ? write own code to check if... else with Querystring



Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));       
Response.Cookies.Add(userInfo);

HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
 User_color = reqCookies["UserColor"].ToString();        
}

Example 2
Response.Cookies["userName"].Value = "Annathurai";                     
Response.Cookies["userColor"].Value = "Black";

User_Name = Request.Cookies["userName"].Value;        
User_Color = Request.Cookies["userColor"].Value;

Caching

  • To Store frequently used data in memory.
  • 1st Time will get from DB and retain a copy in memory. Any request during duration will get from cache.
  • After duration, the next request will get from DB again and cache for another duration.
  • Improve the performance and scalability. 
  • VaryByParam="None" , a seperate response is cached for GET and POST request, that's why when you change drop down (POST), it will keep showing back same selection.
  • Disadvantage: cached pages that display results can be inconsistent, i.e. not reflecting the latest changes applied to a database.
1)Output Caching
  • Store a copy rendered HTML pages to the client.
<%@ OutputCache Duration="10"//Second 
VaryByParam="ddlProducts" //No use then None
Location="ServerAndClient" //Where the cache store %>

OR Code Behind :

Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["ddlProducts"] = true;


2)Fragment Chaching
  • partial Caching use for specific section of page is static and take long time to load. Others is process like normal. E.g. past 10 year total sales.
  • Use in UserControl
  • "Shared =  true" attribute in OutputCache only for userControl, it allow many web forms share a single userControl.
Steps :
  1. Encapsulate specific sections of that page put into userControl.
  2. Use OutputCache directive on that userControl to specify the cache settings.
  3. Drag and drop the userControl on the webform.
VaryByParam
Description
none
only GET
*
n versions of page cached based on query string and/or POST body
-can be user control or QueryString
V1
n versions of page cached based on value of V1 variable in query string or POST body
V1;V2
n versions of page cached based on value of V1 and V2 variables in query string or POST body

  • VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.)
  • VaryByControl - for user controls, maintain separate cache entry for properties of a user control
  • VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplication derived class.
3)Data Caching
  • Store data in cache. Just Query DB 1 time.
  • Cache will be remove when expired, full, dependency object change.
  • Cache can set expired, but Application Cannot.
  • AbsoluteExpiration : when should be remove the cache
  • SlidingExpiration : How long data remain in cache after the data was last accessed.
  • You will get run-time error if sepicy AbsoluteExpiration and SlidingExpiration .
  • CacheItemPirority : If server memory full, cache may removed. So this 1 is to specified the priority of cache. 
  • Add and Insert is same. Different : If Cache already have, add is not work, but insert will overwrite the Cache.
  • CacheItemRemovedCallback :  this delegate use when cached item is removed from cache, we can store the info to DB.
  • Cache Dependency
    • When the file changes, the cache will remove.
    • https://www.youtube.com/watch?v=cB9TlZB3pSw#t=61.538684 (DB)
Different between Cache and Session and Application
  • Cache and Application is per application(Shared all user), Session is per user.
  • Cache can be remove in expire, full or dependency changes, but Session will stay until session end. Application do not time out or file dependency.
  • Cache and Application is keep in process worker, Session can keep in external (state server or SQL server) and apply for Web Farm.

Session

Session is a server side storage of your variables. Default, it stored on server's memory. But you can configure it to store at SqlServer. It's scope is browser wide. 
  • Session data is stored on the server and key are stored in cookies files, if cookies is disabled then session id key passed via query string. <sessionState cookieless="AutoDetect" />
  • Same user can run two or more browsers and each browser has it's own session.
  • Maintain Data all over the application.
  • Store any kind of object.
  • Secure and transparent from the user (You can save sensitive data in session)
  • After user closes browser, session timeout only clears all information. (default is 20 minutes) <sessionState timeout="30" />
  • Can disable Session in Page Level and Application Level(web.config)
  • Can set Read Only in page level.
  • Use Out-Proc Session Mode can share session between web server.
Disadvantage :
  • Perform overhead in large volume, because store in Server.
Session can store at few places :
  • InProc (In-Memory Object)
    • Default Session Mode
    • Useful in Single Web Server
    • Store on the current application domain and within worker process (w3wp.exe) (access fastest)
    • Object can be added without serialization.
    • if worker process or App Pool restart, session data will lost.
    • Not Suit Web Farm
  • State Server (Aspnet_state.exe)
    • Out-Proc Session Mode.
    • Useful in Web Farm.
    • More scalability than InProc. (dedicated state server, more memory to process it and no impact the Processing Web Server)
    • Use stand-alone Windows Service , outside of IIS and application domain,  can be different server.
    • Restart App domain, your session still be alive.
    • Overhead Serialization and de-serialization, increase data access cost, process slow because run in different process.
    • Use TCP to connect (tcpip=ServerIP:42424)
  • SQL Server (Database)
    • Out-Proc Session Mode.
    • More reliable and secure. (Restart IIS and SQL Server, the data is still here, until it time out)
    • Useful in Web Farm.
    • If Server Frequent restart, SQL Server is best choice.
    • More Scalable than State Servcer and InProc
    • keep data centralized location (Database).
    • able to share session between 2 application.
    • Slower than StateServer and InProc. (Retreive Data from HardDisk is slower than Memory)
    • Overhead Serialization and de-serialization, increase data access cost, process slow because run in different process.
  • Custom (Custom Provider)
    • Existing table to store session data.
    • We need to create own session ID.
    • No Depend ON IIS
    • Create own algorithm for generate session ID.
    • Process Data slow
    • need to handle yourself, especially security.