- In C# we have 5 access modifiers:
- Public
- Private
- Protected
- Internal
- Protected Internal
- A class member declared with public is accessible everywhere.
- A class member declared with private is accessible only from inside the class.
- A class member declared with protected is accessible for containing class and the derived types of the containing class.
- A class member declared with internal is accessible only for current assembly.
- A class member declared with protected internal is accessible for current assembly and derived types of the containing class.
Tuesday, August 25, 2020
Access Modifiers
Monday, August 24, 2020
Properties
- A property is a class member that encapsulate a getter/setter for accessing a filed.
- As a best practice, we must declare fields as private and create public properties to provide access to them.
- A property encapsulates a get and a set method.
public class Customer
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public class Person
{
public DateTime BirthDate { get; set; }
public int Age
{
get
{
var timespan = DateTime.Today - BirthDate;
var years = timespan.Days / 365;
return years;
}
}
}
public class Person
{
public DateTime BirthDate { get; set; }
}
public class Person
{
public DateTime BirthDate { get; private set; }
}
Friday, August 21, 2020
Read only and Constants Fields
Readonly
- When a field is declared with readonly, it needs to be initialized either during declaration or in a constructor.
public class Const_V_Readonly
{
public readonly int Readonly_Value;
public Const_V_Readonly()
{
Readonly_Value = 3;
}
}
public class Const_V_Readonly
{
public static readonly int Readonly_Value;
//Access modifiers are not allowed on static constructors
static Const_V_Readonly()
{
Readonly_Value = 3;
}
}- If consider "Const_V_Readonly" class in AssemblyA , AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled, readonly values are like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if "Readonly_Value" is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.
- So if you have a constant that may change or when in doubt, use a readonly.
Constants
- A const keyword is used to declare constant fields and constant local.
- The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed.
public class Const_V_Readonly { public const int Constant_Value = 2; }
- The constant field should be initialized on the declaration. (Can not intialize it in a constructor or method)
- If consider "Const_V_Readonly" class in AssemblyA and AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled, const value is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if we update Constant_Value to 20 in the future. AssemblyB would still have 2 till we recompile it.
- So if you are confident that the value of the constant won't change use a const.
Wednesday, August 19, 2020
Constructors
- Constructor is a method that is called when an instance of a class is created.
- Usage of a constructor is to put an object in an early state (To initialize some of the class fields in a class).
- Constructor can be declared as below.
public class Customer { //Default Constructorpublic Customer() { } } - If we don't define a default constructor or parameterless constructor, C# compiler automatically will create it when an instance of a class is created.
public class Customer { public bool IsMarried; public string Age; } class Program { static void Main(string[] args) { var customer = new Customer(); Console.WriteLine(customer.IsMarried); Console.WriteLine(customer.Age); Console.Read(); } } Output False 0
- We can also define a constructor with one or more parameter which is called parameter constructor.
public class Customer {public string Name;//Parameter Constructorpublic Customer(string name) { this.Name = name; } } - Constructors can be overloaded. Overloading means creating a method with the same name and different signatures. Signature is what uniquely identify a method. That includes return type, name, parameter type , no of input parameters and order of the parameters.
public class Customer {public Customer(){} public Customer(string name){} public Customer(string name, int Age){} }
- As a best practice, when we have a list of objects inside a class, always the list should be initialized in the constructor or on the declaration. Otherwise it will give an exception.
public class Order { } public class Customer { public string Name; public int Age; public List<Orders>; public Customer() { } public Customer(string name) { this.Name = name; } public Customer(string name, int age) { this.Name = name; this.Age = age; } } class Program { static void Main(string[] args) { var customer = new Customer(); var order = new Order(); customer.orders.Add(order); Console.Read(); } } - So we should initialize the list of order inside the constructor. But the problem is, when we use other parameter constructors , list will be set to null again. To overcome this, We can pass control from one constructor to the other by using the this keyword.
public class Customer { public string Name; public int Age; public Listorders; public Customer() { orders = new List (); } public Customer(string name) :this() { this.Name = name; } public Customer(string name, int age) : this(name) { this.Name = name; this.Age = age; } }
- But still this way is little ugly and hard to maintain. So you should only define a constructor when you really have to initialize some fields and etc.
Constructors Inheritance
- When creating an object of a type that is part of an inheritance hierarchy, base class constructors are always executed first. They are not inherited to the derived class and need to define explicitly.
public class Vehicle { public Vehicle() { Console.WriteLine("Vehicle is being initialized.."); } } public class Car : Vehicle { public Car() { Console.WriteLine("Car is being initialized.."); } } public class Program { static void Main(string[] args) { var obj = new Car(); Console.Read(); } }OutPutVehicle is being initialized..Car is being initialized..
public class Vehicle
{
private readonly string _registrationNumber;
public Vehicle(string registrationNumber)
{
this._registrationNumber = registrationNumber;
Console.WriteLine("Vahicle is being initialized.. Registration No : " + registrationNumber);
}
}
public class Car : Vehicle
{
public Car(string registrationNumber) :base(registrationNumber)
{
Console.WriteLine("Car is being initialized.. Registration No : "+ registrationNumber);
}
}
public class Program
{
static void Main(string[] args)
{
var obj = new Car("CAS-5276");
Console.Read();
}
}
OutPut
Vahicle is being initialized.. Registration No : CAS-5276
Car is being initialized.. Registration No : CAS-5276
Saturday, August 15, 2020
Classes and Objects in C#
Classes
A building block of an application.
Anatomy of a class is,
1. Data (Represented by fields)
2. Behavior (Represented by methods/functions)
Declaring a class
Class Members
1. Instance - Accessible from an object
var person = new Person();
person.Introduce();
2. Static - Accessible from the class
Console.WriteLine(); // Console is the class and WriteLine is a static method.
No need to create a object of Console class by using new operator in order to call WriteLine method.
Objects
Object is a blue print of a class. Also called an instance of a class. It has an identity, attributes and behavior.
Creating an Object
To create objects, we use "new" operator. By using objects, we can access class fields and methods.
Thursday, June 25, 2020
How to fix for Fortify issue Open Redirect and Cross-Site Scripting: Poor Validation (URL_ENCODE)
Below are sample fixes for Fortify issue:
• Open Redirect
• Cross-Site Scripting: Poor Validation (URL_ENCODE)
Replace “Sink: Assignment to window.location”:
window.location = theUrl;
with:
var redirectUrl = window.urlUtil.getRedirectUrl(theUrl);
if (redirectUrl) {
window.location = redirectUrl;
}
Add DOMPurify to _Layout.cshtml:
<script src="~/lib/dompurify/purify.min.js"></script>
Initialise trusted sites in e.g. _Layout.cshtml or site.js:
<script>
"use strict";
window.app.addTrustedSite('https://www.google.com');
window.app.addTrustedSite('https://www.microsoft.com');
</script>
Add below js to a file e.g. site.js
"use strict";
(function () {
var appService = {
getPublicOrigin: getPublicOrigin,
setPublicOrigin: setPublicOrigin,
getTrustedSites: getTrustedSites,
addTrustedSite: addTrustedSite,
};
window.app = appService;
var publicOrigin = '/';
var trustedSites = [];
function getPublicOrigin() {
return publicOrigin;
}
function setPublicOrigin(value) {
publicOrigin = value;
}
function getTrustedSites() {
return trustedSites;
}
function addTrustedSite(value) {
if (value) {
trustedSites.push(value);
}
}
})();
(function () {
var urlService = {
getRedirectUrl: getRedirectUrl,
isRelative: isRelative,
isWhitelisted: isWhitelisted,
};
window.urlUtil = urlService;
function getRedirectUrl(url) {
if (isRelative(url))
return DOMPurify.sanitize(url);
if (isWhitelisted(url))
return DOMPurify.sanitize(url);
return null;
}
function isRelative(url) {
return url && url.match(/^\/[^\/\\]/);
}
function isWhitelisted(url) {
url = url.toLowerCase();
var whitelist = window.app.getTrustedSites();
var i = whitelist.length;
while (i--) {
if (url.startsWith(whitelist[i])) {
return true;
}
}
return false;
}
})();
Tuesday, June 23, 2020
Validate the Hostname or Domain Name
JS files
1. Add below method to get exact host name.
function extractHostname(url) {var host = new URL(url).hostname;
return host;}
2. Use above method in the issue finding.
var domain = 'localhost'; //add exact domain name or IP address
var loginUrl = 'define the login Url here';
var currentUrl = $(location).attr("href");
var host = extractHostname(currentUrl);if (host === domain)
{
$(location).attr("href", loginUrl + "?returnurl=" + currentUrl );
}
$(location).attr("href", loginUrl + "?returnurl=" + currentUrl );
}
else
{
alert("Invalid Return URL");
}
.CS file
private bool IsLocalUrl(string url)
{
if (string.IsNullOrEmpty(url))
{
return false;
}
else
{
return ((url[0] == '/' && (url.Length == 1 ||
(url[1] != '/' && url[1] != '\\'))) ||
(url.Length > 1 &&
url[0] == '~' && url[1] == '/'));
}
}
if (IsLocalUrl(strRedirectUrl))
{
returnUrl = strRedirectUrl
}
Subscribe to:
Posts (Atom)