Log4net (1)

In VS 2013, create a new web application project. Go to NuGet, and search for Log4net, and install it in your web project.
image

In your /Bin folder, you should see the log4net dll and xml file
image

And you should see log4net in the Reference
image

(If you cannot see the /bin folder, click “Show All Files” in your project.)
image

Now we want to put the log4net configuration information in a separate file under the application root, called Log4Net.config
Here is the Log4Net.config
image

Open AssemblyInfo.cs and add this line in the end:
image
image

Add a line to web.config in the configSections tag.
image
Add to Startup.cs
image
image

In the caller (ASPX.CS), add these:
image

These log files are created under the root:
image

What the log file looks like:
image

To use Window’s event log to log information, add a new “appender” section to Log4net.config, and change the root section so the EventLogAppender is used for logging.
image

Run the application again, and you will see the logs in Event Log:
image

11/10/2013, 10:05pm

APRess ASP.NET MVC 4 (3)

Chapter 8: Ajax and jQuery
Use ScriptBundle and StyleBundle to bundle scripts/styles into one single file. (Include() method)
Bundles are added in the BundleConfig class in the app_start/BundleConfig.cs:
image
image
To use your bundle in View:
image
Execute the jQuery script when all elements in HTML are loaded –
$(document).ready(handler)
or
$().ready(handler)
or
$(handler)
or
$(document).ready(function(){
…..
});
or
$(function(){
…..
});

jQuery selector
$(‘#menu’): id
$(‘.selected’): class
$(‘h1’): tag
$(‘#menu ul’): descendants

var myname=$(‘#myname’).val();
alert(myname);
image
One way to achieve “unobstrusive” –
(1) In event-handler.js: has the javascript file defined
image
(2) In HTML, include the js file:
image
Working with Ajax
image
Page 118
AjaxHelper
@Html and @Ajax methods are very similar except that @Ajax are async.
This is a regular link
@Html.ActionLink(“This is a regular link”, “actionName”,”controllerName”)
This is an async link
@Ajax.ActionLink(“This an Ajax Link”,”actionName”,”controllerName”,
new AjaxOptions {
Confirm = “Are you sure?”,
HttpMethod=”Post”,
UpdateTargetId = “resultDiv”,
InsertionMode = InsertionMode.Replace
}))

Other options include: OnBegin, OnComplete, OnSuccess and OnFailure.
LoadingElementId and LoadingElementDuration are images displayed while process in ongoing.
To change a form to use Ajax/Async processing: (using the Send email form as an example)
(1) In your View, add a DIV tag around your form. The return result (a partial view) will completely replace this form.
image
(2) Outside of that DIV tag, add another DIV that can be used to display images/text during the async process.
image
(3) Change the Html form to Ajax Form; also add options for the Ajax Form:
image
(4) Change the controller so partial view (not full view) is returned. (Because in Ajax Form, we’re only replacing part of the screen with returned results)
image
Creating Ajax ActionLinks
Step by step (create an Ajax Action link, so when clicked, an image displays)
(1) You access the site by this URL:
http://localhost:50619/AjaxMessage/Send/Hydrangeas in which Hydrangeas is the paramater (id=Hydrangeas). You see the Send form with a link at the bottom
(2) In /AjaxMessage/Send controller,
image
(3) View – Display the Ajax Link
image
(4) Link is displayed
image
(5) When clicked, (the posting URL is /Pet/GetPhoto/Hydrangeas), 
image
(6) This is the View of GetPhoto – an HTML markup for image
image
(7) In the browser, the HTML return replaces anything inside the DIV tag  thus the images is displayed.
image
Page 124
Implementing Ajax Callback
Flow of an Ajax call and Ajax Option/Functions available:
image
Now, use these callback functions to prevent user clicking on the button multiple times!!!!!

In your Ajax Form, add two more ajax options using OnBegin and OnComplete.
image
At the end of the View file, add these two function to hide the while form (and hiding the button too). The form will be displayed again once the request is completed (but before OnSuccess or OnFailure)
image
The above is using MVC’s Ajax Helper to create a form that uses Ajax to send request – which is pretty straight forward and easy to handle. Next, using jQuery to make Ajax request. (Actually, MVC’s Ajax.Begin Form and Ajax.ActionLink() are translated into jQuery Ajax calls!! The information in the AjaxOptions provide everything jQuery needs to know to make an ajax call)
in jQuery, you can use $.ajax(), $.post() or $.get() to make ajax call.
But it’s better to use just one of them so it’s easier to remember –
$.ajax({
url: ‘”……”, // URL to which the request is sent ==> AjaxOptions.Url
type: “……”, // Post, Get, Delete, Put ==> AjaxOptions.HttpMethod
data: “……”, // data sent ==> Form fields
dataType: “……”, // data expected from the server; xml, json, jsonp, script, text or html
beforeSend: handlername, ==> AjaxOptions.OnBegin
complete: handlername, ==> AjaxOptions.OnComplete
success: handlername, ==> AjaxOptions.OnSuccess
error: handlername ==> AjaxOptions.OnFailure
});

Now create a link that use jQuery to download the pic –
(1) Add a new image file to your folder
image
(2) Create a new Link in View
image
(3) Add the javascript
image
So now you can get the image using MVC Ajax or jQuery Ajax
image
Working with JSON
Using Action to return method is simple –
(1) Set action method return type to JsonResult
(2) Create the object, and return it using Json(object)
For example:
image
Caution: Do not return JSON in GET method!!! Limit it for POST method.

If you must use GET, add a second parameter
image
Page 129

APRess ASP.NET MVC 4 (2)

Adding a business class
e.g., a class in charge of sending email messages to pet owners. Or, a class that creates image thumbnails. In short, any type of processing on the server is handled by business model classes. (Similar to APP_CODE in Web Site Project)
Under Models, add a new folder: Business. And under the folder create a new class: PetManagement.cs.
image
image
Create a view model: Picture Model to pass between controller and view:
image
Then create the view
image
This line:
image
adds a anti-forgery token in HTML like this:
image

This works only when the server side action also has a annotation tag placed on top
(This is the POST Method)
image
After this you can upload and save the file.
Understand Model Binding
GET request – saved in HttpRequest.QueryString
POST request – saved in HttpRequest.Form
POST/File Upload request — saved in HttpRequest.Files

Model Binding:
1) No manual code is needed to extract the data from the HTTPRequest object.
2) Data type conversion happen automatically.
3) Data can be easily validated

