Search This Blog

Thursday, July 1, 2021

Q46-Q50

Q46.  If we have 3 types of constructor in code static, default, parametrized. In which order they will be called. 
Q47. What is GAC?
Q48. Different state management options available in asp.net? 
Q49.  What is Data Annotation in MVC?
Q50. What is the difference between html.partial and html.renderPartial in mvc?



============================================================================
Q46.  If we have 3 types of constructor in code static, default, parametrized. In which order they will be called. 

Answer:
Static constructor will be called first and then depending upon object creation. 
============================================================================
Q47. What is GAC?

Answer:
GAC stands for Global Assembly CacheGAC is the place where shared assemblies get stored in a system.In order to install an assembly to GAC one needs to use the command : gacutil.exe i Assembly name 

============================================================================
Q48. Different state management options available in asp.net? 

Answer:
State management maintains and stores the information of any user till the end of the user session.

1. Server Side
  1. Sessions state
  2. Application State
  3. Cache   
2. Client Side
  1. Cookie
  2. Hidden field
  3. Query strings
  4. Local Storage

============================================================================
Q49.  What is Data Annotation in MVC?

Answer:
Data Annotations are certain validations that we put in our models to validate the input from the users.

Required
[Required(ErrorMessage="Please enter name"),MaxLength(30)]

Range
[Range(100,500,ErrorMessage="Please enter correct value")]

StringLength
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]

DisplayName
Using this attribute we can specify property name to be displayed on view.
[Display(Name="Student Name")]

MaxLength
[MaxLength(3)]

Bind
This attribute specifies fields to include or exclude for model binding.
[Bind(Exclude = "StudentID")]

DisplayFormat
This attribute allows us to set date in the format specified as per the attribute.
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]

RegularExpression
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]

DataType
[DataType(DataType.Text)]

============================================================================
Q50. What is the difference between html.partial and html.renderPartial in mvc?

Answer:
At end both give us the same result but the way they give result behind the scene is different. 
in case of html.partial we get html data which can be stored in a variable and we could play around that html. 
In case of html.renderedpartial we directly render the html content by stream and it can not be tempered. 



============================================================================

Monday, June 14, 2021

Q41-Q45

Q41. What are partial View in MVC?
Q42. How to do MVC model binding?
Q43. What is remote validation in MVC?
Q44. What is CSRF or XSRF. Cross site scripting attack? how can we avoid in mvc?
Q45. What is repository pattern in .net?

====================================================================================
Q41. What are partial View in MVC?

Answer:
Partial view is something which renders itself inside another view. 
Partial views can be put in View folder also but it is recommended to place them in "shared" folder. 
We usually have _ in the beginning of name of partial view. 

Advantages:
1. Partial view is a reusable portion of a view which can be used in multiple places across the other views. 
2. It reduces code duplication. 
3. You can break your large markup files into small partial views for better maintenance. 
====================================================================================
Q42. How to do MVC model binding?

Answer:
Model binding is a process where we bind model to controller and view. 
Steps:
1. Create a model class eg StudentModel
2. Create a Controller class and give path till Model classes folder in using reference. 
3. Create a view. We can use scaff folding way to bind the view to a model. 
Check at top of view below model linkage
@model MvcApplicationDemo.Models.Student  


====================================================================================
Q43. What is remote validation in MVC?

Answer:
 Remote validation is the process where we validate specific data posting data to a server without posting the entire form data to the server. Let's see an actual scenario, in one of my projects I had a requirement to validate an email address, whether it already exists in the database. Remote validation was useful for that; without posting all the data we can validate only the email address supplied by the user.

  1. public class UserModel  
  2. {
  3.     [Required]
  4.     public string UserName { getset; }
  5.     [Remote("CheckExistingEmail","Home",ErrorMessage = "Email already exists!")]
  6.     public string UserEmailAddress { getset; }
  7. }

Here UserEmailAddress required remote validation on mvc.

  1. public ActionResult CheckExistingEmail(string UserEmailAddress)
  2. {
  3.     bool ifEmailExist = false;
  4.     try
  5.     {
  6.         ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com") ? true : false;
  7.         return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
  8.     }
  9.     catch (Exception ex)
  10.     {
  11.         return Json(false, JsonRequestBehavior.AllowGet);
  12.     }
  13. }


