Saturday 11 April 2020

Design patterns (short description)

Here is some short description of GoF design patterns. It is just to remind the explanations. so first you have to understand each design pattern separately.

Adapter Pattern: 

Convert the interface of a class into some other classes that client expects. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Decorator Pattern: (alternate of sub classing)

Attach additional responsibilities to an object at run-time. It follow closed for modification but open for extension SOLID rule.

Strategy Pattern: (Reduce IFs)

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from client that use it.

Template method pattern:

Define the skeleton of an algorithm in an operation, differing same steps to sub classes. Template method lets sub classes redefine certain steps of an algorithm without changing the algorithm structure.

Visitor Pattern

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Ex :calculate IsAboveEighteen by introducing same new property in same class.

Observer Pattern:

Define a one to one dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Builder pattern:

Separate the construction of complex object from its representation so that the same construction process can create different representation. Ex: different configuration computer assembling by robots 

Chain of responsibility:

Avoid coupling of the sender of a request to its receiver by giving more than one object a chance to handle the request.
 Ex: Logic logic =new Logic();
        logic.Receiver=new Logger(new Email(null));
        logic.HandleMessage();

Abstract Factory pattern:

Provides an interface for creating families of related dependent object without specifying their concrete classes. Ex: DbProviderFactory

Factory Pattern:

Define an interface for creating an object but let classes decide which class to instantiate. Factory method lets a class defer instantiation to sub classes. 




















Monday 15 October 2018

Generic Modifier In & Out C#

In [Contravariant]

The image is self-explanatory.


Out [Covarient]

The image is self-explanatory.


Tuesday 11 September 2018

Reduce your Azure Development Subscription Cost


Azure VMs

Usually you should convey to developers and testers to shut down the VMs manually when they are not using non production virtual machines. Also there some ways to automatic shutdown the VMs like you can create and schedule a script to start and shutdown VMs based on use timings or you can use Dev Test labs.

Azure App Services

As app service plan allocate compute resources for which you pay so if you run multiple applications in same app service plan, that will definitely reduce your cost. If your app service plan tier is not fulfilling your new app requirements like it requires high computation resources or your exiting app service plan is already exceeding the resource utilization, than its better to create new one.

Friday 17 August 2018

Generic error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'isLoading: [object Object]'. Current value: 'isLoading: true'

Error: Generic error:  ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'isLoading: [object Object]'. Current value: 'isLoading: true'

Resolution:

setTimeout the code that is setting the value. In my case, it was ngRX store dispatch action so I have changed action like below.

It was like below =>

public setProgress(isLoading: boolean) {
this.store.dispatch(new SetLaoding(isLoading));
}

I changed it to =>

public setProgress(isLoading: boolean) {
setTimeout(() => {
this.store.dispatch(new SetLaoding(isLoading));
});
}

and then this error resolved.

Friday 24 November 2017

Azure data centers and Regions: How to pick a best azure region.

Azure data centers and Regions:


Azure data centers are located worldwide and a team/division MCIO (Microsoft Cloud Infrastructure and Operations) manages all the data centers and its operations. Microsoft divided all the data centers into several regions called “Azure Regions” based on geographic locations. Currently Azure services are available in more than 35 regions around the world and increasing the count rapidly. But all the azure services are not available to each data center, so you have to check the availability of required azure service in the closest region. However there are many parameters need to be consider like cost, redundancy, and network performance etc. because each region have different cost, redundancy option and network performance. So if your requirement is best performance then you can follow below steps before deploying your service otherwise you can compare each parameter region wise.

1)      Find the closest region:

To decide where you should deploy your workload, there is a tool Azure speed test that can suggest the suitable region for your workload.




You should deploy your workload to the closest data center that has the shorter latency time but that region should support your workload type. So move to the next step.

2)      Check availability of the service in selected region.



3)      If required service is not available in the closest region check for the next closer region.

Affinity Group and Regional Virtual Networks

