Please enable JavaScript.
Coggle requires JavaScript to display documents.
C# and .NET MVC and Web API (C# Programming Language (Class (Class with 2…
C# and .NET MVC and Web API
C# Programming Language
Variables
string name ="John";
const myNum = 15;
bool isGood = true;
Some data types:
long x = 11003L;
float y = 123.45F;
double z = 19.29D;
Scientific numbers( e = pow(10)):
float x = 12e3F;
Type casting
implicit casting(automatically):
char -> int -> long -> float ....
Explicit casting(manual):
double -> float -> long ...
int myInt = (int) myDouble;
Type conversion:
double myDouble = 5.25;
Console.WriteLine(Convert.ToInt32(myDouble));
dynamic types: Only check type at run-time:
dynamic x = 1;
object y = 2;
Input variable:
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
String interpolation/concatenation:
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
String with special characters:
string txt = "We are \"Vikings\" from the north.";
Function/method
Method with default params:
//default params at the end of params' list
static int MyMethod(int y, int x = 0) {...}
Named Arguments:
Every functions can support "named/labelled arguments"
MyMethod(x: 10, y: 20);
Method with dynamic type:
void PrintValue(dynamic x) {...}...
PrintValue(true);//ok
PrintValue(100);//ok
2 more items...
struct, contains many properties:
struct Employee {
public string FirstName;
public string LastName;
}
Parameterized Constructor:
public Employee(string firstName, string lastName){
FirstName = firstName;
LastName = lastName;
}
Create struct object:
Employee emp = new Employee("Bill", "Gates");
Class
Class with 2 fields:
class Car {
string color = "red";//private
int maxSpeed = 200;
}
Getter+setter = properties:
public string Name {
get { return name; }
set {name = value;}
}
Properties are "public"
Automatic properties(short-hand):
class Person {
public String Name {get; set;}
}
Inheritance:
class Car:Vehicle {
}
Cannot inherit a "sealed" class:
public sealed class Vehicle {...Error !
Override a method:
class Dog: Animal {
public override void makeSound(){...}
}
Thread and multi-thread
1 more item...
Write Test cases
1 more item...
Interface: contains method or property:
interface IPen {
string Color { get; set; }
void Write(string text);//no implementation
}
struct like "class", but:
structA = structB; //clone an object structA from structB
Objects
Initialize/create an anonymous type:
var person = new {
name = "Hoang", age = 30,
passport = new {id = 123},
};
//key - value object
Create an object:
var studentA = new Student() {
StudentID = 1, StudentName = "John", age = 18 };
List
Create a list of objects:
ArrayList<Person> persons = new ArrayList<Person>() {
new Person(),...
}
Number of item in list = Count = Length:
Console.WriteLine(persons.Count);
LINQ = Language Integrated Query
var result = from person in persons
where person.email ==
"hoang@gmail.com
" && person.Age == 30;
Select some properties:
var result = from person in persons
where person.Price == 200
select person.Name, person.Price;
select as "alias":
select new {
ten = person.Name,
gia = person.Price
}
linq query/select in db:
var query = from p in dbContext.Products
where p.productName=="iphone x"
select p;
var list = query.ToList();
Sort data in Linq:
...where...
order by p.productName ascending
select p;
"groups by" in Linq:
var query = from p in dbContext.Products
groups by p.Category
Join table in Linq:
var query= from c in categories
join p in products
on c.id equals p.categoryId
where ...select...
var list = query.ToList();
MVC = Model - View - Controller
ASP.NET MVC
Open App_Start/RouteConfig.cs to configure Route
...routes.MapConfig();
3 parameters: controller, action, id
Models
contains:
Entity classes, Database class,
Initializer class
Property's validations
Each property has some DataAnnotations
Default Validations
[Required] //=> Not null
[StringLength(200)]
[DisplayName("Ảnh nè")], //not property's name
public String ProductName {get; set;}
Property can be "file's content":
public byte[] PhotoFile { get; set; }
Custom Validations
Validation name = your class's name,
must inherits ValidationAttribute
public class CheckValidYear : ValidationAttribute
...
public override bool IsValid(object value) {...}
1 more item...
In Models package:
public class MyDBInitializer: DropCreateDatabaseAlways<MyDatabase>
override void Seed(OperasDB context) {
context.Operas.Add("an object");
context.SaveChanges();
}
Call initializer in Global.asax:
Database.SetInitializer<MyDatabase>(new MyDBInitializer());
Data is loaded from Database
Install Entity Framework
Add connectionStrings in web.config
public class MyDatabase: DbContext {...}
n tables => n DataSet property, eg:
public DbSet<Opera> Operas { get; set; }
Find Object by ID:
contextDB.Operas.Find(id)
Controllers
Contains many actions:
"Action" = public method which returns ActionResult type, FileContentResult
ActionResult type
return HttpNotFound() => 404 Error
check validation:
if(ModelState.IsValid) {...}
public ActionType methodA(){
//Show view and send params to view:
return View("action name", "params, model,..");
//file view : /Views/ControllerA/methodA.cshtml
}
Redirect to action(after finish result):
return RedirectToAction("Index");
Action Filter:
Request from Client => ActionFilter => Action
=> ActionFilter
public class MyFilter: ActionFilterAttribute {
override void OnActionExecuting(...) {
//router' infor here: filterContext.RouteData
}
}
1 Filter => n Controllers
[MyFilter]
public class MyController : Controller {...}
Views
Receive params, model from Controller
View receives model(eg: Product, Student,...)
Example:/Views/Opera/Create.cshtml
One model object
model
OperasWebsites.Models.Opera
List of model objects:
model
IEnumerable<OperasWebsites.Models.Opera>
Html Helpers : Functions => html tags
form method="Post" action=/Opera/Create.cshtml:
using
(Html.BeginForm("Create", "Opera", FormMethod.Post)){...}
<label>abc</label>
Html.LabelFor(model
=> model.Title)
<span>abc123</span>
Html.ValidationMessageFor(model
=> model.Year)
<a href="/Index">Back to List</a>
Html.ActionLink("Back
to List", "Index")
<a href="/Opera/Details/11">Chi tiet</a>
Html.ActionLink("Chi
tiet", "Details", new {id = 11})
1 more item...
<input type="text" value="xyz"/>
Html.EditorFor(model
=> model.Title)
View receives key-value object:
ViewData, ViewBag objects
Winform
DataGridView with DataSet
DataSet:
SqlConnection connection = "create here";
using SqlCommand command = new SqlCommand("SELECT * FROM ...", connection);
connection.Open();
command.CommandType = CommandType.Text;
command.Parameters.Add("@deparmentId
", departmentId);
using SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(command);
using DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet);
Fetch DataSet to DataGridView:
dataGridView.AutoGenerateColumns = false; //true
dataGridView.ColumnCount = 4;
dataGridView.Columns[0].Name = "TenLop";
dataGridView.Columns[0].HeaderText = "Ten lop";
dataGridView.Columns[0].DataPropertyName = "TenLop";
//Column[1], Column[2], Column[3]
dataGridView.DataSource = dataSet.Tables[0];
Connect SQL Database
string queryString = "SELECT * FROM Departments;";
SqlConnection sqlConnection = new SqlConnection(Database.CONNECTION_STRING);
SqlCommand sqlCommand = new SqlCommand(queryString, sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {....reader[0], reader[1]}
Basic toolboxes
ComboBox
comboBoxDepartment.DataSource = "list objects";
comboBoxDepartment.DisplayMember = "DeparmentName";
ListView
listView.View = View.Details;
listView.Columns.Add("ColumnA", -2);//autosize
ListViewItem listViewItem = new ListV....
listViewItem.Tag = objectA;
listView.Items.Add(listViewItem)
selectedListViewItem = listView.SelectedItems[0]