====================================================================================
Q44. What is CSRF or XSRF. Cross site scripting attack? how can we avoid in mvc?

Answer:
We can avoid CSRF by having token based authentication and authorization with every call. 


====================================================================================
Q45. What is repository pattern in .net?

Answer:
Repository pattern: It is a design pattern used in ENTITY FRAMEWORK for database connection. We have two things repository classes and IRepository interface.  like EmployeeRepository.cs and IEmployeeRepository 

Layer1 (MVC contoller) --> 
Layer2 (Repository classes, Domain classes and Database contexts) --> 
Layer3 SQL server database

Two approaches. 
1) Create one repository per model. 
2) Create a Generic repository for all. 

In Repository class we write all CRUD functions with help of dbcontext object. 



====================================================================================

Q36-Q40(Kafka)

Q36. How to create Topics in Kafka?
Q37. How to enforce schema validation in kafka?

==============================================================================
Q36. How to create Topics in Kafka?

Answer:
follow below steps
1. check if java is installed or not? if not install java
2. install kafka is not already installed. 
3. install zookeeper is not already installed. zoo keeper helps to manage brokers. 
4. Go to zookeeper folder and launch zoopkeeper and new terminal window will be alunched. 
5. Go to kafa folder and launch kafka. again a new terminal window will be launched. 
6.  Open another terminal session and run:
$ bin/kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092

Step 4:
# Start the ZooKeeper service
# Note: Soon, ZooKeeper will no longer be required by Apache Kafka.
$ bin/zookeeper-server-start.sh config/zookeeper.properties

Step 5:
# Start the Kafka broker service
$ bin/kafka-server-start.sh config/server.properties

==============================================================================




==============================================================================





==============================================================================





==============================================================================

Monday, May 10, 2021

Q26-Q30(Kafka)

Q26. Offset is set by us or does it set by kafka?
Q27. What are the benefits of using Kafka?
Q28. Difference between Kafka and Web API?





==============================================================================
Q26. Offset is set by us or does it set by kafka?

Answer:
Kafka stores offset commits.
==============================================================================
Q27. What are the benefits of using Kafka?

Answer:
Kafka is a distributed public subscribe messaging service. 

Distributed - 
Highly scalable
Low latency
Enormous messaging streaming
Durability - , durability refers to the persistence of data/messages on disk. Also, messages replication is one of the reasons behind durability, hence messages are never lost.
Real-Time Handling
Kafka can handle real-time data pipeline. Since we need to find a technology piece to handle real-time messages from applications, it is one of the core reasons for Kafka as our choice.

Kafka doesn’t try to track which message was actually read by what consumer and just hold on to unread messages. Instead, it holds all of the messages for a pre-specified amount of time, and consumers are charged with tracking their location within each log

  1. Kafka is highly scalable. Kafka is a distributed system, which is able to be scaled quickly and easily without incurring any downtime. Apache Kafka is able to handle many terabytes of data without incurring much at all in the way of overhead.
  2. Kafka is highly durable. Kafka persists the messages on the disks, which provides intra-cluster replication. This makes for a highly durable messaging system.
  3. Kafka is Highly Reliable. Kafka replicates data and is able to support multiple subscribers. Additionally, it automatically balances consumers in the event of failure. That means that it’s more reliable than similar messaging services available.
  4. Kafka Offers High Performance. Kafka delivers high throughput for both publishing and subscribing, utilizing disk structures that are capable of offering constant levels of performance, even when dealing with many terabytes of stored messages.

==============================================================================
Q28. Difference between Kafka and Web API?

Answer:
WebApi:
1. Request/ Response model.


Kafka:
1. Publish/ Subscribe model. 


==============================================================================



==============================================================================

Q21-Q25(Kafka)

