asp.net · ebook

[ASP.NET] TryUpdateModel and FormValueProvider

1. TryUpdateModel

TryUpdateModel method: perform a process called model binding where data value are used from the browser request to populate property of our data object. FormValueProvider class will provides value from form data.

Example:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) return;
 
            var rsvp = new GuestResponse();
 
            if (!TryUpdateModel(rsvp, new FormValueProvider(ModelBindingExecutionContext))) return;
 
            ResponseRepository.GetRepository().AddResponse(rsvp);
 
            if (rsvp.WillAttend.HasValue && rsvp.WillAttend.Value)
                Response.Redirect("seeyouthere.html");
            else
                Response.Redirect("sorryyoucantcome.html");
        }

Source: ASP.NET 4.5 Pro Apress – Chapter 1

 

asp.net · pluralsight

[Pluralsight – ASP.NET 3.5 Fundamentals] ASP.NET Architecture (Part 1)

1. ASP.NET Architecture

  • Build completely on top of .NET
    • All pages (.aspx) are parsed into classes and compiled into assemblies
    • Assemblies are loaded on-demand into the worker process (w3wp.exe)
    • Classes are created on demand to service requests
  • You work with ASP.NET by
    • Building additional classes
    • Extending base classes
    • Controlling class generation from .aspx files

Everytime an aspx file is requested, it does go through a class creation mechanism, and the first time it’s requested it go through the parsing of the file and the source code generation for that class.

Example:

<%@ Page Language="C#" Debug="true" %>
<h1>Hello ASP.NET!</h1>
<h3><%= GetType().Assembly.Location %></h3>

First line is Page directive which can influence the page class generation. Debug = true will make the source code file stay on disk. <%= … %> for server side script. %= is called evaluation syntax.

The line GetType().Assembly.Location will give us the location where classes are generated and we can dig in and see how the source code is generated.

2. Dynamic content

  • ASP.NET inherit a lot of dynamic content syntax
  • Interspersed server-side script <%
  • Server-side evaluation syntax <%=
  • Server-side script block (We can’t but executable code here Ex: Response.Write(“”) since the whole script block will be generated directly in class definition)

3. Server-side control

  • Elements marked as runat=”server” (could be HTML control or server-side control definition)
    • Clean alternative way to interspersed server-side script
    • Added to class definition as member variables
    • Programmatically intereact with object model of controls
    • State retained implicitly across POST request to same page

4. Data binding

  • List controls all support data binding
    • Bind a collection (IEnumerable) to a control
    • Implicit creation of child elements based on collection
protected override void OnLoad(EventArgs e)
{
_displayItems.DataSource = _displayItemData;
_displayItems.DataBind();
}

Example:

<%@ Page Language="C#" Debug="false" %>

string[] _displayItemData = {"Item #1","Item #2","Item #3","Item #4","Item #5"};
const int _itemCount = 10;
//Response.Write(""); --invalid
string GetDisplayItem(int n){
	return "Item #" + n.ToString();
}

