Wednesday, July 22, 2020
5:45 AM
__________________________________________
Design Patterns & focus in Singleton
__________________________________________
Patterns are about reusable designs and
interactions of objects. They are solutions for recurring problems in a given
context.
The 23 Gang of Four (GoF) patterns are
generally considered the foundation for all other patterns.
The most important part of applying patterns
to your codebase is knowing when and where to apply each pattern.
Creational Patterns ABFPS (Abraham
Became First President of States).(Republican 😊) |
|
Creates an instance of several families of
classes |
|
Separates object construction from its
representation |
|
Creates an instance of several derived
classes |
|
A fully initialized instance to be copied or
cloned |
|
A class of which only a single instance can
exist |
Structural Patterns (ABCDFFP) |
|
Match interfaces of different classes |
|
Separates an object’s interface from its
implementation |
|
A tree structure of simple and composite
objects |
|
Add responsibilities to objects dynamically |
|
A single class that represents an entire
subsystem |
|
A fine-grained instance used for efficient
sharing |
|
An object representing another object |
Behavioral Patterns 2 MICS On TV
(MMIICCSSOTV). |
|
A way of passing a request between a chain
of objects |
|
Encapsulate a command request as an object |
|
A way to include language elements in a
program |
|
Sequentially access the elements of a
collection |
|
Defines simplified communication between classes |
|
Capture and restore an object's internal
state |
|
A way of notifying change to a number of
classes |
|
Alter an object's behavior when its state
changes |
|
Encapsulates an algorithm inside a class |
|
Defer the exact steps of an algorithm to a
subclass |
|
Defines a new operation to a class without
change |
C# Singleton Design Patterns
Where context requires a project calls for
only one instance of Object be created and shared between clients, and the
client cannot create an instance from outside.
Class of which only a single instance can
exist.
Creation:
· Private Constructor
· Static Instances and methods
With .NET 4 +use the System.Lazy<T> type to make the laziness really simple. Simply pass a delegate to the constructor, that calls the Singleton constructor (done easily with a lambda expression)
using System; public sealed class Singleton { //initialize the instance private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { Logger.Log("Instance called."); return _lazy.Value; } } private Singleton() { // cannot be created except within this class Logger.Log("Constructor invoked."); } }
|
C# Fundamentals
_____________________________________________________________
Dependency
Injection
______________________________________________________________
ASP.NET Core supports
the dependency injection (DI) software design pattern, which is a technique for
achieving Inversion of Control (IoC) between classes and their dependencies.
In software engineering,
dependency injection is a technique in which an object receives other objects
that it depends on. These other objects are called dependencies. In the typical
"using" relationship the receiving object is called a client and the
passed (that is, "injected") object is called a service
Dependency
Inversion and Dependency Injection
Dependency Inversion is
one of the core software design principles which we use to create modules that
are loosely coupled. While creating applications, we can achieve this using a
technique called Dependency Injection. Dependency Injection (DI) is the method
of injecting the dependent modules into our classes.
We have discussed this
in detail in one of our other article Dependency Inversion Principle. There, we
discussed the concept of Dependency Injection and how to implement it.
So, in this section, we
are going to look at the support for Dependency Injection in an ASP.NET Core
MVC application.
Injecting
Dependencies into Controllers
ASP.NET Core supports
Dependency Injection(DI) between classes and their dependencies. MVC
Controllers request dependencies explicitly via constructors. Furthermore,
ASP.NET Core has built-in support for dependency injection, hence making the
application easier to test and maintain.
We add services as a
constructor parameter and the runtime resolves the service from the service
container. We typically define services using interfaces.
When we implement a
repository pattern in the ASP.NET Core MVC application, we make use of
Dependency Injection in our controllers. We have explained how to implement a
simple data repository in the article section Implementing a simple data
repository.
Let’s create an ASP.NET
Core MVC application and implement a simple data repository as described in the
article.
First of all, let’s
create an interface IDataRepository:
public interface IDataRepository<TEntity>
{
IEnumerable<TEntity> GetAll();
void Add(Employee employee)
}
Then let’s create a
class EmployeeManager implementing the IDataRepository interface:
public class EmployeeManager : IDataRepository<Employee>
{
public void Add(Employee employee)
{
throw new NotImplementedException();
}
IEnumerable<Employee> IDataRepository<Employee>.GetAll()
{
return new List<Employee>() {
new Employee(){ }
};
}
}
Next step is to add the
service to the service container. We need to do that in the ConfigureServices()
method in the Startup.cs class:
services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
By doing so, we have
configured the repository using Dependency Injection.
Next, let’s create the
EmployeeController with the Index() action method to get the list of all
employees:
public class EmployeeController : Controller
{
private readonly IDataRepository<Employee> _dataRepository;
public EmployeeController(IDataRepository<Employee> dataRepository)
{
_dataRepository = dataRepository;
}
public IActionResult Index()
{
IEnumera
Microservices
______________________________________________________________
What are microservices?
Microservices are a
modern approach to software whereby application code is delivered in small,
manageable pieces, independent of others.
Microservices - also
known as the microservice architecture - is an architectural style that
structures an application as a collection of services that are
• Highly maintainable and testable
• Loosely coupled
• Independently deployable
• Organized around business capabilities
• Owned by a small team
Applications built as a
set of modular components are easier to understand, easier to test, and most
importantly easier to maintain over the life of the application. It enables
organizations to achieve much higher agility and be able to vastly improve the
time it takes to get working improvements to production.
_________________________________________________________
Restful Api
___________________________________________
What is a RESTful API? -
security
One of the most popular
types of API is REST or, as they’re sometimes known, RESTful APIs. REST or
RESTful APIs were designed to take advantage of existing protocols. While REST
- or Representational State Transfer - can be used over nearly any protocol,
when used for web APIs it typically takes advantage of HTTP. This means that
developers have no need to install additional software or libraries when
creating a REST API.
One of the key
advantages of REST APIs is that they provide a great deal of flexibility. Data
is not tied to resources or methods, so REST can handle multiple types of
calls, return different data formats and even change structurally with the
correct implementation of hypermedia. This flexibility allows developers to
build an API that meets your needs while also meeting the needs of very diverse
customers.
There are 6 key
constraints to think about when considering whether a RESTful API is the right
type of API for your needs:
• Client-Server: This constraint operates on the concept that
the client and the server should be separate from each other and allowed to
evolve individually.
• Stateless: REST APIs are stateless, meaning that calls can be
made independently of one another, and each call contains all of the data
necessary to complete itself successfully.
• Cache: Because a stateless API can increase request overhead
by handling large loads of incoming and outbound calls, a REST API should be
designed to encourage the storage of cacheable data.
• Uniform Interface: The key to the decoupling client from server
is having a uniform interface that allows independent evolution of the
application without having the application’s services, or models and actions,
tightly coupled to the API layer itself.
• Layered System: REST APIs have different layers of their architecture
working together to build a hierarchy that helps create a more scalable and
modular application.
• Code on Demand: Code on Demand allows for code or applets to
be transmitted via the API for use within the application.
Unlike SOAP, REST is not
constrained to XML, but instead can return XML, JSON, YAML or any other format
depending on what the client requests. And unlike RPC, users aren’t required to
know procedure names or specific parameters in a specific order.
One of the disadvantages
of RESTful APIs is that you can lose the ability to maintain state in REST,
such as within sessions. It can also be more difficult for newer developers to
use.
It’s important to
understand what makes a REST API RESTful, and why these constraints exist
before building your API.
_________________________________________________________
Async
and Await in a Nutshell
___________________________________________
The async keyword does two things: it enables
the await keyword within that method, and it transforms the method into a state
machine (similar to how the yield keyword transforms iterator blocks into state
machines). Async methods should return Task or Task<T> when possible.
It’s permissible for an async method to return void, but it’s not recommended
because it’s very difficult to consume (or test) an async void method.
The task instance
returned from an async method is managed by the state machine. The state
machine will create the task instance to return, and will later complete that
task.
An async method begins
executing synchronously. It’s only when the async method reaches an await
operator that the method may become asynchronous. The await operator takes a
single argument, an “awaitable” such as a Task instance. First, the await
operator will check the awaitable to see if it has already completed; if it
has, the method continues (synchronously). If the awaitable isn’t yet complete,
the await operator will “pause” the method and resume when the awaitable
completes. The second thing the await operator does is retrieve any results
from the awaitable, raising exceptions if the awaitable completed with an
error.
The Task or
Task<T> returned by the async method conceptually represents the
execution of that method. The task will complete when the method completes. If
the method returns a value, the task is completed with that value as its
result. If the method throws an exception (and doesn’t catch it), then the task
is completed with that exception.
IN Operator Examples
(within?)
SELECT * FROM Customers
WHERE Country IN
('Germany', 'France', 'UK');
A stored procedure is a
prepared SQL code that you can save, so the code can be reused over and over
again.
So if you have an SQL
query that you write over and over again, save it as a stored procedure, and
then just call it to execute it.
You can also pass
parameters to a stored procedure, so that the stored procedure can act based on
the parameter value(s) that is passed.
Index
C# | Action Delegate
Action delegate is an
in-built generic type delegate. This delegate saves you from defining a custom
delegate as shown in the below examples and make your program more readable and
optimized. It is defined under System namespace. It can contain minimum 1 and
maximum of 16 input parameters and does not contain any output parameter. The
Action delegate is generally used for those methods which do not contain any
return value, or in other words, Action delegate is used with those methods
whose return type is void. It can also contain parameters of the same type or
of different types.
Syntax:
// One input parameter
public delegate void
Action < in P > (P obj);
// Two input parameters
public delegate void
Action < in P1, in P2 >(P1 arg1, P2 arg2);
Indexing API
With Indexing API, you
can tell Google which pages need to be re-indexed or removed from the index.
The request should include the URL of the web page.
Sync vs async
Processing Asynchronous
Requests
In web applications that
sees a large number of concurrent requests at start-up or has a bursty load
(where concurrency increases suddenly), making these web service calls
asynchronous will increase the responsiveness of your application. An
asynchronous request takes the same amount of time to process as a synchronous
request. For example, if a request makes a web service call that requires two
seconds to complete, the request takes two seconds whether it is performed
synchronously or asynchronously. However, during an asynchronous call, a thread
is not blocked from responding to other requests while it waits for the first
request to complete. Therefore, asynchronous requests prevent request queuing
and thread pool growth when there are many concurrent requests that invoke
long-running operations.
Local Storage
What is local storage?
Local storage is a
property for accessing a storage object, which is used to store and retrieve
the data from the user’s Browser. It is accessible only at client side and not
at Server side like a cookie.
The data stored in local
storage is accessible. All the pages are under the same domain, unless the user
does not delete it manually. Even though the user closes the Bowser, the data
will be accessible next time.
Set local storage
Optimization
· Benchmark
your code
· Avoid
string based conversions
· Check
for empty strings using string.
· Use
arrays
· Simplify
· …refactor
· ..look
at threading – parallel
Always test?
hash map and abstract
class. A coding problem need to solve with recursive method.
write code to determine
if a tree is mirror structured.
No comments:
Post a Comment