Model Binding is possible thanks to the built-on DefaultModelBinder.
It relies on the “names” of the values – they must be the same as defined in the model object.
Chapter 7 – Data Validation (Page 94)
We have a MessageModel
image
Now we need a controller. MessageController.
image

ModelState.AddModelError has two parameters –
(1) specific property from the view model for which the error is generated. Can be empty if this is a generic error.
(2) error description.
Next, create a GET (Form) view:
image
Now the form is created, but there is no validation checking because there is no data annotation defined in the model and there is no manual checking.
image
Now we add some manual checking
image
Now if you submit the form with an empty “From” field, you get this error:
image
Validate with Data Annotation Benefits:
1) enforced across the whole application, not just a single action.
2) no need to call a method, or do anything to enforce the rule
3) code is much less than coding manually
image
Other annotation:
[CreditCard] is 15 or 16 digits without spaces
[EmailAddress] is a well-formed email address
[EnumDatatype(typeof(name of enum)] enable a .NET framework enum be mapped to a data column. The value must be of those defined in the enum.
[FileExtension(Extensions=”.jpg,.png,.gif”)] file extension must be in one of them
[Range(min, max)] the value must be in the range.
[RegularExpression(pattern)] must match pattern
[Required] is required field
[StringLength(max)] is max length
[URL] must be a well-formed URL
Once you added the notations, the validation will validate the inputs:
image
Custom Data Annotations
To create a custom data annotation (for example, [BirthCertificateNumber]) you need to create a class that inherits from ValidationAttribute. Name of the class must end with Attribute.
Create a folder under /Models, used to save all custom annotations.
image

under the new folder, create a new class: BirthCertificateNumberAttribute.cs.
image
Then in the MessageModel, add a new property so we can test it:
image
In the GET form, add the form fields for the new property so we can test the validation
image
Now you see this form: (new field with the [BirthCertificateNumber] Annotation.
image
If you enter something that’s not valid for this format, you see this error message (custom validations are performed only on the server side!!!! No javascript validation)
image
Page 110

APRess ASP.NET MVC 4 (1)

Chapter 2 – Installing MVC 4
Anatomy of an ASP.NET Internet Application
App_Start – configurable files such as authentication, bundling, filtering, routing and WEBAPI.
Content – CSS and other assets in your project.
Controllers – Controllers
Filters – Action Filters are custom attributes that provide a declarative means to add a specific behavior to controller action methods. Simply the implementation of a logic.
Model – data and business logic classes.
Scripts – Javascripts
Views – UI Logic/HTML files.
Global.asax: Handle application and session level events
Packages.Config – Nuget

Chapter 3 – Build an application – “Have you seen me?”
(1) In VS 2012, create a MVC 4 Internet Application, debug, and go to login page. VS 2012 will create a LocalDB under /APP_Data.
image
(2) Right click the database file, and select “Include in Project”. Double click the database and VS will open the DB in Server Explorer.
image
(3) Right click “Table” and select New Query. You see a new query window. Cut and paste the SQL script in there (script from the book)
image
(4) Now you should have new tables created.
image
Chapter 4: Controllers
Controllers process incoming HTTP requests. Method in a controller is called action method because they return an object of type ActionResult.
(1) IN Global.asax., APplication_Start, it register all configuration files; including configuration, filter, routes, bundles and auth. All these classes are defined in app_start:
image
ViewResult (ActionResult)
image
FileResult
image
or this (this will prompt user to download)
image
(this will display the image in browser)
image
If user is accessing an unauthorized area, return this:
image
404 Not found error
Page 47
Chapter 5: Views
——————————–
@DateTime.Now
——————————–
@if (DateTime.Today.Year == 2103) {
<span>Current Year</span>
}
——————————–
<ul>
@foreach (var t in tweets) {
  <li>@t.content</li>
}
</ul>
——————————–
@{
var name=”Jose”;
var message = “Welcome “ + name;
}
———————————-
In Action method, right click anywhere in the method, and select “Add View” to add a view.
image
To return the default view for the current action method, simply do return View(); else, do return View(“NameOfView”)
image
image
image
In _Layout.cshtml, to display a section, use @RenderSection(“sectionname”, required: false)
@RenderBody(); renders the main contents.
Working with HTML Helpder Methods
Displays a link:
@Html.ActionLink(“Display text”, “ActionName”, ‘ControllerName”);
Render a partial view:
@Html.Partial(“MyViewName”);
image
_LoginPartial.cshtml is under /View/Shared/….
image
It displays different contents based on the Request.IsAuthenticated()
image
Here it either show log in links, or says “Hello, XXX”.
image

ViewData and ViewBag.
To pass information from an action method to a view, you basically have 3 options
1) ViewData
2) ViewBag (actually the same as ViewData, Except View bag has intellisense).Properties can be added to Viewbag dynamically.
3) strongly typed view with a view model object.