protected override void OnLoad(EventArgs e)
{
	_displayList.DataSource = _displayItemData;
	_displayList.DataBind();
	base.OnLoad(e);
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Simple Page</title></head>
<body>
<form runat="server">
<h1>Hello ASP.NET !</h1>
<h3>I was loaded from
<%= GetType().Assembly.Location %>
</h3>
	<asp:BulletedList runat="server" ID="_displayList">
		<asp:ListItem>Sample Item 1</asp:ListItem>
		<asp:ListItem>Sample Item 2</asp:ListItem>
		<asp:ListItem>Sample Item 3</asp:ListItem>
	</asp:BulletedList>
	
	<%Response.Write("<h2>Total number of items = "
	+ _itemCount.ToString() + "</h2>");
	%>
</form>
</body>
</html>

5. Declarative Data Binding

Version 2.0 ASP.NET introduces data source controls that enables declarative data binding.

In ASP.NET, we decorate code behind class with partial, when we request to an aspx file, that file will be generated to a class which is also a partial class of code behind file. All controls in aspx will be declared as protected variables in generated class.

6. Page Life Cycle

List of events/functions: (common one in bold)

  • PreInit (only place that we can manipulate master pages and themes)
  • Themes initialized, master pages applied, control skins applied
  • Init (at this point, controls have already been constructed in control tree and we can inspect the control tree)
  • InitComplete
  • CreateChildControls (if IsPostBack) | Control/View state loaded (if IsPostBack)
  • PreLoad (do something before all Load logic is executed. Ex: something prior to data binding)
  • Load
  • Server-side events fired (if IsPostBack)
  • LoadComplete (happens right after all server0side events fired which we can add some custom code)
  • CreateChildControls (if !IsPostBack)
  • PreRender (back stop if you need to do something just before rendering actually takes place and the response is sent back to the client )
  • PreRenderComplete
  • Control/View state saved
  • SaveStateComplete
  • Render
  • Unload

7. Event handling

<%@ Page Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" 
    Inherits="DemoWebForm.Default" %>

AutoEventWireup set to true so instead of wiring up event ourself, we can declare some special events and page will automatically subscribe to it. Example: Instead of overriding OnLoad event, we can set AutoEventWireup = “true” and use Page_Load.

Some special ASP.NET directories

8. Shadow copying (a feature of .NET runtime)

  • Assemblies (libraries) placed in /bin are
    • implicitly referenced by every compiled page
    • shadow copied to an alternate location to avoid file locks
    • monitored for changes to shadowed copies can be updated

This is an important feature when you deploy a new update to your website in order to keep the site running. When you are loading an assembly, instead of loading the assembly directly from the location it’s deployed (/bin), .NET will implicitly copy that to another location. And it will reference that one instead. Also, it will add a timestamp to the original one, then if there is a new update on the original one, it will make another copy and refer to that copy instead.

programming tictac

IIS Installation

To install IIS:

Step 1: Navigate to Control Panel > Uninstall or change a program > Turn Windows Features on or off

Step 2: Choose Internet Information Services > Web Management Tools and World Wide Web Services

If we can’t run a aspx page and get this error “The page you are requesting cannot be served because of the extension configuration.”, normally because we install IIS after Visual Studio or .NET.

=> In Windows 8/10, you have to use Programs and Features, Turn Windows features on or off, IIS, World Wide Web Services, Application Development Features, and check the appropriate items, such as enabling ASP.NET. Also, check .NET Framework 4.5 Advanced Services > WCF Services > HTTP Activation

personal

My dogs are barking

So today, I run for 4.5 miles and it hurts my feet so bad since I am not really a runner but feel bad after 2 weeks skipping the gym.
Anyway, I remember the quote my housemate said last time when we jogged together: “When your feet are hurt, you say My dogs are barking”. I find it amusing but too lazy to verify its source until now, it turns out that there is a brand of shoe called “Hush Puppy” (http://www.hushpuppies.com/US/en/home) and it’s named that as a reference to the expression “My dogs are barking”. In the case of the shoe, Hush Puppies are supposedly so comfortable they can quiet your puppies – that is, stop your feet from hurting.

C#

[C#] Abstraction Class vs Interface

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

  • An abstract class is a special type of a class that cannot be instantiated.
  • An abstract class should, however, be inherited by its subclasses.
  • Abstract classes are either partially implemented or not implemented at all. You can have functionality in your abstract class — the methods in an abstract class can be both abstract and concrete.
  • An abstract class can have constructors — this is one major difference between an abstract class and an interface.
  • You may take advantage of abstract classes to design components and specify some level of common functionality in the methods of the abstract class until a specific implementation of the abstract class is needed in the class hierarchy.
  • The constructor of an Abstract Class can be called through the derived class constructor.
  • All abstract methods must be implemented in its derived class, if inherited.

An interface contains definitions for a group of related functionalities that a class or a struct can implement.

  • We cannot create an object of an interface, we can only create a reference or Interface Variable.
  • An interface will have only abstract methods (method declaration).
  • Interfaces supports Inheritance, Polymorphism (Overloading, Overriding (using the “new” keyword to hide the interface methods above)).
  • We cannot create variables in an interface.
  • Only Properties, Indexers, Methods and Events are allowed in an interface.
  • A class can inherit multiple interfaces, which is also shown in the snapshot above.
  • We cannot create any Access modifiers with Interface Members (like private, public, protected, internal, protected internal, virtual, override, static, abstract etc.)
  • The new keyword is allowed in an interface.
  • All methods of an interface must be defined in every derived class.

You should use interface if

  • You want to simulate inheritant from struct since struct can’t inherit from another struct or class
  • If the functionality you are creating will be useful across a wide range of disparate objects
  • If you are designing small, concise bits of functionality

You should use abstract class if

  •  It applies to objects that are closely related
  • If you are designing large functional units
  • If you want to provide common, implemented functionality among all implementations of your component

 

C#

[C#] VAR keyword

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit “type” var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

In some case like below example, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}