Q21. Give one limitation of working with Kafka?
Q22. Multiple consumers can read from same Topic in Kafka?
Q23. I have to ensure once I post the data in kafka, the consumers must its own set of messages. lets say we have 10 consumers and all are subscribing to same topic? 
Q24. What is partition in Kafka?
Q25. In kafka once you have read the message how you make sure that this message is not read again?

=============================================================================
Q21. Give one limitation of working with Kafka?

Answer:
Like any technology, Kafka has its limitations - one of them is the maximum package size of 1 MB. This is only a default setting, but should not be changed easily.
=============================================================================
Q22. Multiple consumers can read from same Topic in Kafka?

Answer:
Yes, multiple consumer can read from same topic also multiple publisher can publish on same topic. 

=============================================================================
Q23. I have to ensure once I post the data in kafka, the consumers must its own set of messages. lets say we have 10 consumers and all are subscribing to same topic? 

Answer:
Topics can be further divided into partitions. each consumer must be associated wtih different partition. 

=============================================================================
Q24. What is partition in Kafka?

Answer:
A topic might have multiple partition. Partitions can be used to handle arbitrary amount of data. 
=============================================================================
Q25. In kafka once you have read the message how you make sure that this message is not read again?

Answer:
Offset

Friday, February 19, 2021

Q16-Q20

Q16. Can a static class contains non static members like variables, methods and properties?
Q17. Can a normal class contains static members?
Q18. What are the difference between MVC and angular? which to choose which one?
Q19. What are the differences between MVC and MVVM?
Q20. How to implement Custom filters in MVC?

===================================================================================
Q16. Can a static class contains non static members like variables, methods and properties?

Answer:
No Static class has only static members like variables, methods and properties.

===================================================================================
Q17. Can a normal class contains static members?

Answer:
Yes. normal class can have static members. eg singleton
for ex. for below code. 
    public class normalclass
    {
        public static void staticmethodofnormalclass()
        {
            Console.WriteLine("this is static method of non static class");

        }
    }

We can call the method staticmethodofnormalclass directly with class name ie normalclass.staticmethodofnormalclass()

===================================================================================
Q18. What are the difference between MVC and angular? which to choose which one?

Answer:

MVC 5 or MVC core
1. MVC gives you a flavor of full flashed full stack layer. All you need is database for storage. 
2. No as such AOT concept. 
3. Testing is kind of mixed for UI and service layer because with bad architecture you might have tight coupling between these two layers.
4. No SPA concept. 
5. Might be good choice in case of Rapid development as it gives easy templates creation. Scaffolding saves lots of time.
6. Less maintenance cost as we have easy and less code. 

Angular
1. This is only for Frontend application. you need service layer as well for this. 
2. Angular has its optimized AOT. Ahead of time compilation which boots speed. 
3. Simplified testing for UI.
4. Better performance because of SPA. 
5. Little more tricky to learn for new developer and usually takes more time to develop. 
6. More maintains cost for both UI layer and service layer. 

===================================================================================
Q19. What are the differences between MVC and MVVM?

Answer:
MVVM - Model, View, ViewModel



>> Angular is more of MVVM model, not MVC

MVVM:
1. Supports two way binding of data between view and viewmodel. 
2. View is the entry point. 


MVC:
1. Does not suppot two way binding by default. 
2. Controller is the entry point. 
===================================================================================
Q20. How to implement Custom filters in MVC?

Answer:
There are two ways by which we can have custom filter. 
1. Simply implementing the interface of any particular filter. 
2. By creating Global filter. This can be done by inheriting Attribute class and overriding its methods.  [remember Interface is not used]

Global filter example --
class MyErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..
 
    }
}
You can now apply the MyErrorHandler attribute at the global level or controller or action method level, the same way we applied an HandleError attribute.

[MyErrorHandler]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

}
==================================

Monday, February 15, 2021

Q11-Q15

Q11. What is difference between static class and Singleton class?
Q12. What is eager loading in entity framework. How it is different from Lazy loading in EF?
Q13. What are the various types of Design pattern in C#?
Q14. Tell me one liner about all design patterns you know?
Q15. Tell something more about Factory method design pattern. How to implement it?
============================================================================
Q11. What is difference between static class and Singleton class?

