@manhng

Welcome to my blog!

CKEditor

May 24, 2020 09:16

CKEditor (edit)

https://vkhangyang.wordpress.com/2012/07/14/su-dung-ckeditor-vo-ung-dung-asp-net-mvc-3/

https://vkhangyang.wordpress.com/2012/07/09/thm-xa-sua-nhanh-chng-voi-asp-net-mvc-3/

https://vkhangyang.wordpress.com/2016/12/31/su-dung-ckeditor-vao-ung-dung-asp-net-core/

Authorize Attribute in ASP.NET MVC

November 4, 2019 10:12

Authorize Attribute in ASP.NET MVC (edit)

Helper:

        public class ApplicationAuthorizeAttribute : AuthorizeAttribute
	{
		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
		{
			var httpContext = filterContext.HttpContext;
			var request = httpContext.Request;
			var response = httpContext.Response;
			var user = httpContext.User;

			if (request.IsAjaxRequest())
			{
				if (user.Identity.IsAuthenticated == false)
					response.StatusCode = (int)HttpStatusCode.Unauthorized;
				else
					response.StatusCode = (int)HttpStatusCode.Forbidden;

				response.SuppressFormsAuthenticationRedirect = true;
				response.End();
			}

			base.HandleUnauthorizedRequest(filterContext);
		}
	}

Controller:

		[HttpPost]
		public ActionResult GetData1()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

		[HttpPost]
		[ApplicationAuthorize]
		public ActionResult GetData2()
		{
			return Json(new
			{
				Items = new[] { "String 1", "String 2", "String 3" }
			});
		}

		[HttpPost]
		[ApplicationAuthorize(Roles = "admin")]
		public ActionResult GetData3()
		{
                    return Json(new
                    {
                        Items = new[] { "String 1", "String 2", "String 3" }
                    });
                }

ASP.NET MVC: Using JavaScript with Ajax and Razor view

October 8, 2019 19:41

ASP.NET MVC: Using JavaScript with Ajax and Razor view

https://bitoftech.net/

View

<button id="btnGetData" type="button" class="btn btn-primary"> @Resources.GetData</button>

Controller

The complete list of objects is (they all receive the ControllerContext as the contructor parameter):

  • FormValueProvider: search for data in the body (Request.Form)
  • RouteDataValueProvider: search for data in the route (RouteData.Value)
  • QueryStringValueProvider: search for data in the query string (Request.QueryString)
  • HttpFileCollectionValueProvider: search for uploaded files (Request.Files)

System.Web.Mvc.HttpPostAttribute & System.Web.Http.HttpPostAttribute

  • System.Web.Mvc.HttpPostAttribute
  • System.Web.Http.HttpPostAttribute

IHttpActionResult & HttpResponseMessage

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

https://www.infoworld.com/article/3192176/my-two-cents-on-using-the-ihttpactionresult-interface-in-webapi.html

ihttpactionresult

[FromBody]

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#using-frombody

FromBodyAttribute Class (System.Web.Http)

// POST /api/Product/Post
[HttpPost]
public HttpResponseMessage Post([FromBody] Product product)
{
var name = product.Name; // "Product Name"
var price = product.Price; // 0.50
}

Model Binding

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

You can use one of the following attributes to specify the source to use for any given target:

Model

// a complex object
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}

JSON

{
  "Name" : "Product Name",
  "Price" : 0.50 
}

Action Get

// GET: /Home/GetData
[HttpGet]
public ActionResult GetData()
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        string redirectUrl = Utilities.GetPageUrl(actionName, controllerName);
        string loginUrl = Utilities.GetLoginUrl();
        string loginUrlEncrypted = loginUrl;
        ViewBag.Url = loginUrl + redirectUrl;
        return Json(new { Success = true, Data = loginUrlEncrypted }, JsonRequestBehavior.AllowGet);
    }
    catch
    {
        return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
    }
}