If you are using old azure portal (Classical portal), there is concept of affinity group.  Affinity groups improved performance of multi-tiered applications. Resources that are placed in same affinity group minimize latency between those resources because these resources share same data center. To understand this rack, you have to aware about datacenter architecture.
There are multiple racks in each datacenter. Each rack has 40 to 50 blades and has network switch on top to connect other racks. 20 racks groups together to make a cluster (also called stamp) and all hardware in a cluster uses same processor generation. When all resources are bound to an affinity group, they use same cluster. If you specify the affinity group and create all dependent services in same affinity group, unnecessary network latency avoided and performance will be improved.



In new azure portal, Affinity groups are deprecated and Regional Virtual Networks supported for same feature. https://azure.microsoft.com/en-in/blog/regional-virtual-networks/

Monday 12 June 2017

Windows Azure random FAQs

1. What are IaaS, PaaS and SaaS?

Basically these are cloud service models for cloud offerings. These are categorized on the basis of cloud management of resources.
SaaS: In this web browsers are used to access the software.  In SaaS, all things are managed by cloud providers like infrastructure, data, storage, security etc.
Example of SaaS: Office365, Web based Email services.
Benefits: Scalability, Multi-Tenancy, Security, Pay only what you use. You don’t need to purchase, install, update or maintain any hardware, middle-ware or software. SaaS makes costly application like ERP and CRM affordable for users that lack the resources to buy, deploy and manage the required infrastructure and software themselves.
PaaS: This offers a platform to develop and deploy applications.
IaaS: This offers the cloud servers and associated resources with these servers.
The below table explain these in details.

SaaS
PaaS
IaaS
1.       Hosted Applications



All are managed by Cloud Provider.

Managed by User.


Managed by User.
2.       Develop and deployment tools


Managed by cloud provider.
3.       OS
4.       Server and Storage
Managed by cloud provider.
5.       Networking/Firewall Security
6.       Data Centers

2. What is Service bus and its components?

Main use of service bus is to integrate on premise applications with cloud.
It’s something like postal service that we see in real world. This ensure the communication between two parties even both are not online at same time. That’s why it is brokered messaging mechanism. However it also provides third party communication as well. So it supports two type of messaging patterns.
Azure Relay: The WCF Relay component of Azure Relay is a centralized (but highly load-balanced) service that supports a variety of different transport protocols and Web services standards. The relay service supports traditional one-way messaging, request/response messaging, and peer-to-peer messaging.
Azure Service Bus: Also called Brokered messaging. In this the messaging infrastructure reliably stores messages in a "broker" (such as a queue) until the consuming party is ready to receive them.
 Below are the basic components of Azure Service Bus.
Queues
Topics
Relays
Can be many receivers but one receiver can only receive a message at a time. No two receivers can receive a single message simultaneously.
Each message is processed by a single consumer.

Methods:
ReceiveAndDelete: remove message and immediately deletes it. If exception then message will be lost.
PeekLock: Rather than delete, it locks the message and wait for three events.
1.       If the receiver processes the message successfully, it calls Complete (), and the queue deletes the message.

2.       If the receiver decides that it can't process the message successfully, it calls Abandon (). The queue then removes the lock from the message and makes it available to other receivers.

3.        If the receiver calls neither of these within a configurable period of time (by default, 60 seconds), the queue assumes the receiver has failed. In this case, it behaves as if the receiver had called Abandon, making              the message available to other receivers.

Support publish/subscribe messaging communication model.
"one-to-many" form of communication.
When a message is sent to a topic, it is then made available to each subscription to handle/process independently.

Can apply filter when subscribe.
// Create a "HighMessages" filtered subscription.
SqlFilter highMessagesFilter =
   new SqlFilter("MessageId > 3");

namespaceManager.CreateSubscription("TestTopic",
   "HighMessages",
   highMessagesFilter);


Supports traditional one-way, request/response, and peer-to-peer traffic.