ViewData
image
In View, retrieve the values from ViewData[“….”]
image
ViewBag
image
Use ViewBag – it’s better
NOTICE!!!
In your action method, if you assign some data to ViewData/ViewBag, but then use RedirectToAction (HTTP 302 Redirect) to redirect to another action, then the data saved in ViewData/Viewbag will be lost!!!
In this case, you need to use “TempData” – it survives redirect. Saves the data in a “session” object. However, the data is discarded as soon as the view is rendered. Refreshing the page will cause an error.
Working with Strongly Typed Views
When you associate a view with a view model, the view becomes a strongly-typed view.
For example, this view model/class has three properties.
image
Now, this view is associated with that view model.
image
Inside your view, you simply refer to the model (m, a, z, x, or any letter or string to represent the model data passed from controller)
image
Chapter 6: Models
Page 69
Model –
Data Model – classes that interact with database. Normally created by EF. Closely match database tables.
Business Model – implement business functionalities/rules.
View Model – passed information from controller to views. Not exactly data model, but something in between data model and business model. You can define as many view models as needed and use them in different scenarios.
To add an EF data model, two ways –
(1) Using EF Reverse Engineer wizard
image

(2) Add a new item
image
To refresh your models (if you change anything in DB), do this:
image
image
Right click the entity (in design view) and you can change the Entity Set name to the correct form.
image
Page 81