Action Post

// POST: /Home/SaveData
[HttpPost]
public ActionResult SaveData([FromBody] Product product)
{
    try
    {
        string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
        bool success = Utilities.SaveProduct(product);
        return Json(new { Success = success, Message = "Success" }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { Success = false, Message = ex.ToString() }, JsonRequestBehavior.AllowGet);
    }
}

Call AJAX using JavaScript / jQuery

<script>
window.HomeSaveData = '@Url.Action("SaveData", "Home")';
$(function () {
var obj =
{
"Name" : "Product Name",
"Price" : 0.50
};
debugger;
$.ajax({
url: window.HomeSaveData,
type: "POST",
dataType: "json",
data: JSON.stringify(obj);
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var message = resultData.Message;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

Call AJAX using JavaScript / jQuery

<script>
window.HomeGetData = '@Url.Action("GetData", "Home")';
$(function () {
$.ajax({
url: window.HomeGetData,
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
debugger;
if (resultData.Success = false) {
debugger;
} else {
var data = resultData.Data;
debugger;
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
timeout: 120000
});
});
</script>

Một số kinh nghiệm phát triển một Web App sử dụng ASP.NET MVC

May 31, 2019 09:26

Một số kinh nghiệm phát triển một Web App sử dụng ASP.NET MVC (edit)

+ Check null trước khi sử dụng .Name, .Age

+ Check null trước khi sử dụng .ToString(), .Parse()...

+ Khở tạo list rỗng trong constructor để tránh trường hợp sử dụng list đó khi mà list null

+ Không sử dụng return default value khi xảy ra Exception

+ Không sử dụng Cache cho những dữ liệu người dùng (private info, User Settings, ...)

+ Chú ý khi trả về từ lệnh return Json(..., );

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property

https://blogs.msdn.microsoft.com/mayurpatankar/2018/04/05/error-during-serialization-or-deserialization-using-the-json-javascriptserializer-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property/

Solution

https://stackoverflow.com/questions/47257227/the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property-c

https://stackoverflow.com/questions/16848289/error-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-proper

ASP.NET MVC Architecture

https://www.tutorialsteacher.com/mvc/mvc-architecture

https://www.c-sharpcorner.com/article/standard-application-architecture-in-mvc/

https://www.danylkoweb.com/Blog/top-10-books-every-net-developer-should-own-QG?quora

https://www.c-sharpcorner.com/article/mvc-5-demo-project-with-entity-framework-db-first/

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/setting-up-database

https://blog.trigent.com/caching-in-asp-net

https://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En

https://stackoverflow.com/questions/10515623/architectural-decisions-asp-net-mvc-entity-framework

https://stackoverflow.com/questions/15856660/architecture-for-aspnet-mvc-web-application

TDD with MVC Applications

July 30, 2018 23:08

TDD with MVC Applications (edit)

TDD With MVC 5 and Entity Framework and Repository pattern

https://code.msdn.microsoft.com/TDD-With-MVC-5-and-Entity-83ade5cf

Developing an ASP.NET MVC 4 Application for TDD using xUnit and Moq

https://github.com/dotnetcurry/tddusingxunit-dncmag-01

ASP.NET MVC 5 application with TDD using Unit testing framework (xUnit.NET) and Moking/Isolation framework (MOQ)

https://github.com/SanjeevForYou/TDDWithxUnitAndMOQ

TDD in ASP.NET MVC Applications with Moq Framework

https://kakimotonline.com/2011/02/13/tdd-in-asp-net-mvc-applications-with-moq-framework/

Unit Testing .NET Application with Moq Framework

https://kakimotonline.com/2011/01/02/unit-testing-net-application-with-moq-framework/

Test Driven Development in ASP.NET MVC 2

https://visualstudiomagazine.com/articles/2015/02/25/code-management-test-driven-dev.aspx

Test Driven Development in ASP.NET MVC 2

https://visualstudiomagazine.com/Articles/2015/05/14/Test-Driven-ASP-NET-MVC-2.aspx

TDD with .NET Core Web API

https://asp.net-hacker.rocks/2017/09/27/testing-aspnetcore.html

https://github.com/JuergenGutsch/blog/blob/master/_source/_posts/2017-09-27-testing-aspnetcore.md

 

 

ASP.NET MVC + Web API

May 21, 2018 17:54

ASP.NET MVC (edit)

https://github.com/chsakell/mvcarchitecture

ASP.NET Web API

https://github.com/chsakell/webapiunittesting

SPA + Web API

https://github.com/chsakell/spa-webapi-angularjs

ASP.NET MVC + AdminLTE

March 31, 2018 00:14

ASP.NET MVC + AdminLTE (edit)

ASP.NET MVC Application with a Custom Layout (Login screen)

https://code.msdn.microsoft.com/ASPNET-MVC-Application-b4b0dc3f

A NuGet package for integrating Admin LTE 2.0.4 into ASP.Net MVC 5

https://github.com/eralston/AdminLteMvc (AdminLTE version 2.0.4)

ASP.NET Example Version of Beautiful AdminLTE Template

https://github.com/go2ismail/AdminLTE-ASP-NET-MVC (AdminLTE version 2.4.0)

Tutorials & Samples on adding Charts into ASP.NET MVC Applications

https://canvasjs.com/docs/charts/integration/asp-net-mvc-charts/ (Chart)

CRUD Operations in ASP.NET MVC Using AJAX and Bootstrap

https://dzone.com/articles/crud-operation-in-aspnet-mvc-using-ajax-and-bootst

AdminLTE +  ASP.NET MVC 5 + Net Framework 4.8

https://github.com/DiomedesDominguez/AdminLTE.NET

ASP.NET MVC 5 Scaffolding

https://github.com/robinli/MVC5-Scaffolder

ASP.NET MVC 5 SmartCode Scaffolding (HAY HAY HAY)

https://github.com/neozhu/MVC5-Scaffolder

https://www.bbsmax.com/A/kvJ3LkNp5g/

http://www.matools.com/lang-en/blog/190137840

https://www.cnblogs.com/neozhu/p/8744414.html

https://blog.csdn.net/weixin_34235457/article/details/94016484

https://blog.csdn.net/sd7o95o/article/details/78519238

https://blog.csdn.net/weixin_34080951/article/details/94523127

ASP.NET MVC 5 Scaffolding

https://github.com/tzhsweet/MVC5-Scaffolder

ASP.NET Web API Attribute Routing

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing#controller-code

AdminLTE Template

https://github.com/weituotian/AdminLTE-With-Iframe (HAY HAY HAY)

https://github.com/tzhsweet/MVC5-Scaffolder (HAY HAY HAY) - Demo: http://longle.azurewebsites.net/

Demo: https://weituotian.oschina.io/adminlte-with-iframe/index2.html

Demo: https://weituotian.github.io/AdminLTE-With-Iframe/

Preview on github: https://weituotian.github.io/AdminLTE-With-Iframe/pages/index_iframe.html

Preview on oschina: http://weituotian.oschina.io/adminlte-with-iframe/pages/index_iframe.html

https://www.c-sharpcorner.com/article/dashboard-application-with-asp-net-mvc-5-and-jquery/ (HAY HAY HAY)

https://github.com/cyberzilla/dycms (HAY HAY HAY) - How can I implement Tab Pages in AdminLTE?

rrpuz7 x7rns4 9wly7m61z

https://www.quora.com/Where-can-I-find-free-ASP-NET-dashboard-templates (Where can I find free ASP.NET Dashboard templates?)

https://marketplace.visualstudio.com/items?itemName=c0shea.AdminLTETemplate (AdminLTE version 2.4.9)

https://marketplace.visualstudio.com/items?itemName=DiomedesIgnacioDominguezUrena.N-LayerAdminLTENET (AdminLTE version 2.4.9)

https://awesomeopensource.com/projects/adminlte (AdminLTE version 2.4.9)

http://hjnilsson.github.io/country-flags/ (Country flags)

https://vimeo.com/125426951 (IdentityManager with ASP.NET Identity)

https://github.com/eralston/AdminLteMvc/ (AdminLTE version 2.0.4)

https://www.youtube.com/watch?v=xnncfeFv108 (AdminLTE in ASP.NET Core MVC)

Good resources

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-1/

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-2/

https://www.jerriepelser.com/blog/5-weeks-of-aspnet-weekly-tools-and-libraries-part-3/

AdminLTE Downloads

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.10.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.9.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.5.zip

https://github.com/almasaeed2010/AdminLTE/archive/v2.4.0.zip (HAY)

AdminLTE Guide

https://adminlte.io/themes/AdminLTE/documentation/index.html

https://www.howtosolutions.net/2017/05/visual-studio-asp-net-mvc-project-installing-adminlte-control-panel/ (HAY)

AdminLTE + MVC 5
https://github.com/go2ismail/AdminLTE-ASP-NET-MVC
https://github.com/c0shea/AdminLTE-Template (HAY)
https://code.msdn.microsoft.com/ASPNET-MVC-Application-b4b0dc3f/
https://github.com/Magik3a/Multi-Language-API

Patient Management
https://github.com/Magik3a/PatientManagement_Admin

Design and Print Stickers

https://github.com/Magik3a/DesignAndPrintStickers
jQuery file upload, iTextSharp, Html Agility Pack, Cropper v2.3.3 - jQuery image cropping plugin

Easy Admin Dashboard with MVC
http://prabathsl.blogspot.com/2016/04/easy-admin-dashboard-with-mvc.html

Admin Dashboard
https://www.nuget.org/packages/Admin_Dashboard/
Install-Package Admin_Dashboard -Version 1.0.0

AdminLTE
https://github.com/almasaeed2010/AdminLTE

CMS MVC5
+ AdminLteMvc (https://github.com/eralston/AdminLteMvc)
+ Mvc CMS (https://github.com/jwmcpeak/Building-a-CMS-With-ASP.NET-MVC5)
+ Mr CMS (https://github.com/MrCMS/MrCMS)
+ MVCwCMS (https://github.com/valgen/mvcwcms)
+ Umbraco (https://github.com/umbraco/Umbraco-CMS)
+ sBlog.Net (https://github.com/karthik25/sblog.net)
+ N2CMS (https://github.com/n2cms/n2cms)
+ Better CMS
+ Piranha CMS (https://github.com/PiranhaCMS/Piranha)
+ BlogEngine.NET (https://github.com/rxtur/BlogEngine.NET)
+ Awesome (https://github.com/quozd/awesome-dotnet)

CMS MVC6
+ AdminLte .NET Core (https://github.com/moemura/AdminLTE.Core)
+ Awesome .NET Core (https://github.com/thangchung/awesome-dotnet-core)

Ecommerce MVC5
+ NopCommerce (https://github.com/nopSolutions/nopCommerce)

Ecommerce MVC6
+ SimplCommerce (https://github.com/simplcommerce/simplcommerce)

Scheduler
+ Quartznet (https://github.com/quartznet/quartznet)
+ FluentScheduler (https://github.com/fluentscheduler/FluentScheduler)
+ Hangfire (https://www.hangfire.io/)

Search
+ ElasticSearch (https://github.com/elastic/elasticsearch-net)

Templates
+ Boilerplate (https://github.com/ASP-NET-Core-Boilerplate/Templates)
+ MVC Bootstrap (https://github.com/steve-haar/MVC-Bootstrap)

Code review checklist

December 27, 2017 10:09

Code Review Checklist (edit)

https://www.guru99.com/asp-net-web-api-interview-questions.html

https://www.fullstack.cafe/blog/asp-net-web-api-interview-questions

AdminLTE.Core (HAY HAY HAY)

https://www.udemy.com/course/complete-aspnet-core-21-course/

Implementing CQRS Pattern with Vue.js & ASP.NET Core MVC

https://www.codeproject.com/Articles/5262285/Implementing-CQRS-Pattern-with-Vue-js-ASP-NET-Core

https://www.c-sharpcorner.com/article/implementing-cqrs-pattern-with-vue-js-asp-net-core-mvc/

Implementing CQRS Pattern with Vue.js & ASP.NET Core MVC

https://codeload.github.com/ColorlibHQ/AdminLTE/zip/v2.4.18 (HAY HAY HAY)

https://github.com/moemura/AdminLTE.Core (HAY HAY HAY)

https://github.com/moemura/AdminLTE.Core/releases/tag/2.0.1

https://github.com/dotnet-express/AdminLTE-Starter-Kit/releases

https://github.com/dotnet-express/AdminLTE-Starter-Kit/releases/tag/v0.8.0

https://github.com/go2ismail/adminlte-aspnetcore2-version

https://github.com/shehryarkn/Dynamic-User-Defined-Dashboards-Asp-Net-Core

https://github.com/shehryarkn/Asp-net-Core-Project-with-Admin-Template-Setup

Code Review

Checklist: https://www.michaelagreiler.com/code-review-checklist/

Google: https://blog.fullstory.com/what-we-learned-from-google-code-reviews-arent-just-for-catching-bugs/

Microsoft: https://www.michaelagreiler.com/code-reviews-at-microsoft-how-to-code-review-at-a-large-software-company/

Code Guide

https://www.cybersecuritycourses.com/course/dev544-secure-coding-in-net-developing-defensible-applications/ (HAY HAY HAY)

https://niccs.us-cert.gov/training/search/sans-institute/secure-coding-net-developing-defensible-applications (HAY HAY HAY)

Code Quality & Secure

1. Readability a.k.a. ‘Understandability’ (Khả năng đọc hoặc Khả năng hiểu được)
2. Maintainability (Bảo trì)
3. Security (Bảo mật)
4. Speed and Performance (Tốc độ và hiệu suất)
5. Documentation (Tài liệu)
6. Reinventing the Wheel (Phát minh lại bánh xe)
7. Reliability (Độ tin cậy)
8. Scalability (Khả năng mở rộng)
9. Reusability (Tái sử dụng)
10. Patterns (Mẫu)
11. Test Coverage and Test Quality (Phạm vi kiểm tra và chất lượng kiểm tra)
12. Fit for Purpose (Phù hợp cho mục đích)

https://www.enosecurity.com/training-tutorials-courses/secure-coding-in-asp-net-training/ (Tranining)

Audience / Target Group:

  • .NET Application Developers
  • C# Programmers
  • ASP.NET Developers
  • Managers, Architects and Technologists involved in deploying .NET applications

Topics: 

  • General Web Application Security Concepts
  • .NET Framework Security Features
  • Input Validation & Encoding
  • Input Driven Attacks
  • Validation Best Practices
  • Output Encoding
  • Common Authentication Weaknesses
  • Authorization Best Practices
  • Controlling Application Access
  • Password Security
  • Session Hijacking & Trapping
  • Protecting User Sessions & Tokens
  • Canonicalization Problems
  • Parameter Manipulation
  • Encryption, Confidentiality & Data Protection
  • Cookie-Based Attacks
  • Protecting Application Variables
  • Error Handling & Logging
  • Attacking via Error Messages
  • Secure Logging & Error Handling
  • Server Configuration & Code Management
  • Common App Server Misconfigurations
  • Protecting Application Code
  • XML Web Services
  • Overview of WSDL, SOAP & AJAX Security
  • Web Service Attacks
  • AJAX Pitfalls
  • Web Service Best Practices
  • Application Threat Modeling
  • Application Context
  • Identifying Attacks, Vulnerabilities & Countermeasures
  • Threat Modeling Tools
  • Cache Control Issues
  • SSL Best Practices

https://forums.asp.net/t/1926690.aspx?Secure+Coding+best+practices+guideline

https://download.microsoft.com/documents/uk/msdn/security/The Developer Highway Code.pdf

http://www.evoketechnologies.com/blog/code-review-checklist-perform-effective-code-reviews/

https://nyu-cds.github.io/effective-code-reviews/01-intro/

https://nyu-cds.github.io/effective-code-reviews/02-best-practices/

https://nyu-cds.github.io/effective-code-reviews/03-checklist/

Security Code Review

https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf

RESTful API Lifecycle Management

https://dzone.com/refcardz/restful-api-lifecycle-management

LINQ

https://msdn.microsoft.com/en-us/library/bb308959.aspx

Code Review Checklist & Guidelines for CSharp Developers

https://www.codeproject.com/Reference/593751/Code-Review-Checklist-and-Guidelines-for-Csharp-De

Code Review Guidelines

https://www.codeproject.com/Articles/524235/Codeplusreviewplusguidelines

Assign Severity to Review Finding

The severity to find issues with code should go as below. Reviewer must focus on issues with High severity first and then to Medium severity and then Low severity issues.

    1. Naming Conventions and Coding style = Low
    2. Control Structures and Logical issues = Medium or High
    3. Redundant Code = High
    4. Performance Issues = High
    5. Security Issues = High
    6. Scalability Issues = High
    7. Functional Issues =High
    8. Error Handling = High
    9. Reusability = Medium

https://weblogs.asp.net/tgraham/44763

In my previous blog post, we discussed about “10 Simple Code Review Tips for Effective Code Reviews”. Now, let’s take this topic further and explore the code review checklist, which would help to perform effective code reviews to deliver best quality software. 

This code review checklist also helps the code reviewers and software developers (during self code review) to gain expertise in the code review process, as these points are easy to remember and follow during the code review process. 

Let’s first begin with the basic code review checklist and later move on to the detailed code review checklist. 

Basic Code Review Checklist

Let’s discuss about the basic code review checklist, which can be very handy if you are a beginner in code reviews and/or during initial code reviews.

 

While reviewing the code, ask yourself the following basic questions:

  1. Am I able to understand the code easily?
  2. Is the code written following the coding standards/guidelines?
  3. Is the same code duplicated more than twice?
  4. Can I unit test / debug the code easily to find the root cause?
  5. Is this function or class too big? If yes, is the function or class having too many responsibilities?

If you feel that the answer is not satisfactory to any of the above questions, then you can suggest/recommend code changes.

Detailed Code Review Checklist

The following code review checklist gives an idea about the various aspects you need to consider while reviewing the code:

1. Code formatting

While going through the code, check the code formatting to improve readability and ensure that there are no blockers:

a) Use alignments (left margin), proper white space. Also ensure that code block starting point and ending point are easily identifiable.

b) Ensure that proper naming conventions (Pascal, CamelCase etc.) have been followed. 

c) Code should fit in the standard 14 inch laptop screen.  There shouldn’t be a need to scroll horizontally to view the code. In a 21 inch monitor, other windows (toolbox, properties etc.) can be opened while modifying code, so always write code keeping in view a 14 inch monitor.

d) Remove the commented code as this is always a blocker, while going through the code. Commented code can be obtained from Source Control (like SVN), if required.

2. Architecture

a) The code should follow the defined architecture.

  1. Separation of Concerns followed
    • Split into multiple layers and tiers as per requirements (Presentation, Business and Data layers).
    • Split into respective files (HTML, JavaScript and CSS).
  1. Code is in sync with existing code patterns/technologies.
  2. Design patterns: Use appropriate design pattern (if it helps), after completely understanding the problem and context.

3. Coding best practices

  1. No hard coding, use constants/configuration values.
  2. Group similar values under an enumeration (enum).
  3. Comments – Do not write comments for what you are doing, instead write comments on why you are doing. Specify about any hacks, workaround and temporary fixes. Additionally, mention pending tasks in your to-do comments, which can be tracked easily.
  4. Avoid multiple if/else blocks.
  5. Use framework features, wherever possible instead of writing custom code.

4. Non Functional requirements

a) Maintainability (Supportability) – The application should require the least amount of effort to support in near future. It should be easy to identify and fix a defect.

  1. Readability: Code should be self-explanatory. Get a feel of story reading, while going through the code. Use appropriate name for variables, functions and classes. If you are taking more time to understand the code, then either code needs refactoring or at least comments have to be written to make it clear.
  2. Testability: The code should be easy to test. Refactor into a separate function (if required). Use interfaces while talking to other layers, as interfaces can be mocked easily. Try to avoid static functions, singleton classes as these are not easily testable by mocks.
  3. Debuggability: Provide support to log the flow of control, parameter data and exception details to find the root cause easily. If you are using Log4Net like component then add support for database logging also, as querying the log table is easy.
  4. Configurability: Keep the configurable values in place (XML file, database table) so that no code changes are required, if the data is changed frequently.

b) Reusability

  1. DRY (Do not Repeat Yourself) principle: The same code should not be repeated more than twice.
  2. Consider reusable services, functions and components.
  3. Consider generic functions and classes.

c) Reliability – Exception handling and cleanup (dispose) resources.

d) Extensibility – Easy to add enhancements with minimal changes to the existing code. One component should be easily replaceable by a better component.

e) Security – Authentication, authorization, input data validation against security threats such as SQL injections and Cross Site Scripting (XSS), encrypting the sensitive data (passwords, credit card information etc.)

f) Performance

  1. Use a data type that best suits the needs such as StringBuilder, generic collection classes.
  2. Lazy loading, asynchronous and parallel processing.
  3. Caching and session/application data.

g) Scalability – Consider if it supports a large user base/data? Can this be deployed into web farms?

h) Usability – Put yourself in the shoes of a end-user and ascertain, if the user interface/API is easy to understand and use. If you are not convinced with the user interface design, then start discussing your ideas with the business analyst.

5. Object-Oriented Analysis and Design (OOAD) Principles

  1. Single Responsibility Principle (SRS): Do not place more than one responsibility into a single class or function, refactor into separate classes and functions.
  2. Open Closed Principle: While adding new functionality, existing code should not be modified. New functionality should be written in new classes and functions.
  3. Liskov substitutability principle: The child class should not change the behavior (meaning) of the parent class. The child class can be used as a substitute for a base class.
  4. Interface segregation: Do not create lengthy interfaces, instead split them into smaller interfaces based on the functionality. The interface should not contain any dependencies (parameters), which are not required for the expected functionality.
  5. Dependency Injection: Do not hardcode the dependencies, instead inject them.

In most cases the principles are interrelated, following one principle automatically satisfies other principles. For e.g: if the ‘Single Responsibility Principle’ is followed, then Reusability and Testability will automatically increase.

In a few cases, one requirement may contradict with other requirement. So need to trade-off based on the importance of the weight-age, e.g. Performance vs Security. Too many checks and logging at multiple layers (UI, Middle tier, Database) would decrease the performance of an application. But few applications, especially relating to finance and banking require multiple checks, audit logging etc. So it is ok to compromise a little on performance to provide enhanced security.

Tools for Code Reviews

  1. The first step while assessing the code quality of the entire project is through a static code analysis tool. Use the tools (based on technology) such as SonarQube, NDepend, FxCop, TFS code analysis rules. There is a myth that static code analysis tools are only for managers.
  2. Use plug-ins such as Resharper, which suggests the best practices in Visual studio.
  3. To track the code review comments use the tools like Crucible, Bitbucket and TFS code review process.

Conclusion

The above code review checklist is not exhaustive, but provides a direction to the code reviewer to conduct effective code reviews and deliver good quality code. Initially, it would take some time to review the code from various aspects. After a bit of practice, code reviewers can perform effective code reviews, without much effort and time. If you would like to become an expert code reviewer, this code review checklist serves as a great starting point. Happy Code Reviewing!

MVC

December 3, 2017 21:48

Best Practices (edit)

https://stackoverflow.com/questions/32641858/what-is-the-best-practice-for-enterprise-level-application-architecture-using-mv

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

https://code.msdn.microsoft.com/NET-best-practice-samples-4e9b92a4

 

I would start with PCI-DSS guidance as a baseline for protecting the data.

PCI-DSS is the Payment Card Industry Data Security Standard. It's the industries first attempt to lay down guidelines for protecting data around the banking area. The guidelines are specifically for cardholder data, but are a great resource for protection of data in general. PCI requirements include yearly onsite audits, and quarterly network scans.

Another good resource is OWASP which offers guidance on security of web applications in general

OWASP goes into a lot of detail about how to perform threat modelling, test for (and correct) common vulnerabilities. For the quick start head to the OWASP Top Ten

 

AllowHtml, DataAnnotation

https://www.c-sharpcorner.com/article/best-practices-for-asp-net-mvc-application/

Overview MVC 1,2,3,4,5 + @section scripts

https://www.c-sharpcorner.com/article/best-practice-for-mvc/

MVC Solution Architecture (source)

https://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/

Action Filter

https://www.danylkoweb.com/Blog/my-top-5-aspnet-mvc-actionfilters-AD

Unobtrusive Validation

https://stackoverflow.com/questions/14902581/unobtrusive-validation-not-working-with-dynamic-content/

https://stackoverflow.com/questions/28090143/best-practices-viewmodel-validation-in-asp-net-mvc

Data Annotation: Đa ngôn ngữ với Model Metadata

https://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/

Good Practices

http://www.codemag.com/article/1405071/10-Good-Practices-for-ASP.NET-MVC-Apps

https://www.codeguru.com/csharp/.net/net_asp/mvc/top-10-asp.net-mvc-best-practices.htm

Nerd Dinner

http://nerddinner.codeplex.com/

MVC Music Store

MVC Music Store is a tutorial application built on ASP.NET MVC. It's a lightweight sample store which demonstrates ASP.NET MVC using Entity Framework.

How to run MVC Music Store?

1) Download and install ASP.NET MVC 3 Tools from the official ASP.NET MVC 3 page or from Microsoft Download Center. It will install the required DLLS into the GAC.

2) Install the corresponding ASP.NET MVC 3 NuGet package into MvcMusicStore project using following command in the Package Manager Console:

Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1

or

Install-Package Microsoft.AspNet.Mvc -Version 3.0.20105.1

After using either of the described ways you will be able to successfully build and run the MVC Music Store tutorial application.

Note that these ways are not conflicting with each other, so you may safely install ASP.NET MVC 3 Tools into your OS and install ASP.NET MVC 3 NuGet package into the project.

C#

https://stackify.com/net-core-csharp-next-programming-language/

https://stackify.com/learn-c-sharp-tutorials/

MVC

https://www.danylkoweb.com/Blog/what-is-the-best-and-fastest-way-to-learn-aspnet-mvc-8V

https://weblogs.asp.net/jongalloway/learn-asp-net-mvc-3-with-the-mvc-music-store-tutorial 

https://mvcmusicstore.codeplex.com/

https://github.com/aspnet/MusicStore

https://github.com/nffish/MvcMusicStore

https://github.com/evilDave/MVC-Music-Store

Learn MVC in CodeProject

https://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

 

Categories

Recent posts