Enabling you to securely expose services that reside within a corporate enterprise network to the public cloud, without having to open a firewall connection, or require intrusive changes to a corporate network infrastructure.


       
Event Hubs are also part of service bus that are also work on Publisher/subscriber model. When events are stored in the Hub, it will stay in the hub until the retention period expires. so you can read messages if needed, even after other subscribers are already read that event/message.

3. What is App Service?

It is an Azure PaaS offerings to create web and mobile applications and provides supports to integrate your apps with on premise applications.
·         It support multiple languages like ASP.Net, Node.js, PHP, Java, Python etc.
·         Also you can run PS scripts inside app service VMs.
·         Support of scale up and out.
·         Connections to SaaS platforms and on-premises data - Choose from more than 50 connectors for enterprise systems (such as SAP, Siebel, and Oracle), SaaS services (such as Salesforce and Office 365), and internet services (such as Facebook and Twitter). Access on-premises data using Hybrid Connections and Azure Virtual Networks.

App Service offers several app types, each of which is intended to host a specific workload:
·         Web Apps - For hosting websites and web applications.
·         Mobile Apps -For hosting mobile app back ends.
·         API Apps - For hosting RESTful APIs.
·         Logic Apps - For automating business processes and integrating systems and data across clouds without writing code.

4. Difference between Azure Web Role vs Azure Web Apps (Azure websites)?

Web role provides the ability to run elevated startup scripts, edit registries, install third party exe, and optimize IIS.
It provides the full control over IIS and web server. You can RDP the VM.
With Windows Azure Web Apps, you don’t have control over IIS or web Server. But it provides fast deployment than Web roles.

5. Brief about Azure API management.

AAPIM is a solution for publishing your APIs to external and internal customers. You have to create an API gateway for your existing backend services hosted anywhere. You can apply security, rules on these services and get how the developers and other users are consuming your services.

Benefits:
·         Secure your APIs using a key, token and IP filtering.
·         Enforce flexible and fine-grained quotas and rate limits, modify the shape and behavior of your APIs using policies and improve latency and scale your APIs with response caching.
·         Get near real-time analytics reports and identify trends that might affect your business. Plus, log request and response data for more online and offline analysis.
·         Expose all APIs behind a single static IP and domain.

6. How to manage your data in Azure.

Azure provides various ways to store and manage the data. Like
·         SQL Database: if data is relational then it would be good option.
·         Blob Storage: store collection of unstructured bytes like backups, videos, mp3, pdf, documents etc.
·         Table Storage: provides NoSQL like storage that work on key-value pairs.

7. Brief state management in azure.

For state management you can use
·         Table Storage
·         Sql Azure
·         Azure Caching
You can provide the session state provide for each as below.
Table Storage:
<sessionState mode="Custom" customProvider="TableStorageSessionStateProvider">
 <providers>
    <clear/>
    <add name="TableStorageSessionStateProvider"
        type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider" />
  </providers>
</sessionState>
TableStorageSessionStateProvider created by Azure Product development team.

Sql Azure:
<sessionState mode="SQLServer"
sqlConnectionString="Server=tcp:[serverName].database.windows.net;Database=myDataBase;User ID=[LoginForDb]@[serverName];Password=[password];Trusted_Connection=False;Encrypt=True;"
cookieless="false" timeout="20" allowCustomSqlDatabase="true" />

Azure Caching:
<sessionState mode="Custom" customProvider="AzureCacheSessionStoreProvider">
  <providers>
    <add name="AzureCacheSessionStoreProvider"
          type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
          cacheName="default" useBlobMode="true" dataCacheClientName="default" />
  </providers>
</sessionState>

8. What is VIP swap?

VIP swap is just a virtual IP swap. VIP swap is the standard way to move your staging deployment to prod and vice versa. This feature is intended to high availability.

9. How to replace azurewebsites.net URL from custom domain name?