orEILLY–bOOTSTRAP (1)

Chapter 1 – Bootstrap Scaffolding
Bootstrap file structure includes: CSS, Javascript and Image
 image
Grid System
Bootstrap uses 12 column/grids, marking for a 940px-wide container.
image
To run Bootstrap: (If you don’t include jQuery, you get an javascript error: Line: 6, Error: Object expected)
image
Offset
image
Add this CSS style to see the cell borders:
image
If using percentage for width: use row-fluid
image

Professional ASP.NET 4.5 in C# and vb.net (2)

Chapter 5: Web Server Controls
Label control’s Hot key ==> AccessKey=”N” AssociatedControlID=”TextBox1”
image
Literal Control ==> Mode=”Encode”, will encode the output before displaying
image
To enable AutoPostback, enable the property for that control (drop down list, textbox tec.)
image
Button server Control:
CauseValidation Property:
CommandName Property:
You can have two buttons that has the same OnCommand method, but different name, such as
image
In the OnCommand code, you can check the command name to decide what code to run:
image
If you have other parameters to add to the button, use CommandArgument property. in the code behind, you check the value of e.CommandArgument.
Button event:
image
Page 199
Chapter 6: Validation server Controls
To use unobstrusive validation, need jQuery; also, configure, either
(1) web.config
image
(2) or, in global.asax
image

Note: The data-* attributes are only rendered when unobstrusive validation is turned one.
When using requiredfieldvalidator to validate a drop down, the the InitialValue to the first value (default selected) of the drop down, such as this one:
image
Use CompareValidator to ensure the input is an integer.
image
You can use “Currency”,”Date”, “Double”, “Integer”, String”
Use CompareValidator to validate against a value
input has to be an integer >= 18
image
RangeValidator
Must be an integer between 30 and 40
image
To turn off client-side validation, set the validation control’s property EnableClientScript to false.
if you want to show images (instead of text) as error message, you can edit the Text property as this one shows:
image
You get this:
image
Validation Groups
Use Validation Groups to validate different groups of controls on the same form
image
Chapter 7: User and Server Controls
Load user control into form programmatically
image
To access properties and methods that the user control exposes, you need to cast the control from the generic control type to its actual type.
image
page 240

Custom Server Control – Creating a test one!!
User Control is a great way of encapsulating functionality in one unit.
The custom control needs to be created as a new project, not a new item.
image
Create a ASP.NET Server Control project, compile it, and add another web project, compile the solution, so you have:
image
After that you should see your server control in the toolbox:
image
If you don’t, right click the white space in toolbox, and check “Show All”, you should see a lot more controls in the toolbox, including your custom one. uncheck the “Show All”, and most will be gone, but your custom control will stay. Now you can drag your custom control to your web form.
Page 299

Chapter 8: Data Binding
Once you set up a data source, you can configure the data source mode to either DataSet or DataReader
image
Conflict Detection
Default is OverwriteChanges – If changed to CompareAllValues: does not update the data if something has changed since the data is retrieved for update.
image
To detect and process data access error: In DataSource’s Updated event.
image
To use Entity Data Source
(1) Add a Entity Data Model toy our project, configure it to map to tables/store procs/views of a database.
image
(2) Add a Entity Data Source and use that connection as a connection, and configure it.
image
image
Query Extender – works with any data source control that implements the iQueryableDataSource interface. That includes LinqDataSource and EntityDataSource.
(1) Drag it to the designer
image
(2) Use the EntityDataSource’s id as the “TargetControlID” of the QueryExtender.
image
he Query Extender further filter the query results to the condition specified
image

XMLDataSource Control: Binding XML in memory or on a physical drive.
ObjectDatSource – bind directly to middle-layer classes or business objects.
Enabling caching by changing the property in the data source. Note that SQLDataSource caching is available only when the DatsSourceMode is DataSet.
A good control that can be used: Chart
image
image
Chapter 9: Model Binding
MVC was only available in MVC, but now also available in Web Form.
In GridView, you specify the optional ItemType=”Customer”, to get the intellisense.
If you’re expecting a parameter from the QueryString:
image
System.Web.ModelBinding.QueryString is a ValueProvider
ValueProvider:
Form, Control, QueryString, Cookie, Profile, RouteData, Session
Example: A drop down and a GridView
image
The GridView is to be refreshed upon selection of an item in Drop Down: (Drop down’s AutoPostBack is true, so GridView will refreshed during the postback)
image
Inserting
image
image