Answer:

Static Class:-

  1. You cannot create the instance of static class.

  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

  3. Static Class cannot have constructor.

  4. We cannot pass the static class to method.

  5. We cannot inherit Static class to another Static class in C#.

  6. A class having all static methods.

  7. Better performance (static methods are bonded on compile time)

Singleton:-

  1. You can create one instance of the object and reuse it.

  2. Singleton instance is created for the first time when the user requested.

  3. Singleton class can have constructor.

  4. You can create the object of singleton class and pass it to method.

  5. Singleton class does not say any restriction of Inheritance.

  6. We can dispose the objects of a singleton class but not of static class.

  7. Methods can be overridden.

  8. Can be lazy loaded when need (static classes are always loaded).

  9. We can implement interface(static class can not implement interface).


One of the key advantage of singleton over static class is that it can implement interfaces and extend classes while the static class cannot 

============================================================================
Q12. What is eager loading in entity framework. How it is different from Lazy loading in EF?

Answer:
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method. eg: Here we have two tables users and userDetails and they have  a common key that is userId. 

User usr = dbContext.Users.Include(a => a.UserDetails).FirstOrDefault(a => a.UserId == userId);


Lazy Loading means the related entities are not loaded, until we iterate through them or bind them the data. By default, LINQ to SQL loads the related entities, using Lazy Loading.



============================================================================
Q13. What are the various types of Design pattern in C#?

Answer:
Design patterns make your solution reliable, expandable and testable. 
There are 3 types of design pattern

1. Creational - If you have a huge project with a lot of classes, a lot of classes mean you are going to deal with a lot of objects. So you need to create different objects (like new Customer(), new product(), new invoice(), etc.). If these objects creations are scattered on the client code, then it leads to lots of complicated logic at the client code. 
  1. Singleton
  2. Factory Method
  3. Abstract Factory
2. Structural - These patterns deal with the composition of objects structures. The concept of inheritance is used to compose interfaces and define various ways to compose objects for obtaining new functionalities. 
  1. Adaptor
  2. Façade (Faas Saad)
  3. Proxy
3. Behavioral - This patterns deals with object behavior i.e how object is going to behave when communicating with other objects.
  1. Chain of responsibility
  2. Observer
  3. Iterator
In total there are 23 GOF (gang of four design pattern) which fall on above mentioned categories. 

============================================================================
Q14. Tell me one liner about all design patterns you know?

Answer:

Singleton
  1. A class of which only a single instance can exist.
  2. Lets you ensure that a class has only one instance, while providing a global access point to this instance.

Factory Method
  1. Creates an instance of several derived classes.
  2. Provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created
Abstract Factory
  1. Creates an instance of several families of classes
  2. Create instances of several classes belonging to different families
  3. Lets you produce families of related objects without specifying their concrete classes.
Adaptor
  1. Match interfaces of different classes
  2. Allows objects with incompatible interfaces to collaborate.

Façade (Faas Saad)
  1. A single class that represents an entire subsystem
  2. A single class that represents an entire complex system
  3. Provides a simplified interface to a library, a framework, or any other complex set of classes
Proxy
  1. An object representing another object.
  2. Provides a surrogate object, which references to other object.
  3. Lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

Chain of responsibility
  1. A way of passing a request between a chain of objects
  2. Passes a request among a list or chain of objects.]
  3. Lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

Observer
  1. A way of notifying change to a number of classes.
  2. Allows an object (subject) to publish changes to its state and other objects (observer) that depend upon that object are automatically notified of any changes to the subject's state
  3. Lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they're observing.

Iterator
  1. Sequentially access the elements of a collection
  2. Provides a way to access the elements of a collection object in sequential manner without knowing its underlying structure.
  3. Lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
============================================================================
Q15. Tell something more about Factory method design pattern. How to implement it?

Answer:
Factory design pattern is Creational design pattern

Get good example on LearningTopics #Factory Pattern

Q46-Q50

Q46.  If we have 3 types of constructor in code static, default, parametrized. In which order they will be called.  Q47. What is GAC? Q48.  ...