Programming Quotes
Software is not limited by physics, like buildings are. It is limited by imagination, by design, by organization. In short, it is limited by properties of people, not by properties of the world.
C# the maximum number lines of code?
Rule of 30 – When is a Method, Class or Subsystem Too Big?
https://dzone.com/articles/rule-30-%E2%80%93-when-method-class-or
- The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.
-
If an element consists of more than 30 subelements, it is highly probable that there is a serious problem:
- Methods should not have more than an average of 30 code lines (not counting line spaces and comments).
- A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.
- A package shouldn’t contain more than 30 classes, thus comprising up to 27,000 code lines.
- Subsystems with more than 30 packages should be avoided. Such a subsystem would count up to 900 classes with up to 810,000 lines of code.
- A system with 30 subsystems would thus possess 27,000 classes and 24.3 million code lines.
- Complexity metrics are highly correlated with lines of code, and therefore the more complex metrics provide no further information that could not be measured simplify with lines of code.
- Our goal is to keep our overall system small while we are also keeping our functions and classes small. Remember however that this rule is the lowest priority of the four rules of Simple Design. So, although it’s important to keep class and function count low, it’s more important to have tests, eliminate duplication, and express yourself.
SOLID Principles
SRP: Single Responsibility Principle, There Should Never Be More Than One Reason For A Class To Change
OCP: Open Closed Principle, Software Entities (Classes, Modules, Functions, Etc.) Should Be Open For Extension But Closed For Modification
LSP: Liskov Substitution Principle, Functions That Use ... References To Base Classes Must Be Able To Use Objects Of Derived Classes Without Knowing It.
ISP: Interface Segregation Principle, Clients Should Not Be Forced To Depend Upon Interfaces That They Do Not Use
DIP: Dependency Inversion Principle
- High Level Modules Should Not Depend Upon Low Level Modules. Both Should Depend Upon Abstractions
- Abstractions Should Not Depend Upon Details. Details Should Depend Upon Abstractions
https://blogs.msdn.microsoft.com/
Refactor code
Software Design principles and design pattern reading
- Martin Fowler
- Kent Beck
- Jeffrey Ritcher
- Ward Cunningham
- Scott Hanselman
- Scott Guthrie
- Donald E Knuth
5 Tips to Improve Performance of C# Code
- Choose your data type before using it:
- List<int> = new List<int>();
- int[] arr = new int[100]; //faster
- Use For loop instead of foreach
- Choose when to use a class and when to use a structure
- class
- structure //faster
- Always use StringBuilder for String concatenation operations
- string
- StringBuilder //faster
- Choose best way to assign class data member:
- public string Name {get; set;}
- public string Surname; //faster
Lỗi thường gặp trong code của Developer
- Wrong sizing of available worker threads
- Loading too much data from database
- Excessive use of Database Connections
- Expensive String Concats instead of StringBuilder Usage
- High Memory Usage due to bad SQL Patterns and String Concats
Question – which of these two is faster?
for (int i = 0; i < _map.Length; i++)
{
for (int n = 0; n < _map.Length; n++)
{
if (_map[i][n] > 0)
{
result++;
}
}
}
for (int i = 0; i < _map.Length; i++)
{
for (int n = 0; n < _map.Length; n++)
{
if (_map[n][i] > 0)
{
result++;
}
}
}
Lỗi ở đâu?
DateTime? tmp = new DateTime();
tmp = null;
Console.WriteLine(tmp.ToString());
int? i = new int();
i = null;
Console.WriteLine(i.ToString());
object o = new object();
o = null;
Console.WriteLine(o.ToString());
Calculate Age of somebody
// Save today's date.
var today = DateTime.Today;
// My birthday
var birthdate = new DateTime(1983, 6, 25);
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate > today.AddYears(-age)) age--;
Console.WriteLine(age);
Hidden C# Features:
Keywords
- yield by Michael Stum
- var by Michael Stum
- using() statement by kokos
- readonly by kokos
- as by Mike Stone
- as / is by Ed Swangren
- as / is (improved) by Rocketpants
- default by deathofrats
- global:: by pzycoman
- using() blocks by AlexCuse
- volatile by Jakub Šturc
- extern alias by Jakub Šturc
Attributes
- DefaultValueAttribute by Michael Stum
- ObsoleteAttribute by DannySmurf
- DebuggerDisplayAttribute by Stu
- DebuggerBrowsable and DebuggerStepThrough by bdukes
- ThreadStaticAttribute by marxidad
- FlagsAttribute by Martin Clarke
- ConditionalAttribute by AndrewBurns
Syntax
- ?? (coalesce nulls) operator by kokos
- Number flaggings by Nick Berardi
- where T:new by Lars Mæhlum
- Implicit generics by Keith
- One-parameter lambdas by Keith
- Auto properties by Keith
- Namespace aliases by Keith
- Verbatim string literals with @ by Patrick
- enum values by lfoust
- @variablenames by marxidad
- event operators by marxidad
- Format string brackets by Portman
- Property accessor accessibility modifiers by xanadont
- Conditional (ternary) operator (?:) by JasonS
- checked and unchecked operators by Binoj Antony
- implicit and explicit operators by Flory
Language Features
- Nullable types by Brad Barker
- Anonymous types by Keith
- __makeref __reftype __refvalue by Judah Himango
- Object initializers by lomaxx
- Format strings by David in Dakota
- Extension Methods by marxidad
- partial methods by Jon Erickson
- Preprocessor directives by John Asbeck
- DEBUG pre-processor directive by Robert Durgin
- Operator overloading by SefBkn
- Type inferrence by chakrit
- Boolean operators taken to next level by Rob Gough
- Pass value-type variable as interface without boxing by Roman Boiko
- Programmatically determine declared variable type by Roman Boiko
- Static Constructors by Chris
- Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid
- __arglist by Zac Bowling
Visual Studio Features
- Select block of text in editor by Himadri
- Snippets by DannySmurf
Framework
- TransactionScope by KiwiBastard
- DependantTransaction by KiwiBastard
- Nullable<T> by IainMH
- Mutex by Diago
- System.IO.Path by ageektrapped
- WeakReference by Juan Manuel
Methods and Properties
- String.IsNullOrEmpty() method by KiwiBastard
- List.ForEach() method by KiwiBastard
- BeginInvoke(), EndInvoke() methods by Will Dean
- Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo
- GetValueOrDefault method by John Sheehan
Tips & Tricks
- Nice method for event handlers by Andreas H.R. Nilsson
- Uppercase comparisons by John
- Access anonymous types without reflection by dp
- A quick way to lazily instantiate collection properties by Will
- JavaScript-like anonymous inline-functions by roosteronacid
Other
- netmodules by kokos
- LINQBridge by Duncan Smart
- Parallel Extensions by Joel Coehoorn
C# versions:
These are the versions of C# known about at the time of this writing:
- C# 1.0 released with .NET 1.0 and VS2002 (January 2002)
- C# 1.2 (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.
- C# 2.0 released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks
- C# 3.0 released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions
- C# 4.0 released with .NET 4 and VS2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters
- C# 5.0 released with .NET 4.5 and VS2012 (August 2012). Major features: async programming, caller info attributes. Breaking change: loop variable closure.
- C# 6.0 released with .NET 4.6 and VS2015 (July 2015). Implemented by Roslyn. Features: initializers for automatically implemented properties, using directives to import static members, exception filters, indexed members and element initializers, await in catch and finally, extension Add methods in collection initializers.
- C# 7.0 released with .NET 4.7 and VS2017 (March 2017) Major new features: tuples, ref locals and ref return, pattern matching (including pattern-based switch statements), inline outparameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.
- C# 7.1 released with VS2017 v15.3 (August 2017) Minor new features: async main, tuple member name inference, default expression, pattern matching with generics.
- C# 7.2 released with VS2017 v15.5 (November 2017) Minor new features: private protected access modifier, Span<T>, aka interior pointer, aka stackonly struct, everything else.
There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports 4.0.xxx.
More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site. This includes information about which features of C# 3.0 you can use when targeting .NET 2.0. (If anyone wants to bring all of the content into this wiki answer, they're welcome to.)
As of May 3, 2017, the C# Language Team created a history of C# versions and features on their github repo: Features Added in C# Language Versions
Redundant Code = High (mã dư thừa)
ReSharper: Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
ReSharper: Find dead .NET code
NDepend: can help to find unused methods, fields and types.
NCover: can help to find Code Coverage.
TestDriven.NET: I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit "Test With -> Coverage", and it will pull up the report.
Performance Issues = High
What is the best way to debug performance problems?
+ DebugView: You can also write messages in control points using Debug.Write. Then you need to load DebugView application that displays all your debug string with precise time stamp. It is freeware and very good for quick debugging and profiling.
https://docs.microsoft.com/en-us/sysinternals/downloads/debugview
+ Redgate ANTS Performance Profiler: Boost the performance of your applications with .NET profiling
https://www.red-gate.com/products/dotnet-development/ants-performance-profiler/
+ Active Directory: Performance Issue - Adding / Removing users from large Active Directory groups in .net
https://stackoverflow.com/questions/43585029/performance-issue-adding-removing-users-from-large-active-directory-groups-i
+ Async: Async and LINQ are powerful, but should be used together as carefully and clearly as possible.
https://docs.microsoft.com/en-us/dotnet/csharp/async
https://docs.microsoft.com/en-us/dotnet/standard/async-in-depth
https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async
+ Other: dotTrace, and AQtime
+ Google: http://www.google.com.au/search?hl=en&q=site:stackoverflow.com+.net+profiler&btnG=Google+Search&meta=&aq=f&oq=
https://blogs.msdn.microsoft.com/ricom/2005/05/23/how-to-do-a-good-performance-investigation/
+ The tool I reach for first is PerfMon (Resource and Performance Monitor). Look at key counters like CPU Usage, Memory Usage, Disk and Network I/O.
https://technet.microsoft.com/en-us/library/cc749115(v=ws.11).aspx
http://www.thewindowsclub.com/how-to-use-perfmon-performance-monitor-windows
http://www.thewindowsclub.com/use-resource-monitor-windows-10
Generate System Health Report using Perfmon: http://www.thewindowsclub.com/generate-system-health-report-windows-7-8-perfmon
Troubleshoot performance issues in Windows 10/8/7: http://www.thewindowsclub.com/troubleshoot-performance-issues-windows-7
+ The other tools are: Windows Reliability Monitor, System File Checker
+ For SQL problems there’s of course SQL Profiler (find the key queries) and Query Analyzer (view the plans).
https://blogs.msdn.microsoft.com/
Martin Fowler, Kent Beck, Jeffrey Ritcher, Ward Cunningham, Scott Hanselman, Scott Guthrie, Donald E Knuth.
https://blogs.msdn.microsoft.com/jmeier/2010/10/31/asp-net-code-samples-collection/
Security Issues = High
Scalability Issues= High
Functional Issues = High
Error Handling = High
OOP in JavaScript and TypeScript
http://rachelappel.com/write-object-oriented-javascript-with-typescript/
30 year sorting algorithm
http://rachelappel.com/a-30-year-sorting-algorithm-saga-from-250k-to-14gb-in-one-minute/
WinForm Animation Effect
https://www.codeproject.com/Articles/12597/OSD-window-with-animation-effect-in-C
Data binding concepts in .NET windows forms
https://www.codeproject.com/Articles/3665/Data-binding-concepts-in-NET-windows-forms
Windows Forms: Binding through ITypedList interface
https://www.codeproject.com/Articles/575856/Windows-Forms-Binding-through-ITypedList-interface
TreeView
https://www.codeproject.com/Articles/7884/Data-Binding-TreeView-in-C
https://www.codeproject.com/Articles/11927/DataBound-TreeView
https://www.codeproject.com/Articles/9241/DataBound-TreeView-Control
http://www.vcskicks.com/treeview-state.php
DataGrid: How to build ComboBox, DateTimePicker and Button as User Controls for DataGridColumns for WinForms.
https://www.codeproject.com/Articles/8909/Windows-DataGridColumns-User-Controls
Generic class + Unit Test using Repository & Unit Of Work
https://www.codeproject.com/Articles/1056821/Generic-Multi-Purpose-NET-Layered-Framework
https://www.codeproject.com/Articles/601307/Generic-Database-Access
PDF & iTextSharp
https://www.codeproject.com/Tips/679606/Filling-PDF-Form-using-iText-PDF-Library
https://www.codeproject.com/Articles/23112/Fill-in-PDF-Form-Fields-using-the-Open-Source-iTex
Multiple language instantly in WinForm
https://www.codeproject.com/Articles/8980/Instantly-Changing-Language-in-the-Form
WinForm: A tool for acessing CodeProject and have instant notifications of Codeproject's posts
https://www.codeproject.com/Articles/3027/Desktop-Bob-Instant-CP-notifications
Reflection
https://www.codeproject.com/Articles/503527/Reflection-optimization-techniques
https://www.codeproject.com/Articles/858510/Reflection-with-Example
Optimizing Serialization
https://www.codeproject.com/Articles/15700/Optimizing-Serialization-in-NET
https://www.codeproject.com/Articles/16017/Optimizing-Serialization-in-NET-part
Code-First
https://www.codeproject.com/Articles/826571/Code-First-Approach-with-ASP-NET-MVC-Framework
C# Advanced
Lecture Notes Part 1 of 4 - An advanced introduction to C#
https://www.codeproject.com/Articles/1094079/An-advanced-introduction-to-Csharp-Lecture-Notes-P
Lecture Notes Part 2 of 4 - Mastering C#
https://www.codeproject.com/Articles/1094359/Mastering-Csharp-Lecture-Notes-Part-of
Lecture Notes Part 3 of 4 - Advanced programming with C#
https://www.codeproject.com/Articles/1094625/Advanced-programming-with-Csharp-Lecture-Notes-Par
Lecture Notes Part 4 of 4 - Professional techniques for C#
https://www.codeproject.com/Articles/1094829/Professional-techniques-for-Csharp-Lecture-Notes-P
Utility: Speed Tester
http://www.vcskicks.com/code_speed_test.php
C# Application Programming (HAY HAY HAY)
http://www.vcskicks.com/csharp-programming.php
Desktop GIS Application: Menus & Icons
https://www.codeproject.com/Articles/82449/Build-a-Desktop-GIS-Application-Using-MapWinGIS
A one-line program to count lines of code (đếm số dòng code trong tất cả các files)
https://blogs.msdn.microsoft.com/kirillosenkov/2008/11/30/a-one-line-program-to-count-lines-of-code/
Why would you use a finally block in an iterator?
http://csharpindepth.com/ViewNote.aspx?NoteID=113
Difference between function and method?
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
A method is implicitly passed the object on which it was called.
A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
Chapter 1: What is Software Architecture?
https://msdn.microsoft.com/en-us/library/ee658098.aspx
Chapter 2: Key Principles of Software Architecture
https://msdn.microsoft.com/en-us/library/ee658124.aspx
Chapter 3: Architectural Patterns and Styles
https://msdn.microsoft.com/en-us/library/ee658117.aspx
Chapter 4: A Technique for Architecture and Design
https://msdn.microsoft.com/en-us/library/ee658084.aspx
LINQ
https://www.codeproject.com/Articles/33769/Basics-of-LINQ-Lamda-Expressions
https://www.codeproject.com/Articles/235860/Expression-Tree-Basics
https://www.codeproject.com/Articles/17575/Lambda-Expressions-and-Expression-Trees-An-Introdu
https://www.codeproject.com/Articles/24255/Exploring-Lambda-Expression-in-C
https://www.codeproject.com/Tips/298963/Understand-Lambda-Expressions-in-Minutes
- LINQ to Entities
- LINQ to SQL
- LINQ to Objects
- LINQ to DataSet
- LINQ to XML