Professional ASP.NET 4.5 in C# and vb.net (1)

Chapter 1: One ASP.NET
Whatever project type you choose, it’s all based on ASP.NET. You can add any project to your solution later and it will still be supported.

image

For example, you want to build an app that is a single page app, and use Twitter/Facebook to log in. (VS 2013)
(1) Create a ASP.NET Web APP
image
(2) Select SPA
image
(3) In the solution, add a Web API
image
(To test your Web API, use WebApiTestClient – download it from Nuget.)
(4) SignalR – Relatime functionality.

Chapter 2: HTML 5 and CSS3 Design with ASP.NET
HTML5 –
input type: tel, search, url, email, datetime, date, month, week, time, datetime-local, number, range, color

Example 1:
image

In google crome, you will see:
image
(Not working in IE because it’s not implemented in IE yet)
Example 2:
image
IE and Chrome implemented it differently.
image

CSS Selector
Applies to <p> tag
image
Applies to all tags
image
Descendent Selector
does not have to be direct descendant
image
has to be direct descendant
image 
Attribute Selector
Applies to any element that has the href attribute
image
Advanced:
For each link that starts with https, add an image
image
Class Selector (using DOT)
image
ID Selector (using #)
image
Others:
image
image

Pseudo-Element:
First line or letter of each paragraph
image
Insert content before and after the tag.
image
selector Grouping
image
Page 35

Modernizr.js is inclided in all VS templates to achieve compatibility with older browsers. With better HTML5 support, use HTML5Shiv.js, also known as HTML5 shim file.
Chapter 3: Asp.net Web Forms Structure
Import your namespace so it can be referenced on each page without the full name
image
Under app_code, it is possible to use classes created using C# and VB – need to create a VB and CS folder, such as:
image
and also update web.config file:
image
Resource files – data dictionary and language files.
*** new: Rename your HTML or TEXT file to *.aspx and they will be compiled into APP_WEB_XXXX.dll like other ASP.NET files!!!
Right click a class (in class diagram/designer), and select Refactor –> Extract Interface to extract the interface.
image

You get an Interface file.
image
You can add or edit class members here:
image
After you add a new method:
image

Chapter 4: Server side controls and client-side controls
HTML Server Controls
image
Top is the regular button server control; button is the HTML button control (with runat=”server”). make sure to add an ID attribute to HTML server controls.
image
Define the javascript string in code behind, and then execute the javascript on postback
image
***
Page.ClientScript.RegisterClientScriptBlock – javascript placed on top
Page.ClientScript.RegisterStartupScript – javascript placed at bottom
Page.ClientScript.RegisterStartupScriptInclude – include an external javascript file
***
Page 122

asp.net 4.5 database (2)

SQL2012 new features – FileTable. Allow access to data in the form of files and folder. Also supports pagination –
SELECT * FROM abc order by name offset 5 rows fetch next 10 rows only

A database must be FILESTREAM enabled before you can create FileTables. There is a T-SQL you need to execute when you create the database.

image

The data will be saved in the [DIRECTORY_NAME] folder.
To create a table as a FILETABLE:
CREATE TABLE FT AS FILETABLE

Chapter 4 – Accessing Data Using ADO.NET
SqlCrential is a new class in .NET 4.5. You can use it to store connection string credentials (SQL id/password).
image

Encrypt your connection string in Web.Config
image

You get this:
image

Every asp.net page has a ValidateRequest tag, and true by default:
image
This will prevent injection attack.

Use TryParse to test casting operation before you use the value (Save to DB etc.)
Chapter 5 – LINQ

Difference between iEnumerable and iQueryable –
iEnumerable – the query (and filters) is executed in the memory;
iQUeryable – the query (and filters) is executed on the source. Good for data paging. Page 83

Exercise using LINQ to SQL
Create a DB: with 2 table. And insert some test data.
image

In VS 2012, add a console app:
image
Right click the project and add New iTem –> Linq To SQL Class.
To add foreign key relationship

Define the FK condition
image

Once you define the FY, when you drag the tables from SQL explorer to the LINQ designer, it will create two classes and also the relationship.
image

A datacontext will be created for you.
image

Write code to read data using the context
image
F5, result:
image
Behind the scenes, Linq to SQl use sqlmetal.exe to generate the mapping.
By default, when an entity is loaded with data, child entities are not populated. Called Lazy Loading – for performance reasons.

To eager load, use the class “DataLoadOptions”.
image

Querying WCF Data services
WCF DS allows you to expose your data as RESTFUL services using OData protocol.

Exercise: Querying NetFlix DB – no longer works.
Page 98

asp.net 4.5 database (1)

For a new DB, the code-centric is simpler than it is for an existing database. Three ways of data access development: 
(1) Database first – reverse engineer the Entity Model from the database schema. generate the entity class automatically from the EM using tools.
(2) Model first – Generate the Entity Model in the designer. Generate the database schema and entity classes from the EM.
(3) Code first – Define model and relationships in code. Create a new DB at runtime.

ADO.NET classes
(1) connect to DB using .NET 4.5 data providers
(2) execute commands
(3) retrieve results

The list of ASO.NET data sources: MS SQL, Oracle.

WCF Data services enables CRUD operations on data using the Open Data Protocol (ODATA). WCF Data services will allow REST-style access to data models. Supports JSON and ATOM.
Entity Framework 5 – supports table-value functions and importing Stored Procs.

Create a sample project in VS 2012. Open VS 2012, in server explorer, add a new SLQ DB.
image

Create a new DB: Gadgets
image
Now add some data. Right click the table, and View Data.
image
If you want to make the Id field auto-generated:
image

Now we have a data source, create a asp.net web site to consume the data.
Now add a asp.net web form application to your solution.
image
Press F5 and you should see a default web site. Close it.
Right click the project, add new item –>
image
Since you already have a DB, select generate from DB option.
image
Set up connection strings, and give the name “Entities”
image
In next screen, select the table, and give a Model name space of GadgetsModel.
In your solution explorer, if you only want to display elements related to a specific item (such as a folder), then right click the element, and click “Scope to this.”

Use the back arrow to get out of the “scope” mode.
image

When you scope to the EDMX, you see this:
image
Add a web form to your web project called GadgetStoreView.aspx
Drag a repeater to the web form. Specify in the property window the ItemType: image

After that you can manually edit the repeater with intellisense support!
image
Now you have this in web form:
image
Now edit the code behind.
image
Press F5 –>
image
You can also use EntityDataSource as a data source.
Drag to the form:
image
Select the Context:
image
image
Then set the data source of the repeater to this new data source.
image
You need to comment out the code in LOAD:
image
or else you will get a message that says it has already been defined.
Press F5, you get the same result using the EntityDataSource:
image

End of Chapter 1 – Page 25

Pro asp.net mvc 4 (1)

image
image
Page 30

[HttpGet] – send initial blank form
[HttpPost] – process posted data

//Render view “Thanks” and pass the object to it.
return View(“Thanks”, guestResponse)

Print the text after @:
@:Hello world!

page 35, 03/02/2013, 05:49pm

include the model in the first line
image
image

Adding Validation
In MVC, validation is applied at the domain model, not user interface. 
If you want to make a bool field required, then make it a nullable field!!
If the client returns NULL, then the Required attribute will report an error.
image
image
image
Because of model binding – the previously enter value will be displayed along with the error messages.
If a field does not pass the validation, the HTML for that fields will have this class defined:
image

Chapter 3 – MVC Pattern
image
Chapter 4 – Essential Language Features
image
image

Extension Method: Convenient way to adding new method to classes that you don’t own and so cannot modify directly.
image
How to use the extension method – just like anything else!
image
Using LINQ to get products
image
image

Deferred – method is not executed until the items in the results are enumerated.
image

image

IQuerable<T> is derived from IEnumerable<T>

Chapter 5 – Working With Razor
File in the /View folder that begins with an underscore (_) is not returned to the user.

Add a new layout page by :View –> Add –> New item –> MVC 4 Layout Page.
To use the new layout page in a view:
image
Or, if you want to include this layout in all views, create another special view called _ViewStart.cshtml and include this code:
image
image
Then you won’t need to include reference to the layout page in every view.
Page 109, 03/04/2013, 09:41pm