Custom DNS is not supported in free tier. You have to access control over DNS settings.
·         Create a CNAME record with your domain provider. Provide name as “www”.
·         Enable CNAME record mapping in your app in azure portal.
·         Add hostname
·         Create A and TXT record inside domain provider
For A record provide IP address of your app from azure portal.
For TXT record provide azurewebsite.net URL of your app.
·         Add these record type also by add hostname in azure portal.

10. What is NoSQL Db. List some example of those.

·         DocumentDb
·         CosmosDb



Wednesday 7 June 2017

Random Advance C# FAQs


  1.  Difference between const, readlonly and static readonly?
  2.  const: const variable value is set as constant value at compile time. it can not be changed.
     readonly: readonly value can be changed at run time using constructor. 
     static readonly: static readonly variables value only can be changed inside static  constructor at run time.

  3. Difference between Binary and XML Serialization?

  4. Binary Serialization: In binary serialization, all  members whether these are pubic, private or readonly are serialized. This is faster than XML serialization. 
    XML Serialization: It serialize only public members.


Tuesday 30 May 2017

Angular 2 FAQs

1. What is angular module?

NgModule helps to organize an application into organized blocks of functionality. @NgModule decorator takes metadata that tells angular how to compile and run the module code. A typical NgModule looks like.


Each application in angular 2 must have at least one NgModule that you need to bootstrap to launch your application.

Components of NgModule:
Declarations Array: this includes application’s components only.
Imports Array: this includes modules.
Providers Array: this includes services.
Bootstrap Array: include components to bootstrap, generally one component used  but you can provide multiple components as well if required.

2. Explain Routing in angular 2?

Router package is used for angular 2 routing. And this router comes with many features for routing based on paths and loading specific components.
To define route we can create routes constants in your modules like

const routes=[
  {Path:'',component: HomeComponent},
  {Path:'Contacts',component:ContactsComponent}
];

Then you have to import these routes in NgModule.
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ContactsComponent   
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule, RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Also you have to use router-outlet inside your component.

@Component({
  selector: 'app-root',
  template: '<nav>
             <a routerLink=””>Home</a>
          <a routerLink=”contact”></a>
          </nav>
       <router-outlet></router-outlet>'
})

But this approach can be optimized by putting out routes in separate file.
We can create separate app.route.ts file to define our route.

import { HomeComponent } from './app.component';
import { ContactsComponent } from './app.component';
import { RouterModule } from '@angular/router';
const routes=[
  {Path:'',component: HomeComponent},
  {Path:'Contacts',component:ContactsComponent}
];

export default RouterModule.forRoot(routes);

And then we does not need to import RouterModule.forRoot(routes) inside our module but we simply import this app.rotes that we have created.

import appRoutes from './app.route';

@NgModule({
  declarations: [
    AppComponent,
    ContactsComponent   
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    appRoutes
  ],
  providers: [],
  bootstrap: [AppComponent]
})

You can have separate route for each component as below. This is called lazy loading of modules using angular 2 router.

a.       Create a separate home.route.ts

import { HomeComponent } from "app/home/home.component";
import { RouterModule } from "@angular/router";

const routes = [
{ path: '', component:HomeComponent}
];

export default RouterModule.forRoot(routes);

b.      Configure route into module.

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HomeComponent } from "app/home/home.component";
import { RouterModule } from "@angular/router";
import homeRoutes from 'app/home/home.routes';

@NgModule({
imports :[CommonModule, homeRoutes],
providers:[],
declarations:[HomeComponent]
})

export default class HomeModule{

}

c.       Configure individual routes to app.route.ts that we have created earlier. See the difference on above app.route.ts and this.

import { HomeComponent } from './app.component';
import { ContactsComponent } from './app.component';
import { RouterModule } from '@angular/router';
import {CommonModule} from '@angular/common'
const routes=[
  {Path:'',loadChildren: 'app/home/home.module'},
  {Path:'Contacts',loadChildren:'app/contact/contact.module'}
];


export default RouterModule.forRoot(routes);