Saturday, 23 November 2024

Remove Duplication in the string

 //Word duplication checking

string s = "eearr";

string duplicatewords=string.Empty;

for (int i = 0; i < s.Length; i++)

{

    if (!(duplicatewords.Contains(s[i].ToString())))

    {

        duplicatewords += s[i];

    }

}

Console.WriteLine(duplicatewords);


Output:


Using LINQ for Duplication

//To Get unique Word alone
var a1 = s.GroupBy(x => x.ToString());

OUTPUT: a1[0]=e ,a1[1]=a,a1[2]=r

//To Get duplicate Values alone
var a = s.GroupBy(x => x.ToString())
              .Where(g => g.Count() > 1)
              .Select(y => y.Key)
              .ToList();

OUTPUT: a[0]=e ,a[1]=r

JWT(JSON Web Token)

What is JWT?

JSON Web Token (JWT) serves as a compact and self-contained mechanism for securely transmitting information between parties as a JSON object.

JWT Structure/Components:

Header: Specifies the token type (JWT) and the signing algorithm (e.g., HMAC SHA256).

Payload: Contains the claims, which are statements about an entity (user) and additional metadata.

Signature: Created by encoding the header and payload with a secret, ensuring the token’s integrity.

JWT in Action:

  • Upon user authentication, the server generates a JWT.
  • This JWT is sent back to the client and stored, often in local storage or an HTTP-only cookie.
  • The client includes this token in the HTTP Authorization header for subsequent requests.
  • The server validates the token and grants access if valid.

Advantages:

Scalability: Due to their stateless nature, JWTs are ideal for distributed systems.

Flexibility: They can be used across different domains and applications.

Security: When properly implemented, they provide a secure way to handle user authentication.

Security Concerns:

Transmission Security: It's vital to transmit JWTs over HTTPS.

Storage: Store JWTs securely to prevent XSS attacks and other vulnerabilities.

Handling Token Expiry:

Implement short-lived JWTs and use refresh tokens for renewing access without re-authentication.


Wednesday, 30 October 2024

Create object Using Abstract and Interface and its difference

Interface Class

interface InterfaceA

{

    string MethodA(string s);

}

Abstract Class

public class AbstractB:InterfaceA

{

    public string MethodA(string s)

    {

        return s;

    }

}


Object Creation Using Abstract 

AbstractB abstractB = new AbstractB();

abstractB.MethodA("Abstract object");

Output : Abstract object

Object Creation Using Interface 

InterfaceA interfaceA = new AbstractB();

interfaceA.MethodA("Interface object");

Output : Interface object

Note (Object Creation Using Interface) :



 Inheriting the interface directly in the Class and creating the object


 public class DerivedClass :InterfaceA
 {
     public string MethodA(string s)
     {
         return s;
     }
 }

InterfaceA interfaceA1 = new DerivedClass();
interfaceA1.MethodA("Derived object");

Output : Derived object

Sunday, 13 October 2024

Sync and Async

 


If we use Async and await then its going to work in the normal way.

Sunday, 6 October 2024

React props Vs State

 

PROPS

STATE

The Data is passed from one component to another.

The Data is passed within the component only.

It is Immutable (cannot be modified).

It is Mutable ( can be modified).

Props can be used with state and functional components.

The state can be used only with the state components/class component (Before 16.0).

Props are read-only.

The state is both read and write.

React Pure components

We use the shouldComponentUpdate() Lifecycle method to customize the default behavior and implement it when the React component should re-render or update itself.

import React from "react";

export default class Test extends React.PureComponent {

    render() {

        return <h1>Welcome to GeeksforGeeks</h1>;

    }

}

Pure components automatically implement the shouldComponentUpdate() method with a shallow prop and state comparison. This method returns false if the props and state haven’t changed.

Saturday, 5 October 2024

React Suspense

 how to handle fallback content while asynchronous actions are pending and encapsulate any portion of your component tree


<Suspense fallback={<LeoFallback />}>

  <LeoComponent />

</Suspense>

First, import the Suspense components from React, as well as any components you intend to load lazily.


import { Suspense } from 'react';


Then use lazy() to define a dynamic import. For the component you wish to load slowly, this function accepts an argument that is a function that produces a dynamic import statement.


const LeoComponent = lazy(() => import('./LeoComponent'));


  • After React loads, a component tree is rendered.
  • React looks to see whether any of its child components are in a suspended state when it comes across a Suspense component.
  • React will display the given fallback UI until the data is ready, if a child component is awaiting data (for example, as a result of a lazy() import or a data fetch).
  • React smoothly transitions to rendering the real content once the data is available.

Built-in React APIs

  •  CreateContext lets you define and provide context to the child components. Used with useContext.
  • forwardRef lets your component expose a DOM node as a ref to the parent. Used with useRef.
  • lazy lets you defer loading a component’s code until it’s rendered for the first time.
  • memo lets your component skip re-renders with same props. Used with useMemo and useCallback.
  • startTransition lets you mark a state update as non-urgent. Similar to useTransition.
  • act lets you wrap renders and interactions in tests to ensure updates have processed before making assertions.

React - Prop Drilling

 Prop Drilling -  Passing the props from parent to Child or nested child for multiple components is props drilling


Coding Example :



Output:



Passing data from Child to Parent using Callback functions


Output:

Output After Button click:




Super(props) - Its used inside the constructor 
    It will initiate the parent's constructor method and allows the component to inherit methods from its parent (React.Component).

e.g.
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
}





React Hook - UseContext

To manage state globally



React Hook - UseEffect Using example

  • Perform side effects in your components
  • Fetching data, directly updating the DOM, and timers.

Syntax : useEffect(<function>, <dependency>)


1.No dependency passed - Runs on every render:

useEffect(() => {

  //Runs on every render

});

 Output Times Increase automatically :




2.Empty Array in dependency - Runs only on the first render:

useEffect(() => {

  //Runs only on the first render

}, []);

After adding Empty Array in Dependency 


Output :



3. Props or state values - Runs on the first render And any time any dependency value changes

useEffect(() => {

  //Runs on the first render

  //And any time any dependency value changes

}, [prop, state]);

Adding State dependency in the Array :


Output :



4. Effect Cleanup - Some effects require cleanup to reduce memory leaks

UseEffect(() =>{let timer = setTimeout(() => {}); return () => clearTimeout(timer)},[])

After adding cleanup : first time its rendered , once then it have been cleaned up 


Output:




Friday, 4 October 2024

Linq External Method

Linq provides us following Element operators

    • First

    • FirstOrDefault

    • Last

    • LastOrDefault

    • ElementAt

    • ElementAtOrDefault

    • Single

    • SingleOrDefault

    • DefaultIfEmpty






Entity Framework

 Entity Framework is an Object relation Management (ORM) from Microsoft 

ADO.NET Vs Entity Framework

ADO.NET

Entity Framework

Ado.net is faster

EF will be around the ADO.net which means ADO.NET is faster then EF

We need to write so much code to talk to database

Easy to use.

As an EF will talk to database without much code involved

Performance is better than EF

Performance is not good compared to ADO.NET


Linq to SQL Vs Entity Framework

LINQ to SQL

Entity Framework

Supports only for SQL database

Supports database like SQL,Mysql,DB2 etc.

Allows only one to one mapping between the entity classes and the relational table

Allows one to one , one to many & many to many mappings between the entity classes and the relational tables

.dbml file is generated for maintaining the relationship

Relationships are maintained in 3 different files .csdl,.msl and .ssdl


Different Approaches in EF

  1. Database First 
  2. Model First
  3. Code First
Database First:
We have a database already created and ready to use it.
Using the existing database , we can create the entity Models.

Model First:
Create the Entity Models First and derive the database from the Entity Models.

Code First:
Create the Domain classes first and derive the database from the domain classes.

Three Ways of load entities in Entity Framework

  1. Lazy Loading
  2. Eager Loading
  3. Explicit Loading

Lazy Loading: 
  •     Dependent/related entities are loaded once they are accessed for the First time
  •     Delay the loading of related object until it is required
e.g Student s = dbcontext.students.FirstOrDefault(a => a.StudentId == SId)



The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported

Eager Loading: Will do only one database call and get all the dependent entities
e.g Student s= dbcontext.students.Include(s=>s.Courses).FirstOrDefault(s=>s.studentid == sid).

Explicit Loading: - By default it will be lazy loading , But we can disable the lazy loading and we can still load the dependent/related entities by calling Load method.

Student s = dbcontext.Students.FirstOrDefault(a=>a.studentID == sid);
dbcontext.Entry(s).Reference(s=>s.courses).Load();

Connected Vs disconnected data access in ADO.NET

Connected - DataReader Object 
Dis-Connected - DataAdapter Object 













Thursday, 3 October 2024

Javascripts basic Question and Answers

  1.  Map and foreach
  2. Call and apply and bind
  3. currying function
  4. spread and rest
  5. Event bubbling and event catching
  6. async and await error handling
  7. dbounce javascript
  8. sorting array without sort
  9. Promise.all
  10. set object vs map
  11. clone object value
  12. promise race and any
  13. Strict mode


React Basic Questions and Answers

  1. Controlled Vs Uncontrolled Component
    1. Controlled components refer to the components where the state and behaviors are controlled by Parent components 
    2. while Uncontrolled components are the ones having control of their own state and manage the behaviors on themselves(useref)
  2. React Hook 
  3. Higher Order Components
  4. Props Drilling
  5. How to avoid props Drilling
  6. Functional Vs Class Components
  7. How to pass data from parent to child and child to parent
  8. Imperative Hooks in react
  9. What is Virtual Dom
  10. How react is working
  11. How to acheive life cycle method in function components
  12. life cycle method
  13. how to improve the performance of the react appication
  14. what is BABEL
  15. Error handling
  16. Redux architecture flow
  17. Unit test in React
  18. Lazy loading in React


React Lifecycle of Components

 Lifecycle of Components

  • Mounting 
  • Updating 
  • Unmounting

Mounting

  • constructor()
    • method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values
  • getDerivedStateFromProps()
    • method is called right before rendering the element(s) in the DOM.
    • This is the natural place to set the state object based on the initial props.
  • render()
    • method is required, and is the method that actually outputs the HTML to the DOM.
  • componentDidMount()
    • method is called after the component is rendered

Updating

  • getDerivedStateFromProps()
    • first method that is called when a component gets updated.
  • shouldComponentUpdate()
    • method you can return a Boolean value that specifies whether React should continue with the rendering or not.
  • render()
    • method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.
  • getSnapshotBeforeUpdate()
    • method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.
  • componentDidUpdate()
    • method is called after the component is updated in the DOM.

Unmounting

  • componentWillUnmount 
    • method is called when the component is about to be removed from the DOM.

Common Language Runtime (CLR) VS Intermediate language(IL) VS Just-In-Time (JIT)

Code which managed(C#) by CLR is managed Code.

Code which does not managed(c++,VB6 code) by CLR then its unmanaged code.

Garbage collector will not destroy the object which are created out side of the CLR.


 

Wednesday, 2 October 2024

Differentiate between .Net framework Vs .NET Core Vs .Net 5.0

 


React Hook - UserState with Example

 UserState

The React useState Hook allows us to track state in a function component.

State generally refers to data or properties that need to be tracking in an application.

UserState with Single State:

Code:



Output:



After Button Click Output:



UserState with Object State:

Code:



Output:



After Button Click Output:




Type of React Hook

 Types of React Hooks:

1.UserState

  • track state in a function component
  • State generally refers to data or properties that need to be tracking in an application
2.UserEffect
  • perform side effects in your components
  • fetching data, directly updating the DOM, and timers
  • useEffect(<function>, <dependency>)
  •         useLayoutEffect is a version of useEffect that fires before the browser repaints the screen.
    • useLayoutEffect can hurt performance(bad performance). Prefer useEffect when possible.
3.UserContext
  • Context is a way to manage state globally
    • useContext(SomeContext)
    • Passing data deeply into the tree
    • Updating data passed via context
    • Specifying a fallback default value
    • Overriding context for a part of the tree
    • Optimizing re-renders when passing objects and functions
4.Usermemo
  • The main difference is that useMemo returns a memoized value and useCallback returns a memoized function
5.UserRef
  • persist values between renders
6.UserReducer
  • The useReducer Hook is similar to the useState Hook.
  • It allows for custom state logic.
7.UserCallback
  • The React useCallback Hook returns a memoized callback function
    • useCallback(fn, dependencies)
    • Skipping re-rendering of components
    • Updating state from a memoized callback
    • Preventing an Effect from firing too often
    • Optimizing a custom Hook
8.useId
  •        useId is a React Hook for generating unique IDs that can be passed to accessibility attributes.
    • Generating unique IDs for accessibility attributes
    • Generating IDs for several related elements
    • Specifying a shared prefix for all generated IDs
    • Using the same ID prefix on the client and the server


C# Basic Questions and Answers

 C#

1. String Vs String builder

String

String Builder

Inmutable(unable to be changed.)

Mutable

Object reacted for each string object separately in memory and it will create plenty of memory so it may be run slow

Use less memory and run faster

2. Read-only Vs Const Vs Static




3. Abstract Vs Interface


4. Ref Vs Out

Ref

Out

  • The ref keyword is used to pass an argument as a reference.
  • This means that when the value of that parameter is changed in the method.
  • It gets reflected in the calling method.
  • An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

 

  • The out keyword is also used to pass an argument like the ref keyword.
  • But the argument can be passed without assigning any value to it.
  • An argument that is passed using an out keyword must be initialized in the called method before it returns back to the calling method.

 

5. For Vs Foreach


6.Type of Constructor

    Default Constructor:

 public Person()

 {

 Name = "John Doe";

 Age = 30;

 }

    Parameterized Constructor:

Scholar(String name, int id)

{

 this.name = name;

 this.id = id;

}

    Copy Constructor:

 class Scholars

 {

 private string month;

 private int year;

 // Declaring Copy constructor

 public Scholars(Scholars s)

 {

 month = s.month;

 year = s.year;

 }

 // Instance constructor

 public Scholars(string month, int year)

 {

 this.month = month;

 this.year = year;

 }

}

    Private Constructor:

A constructor is referred to as a private constructor if it was created with the private specifier. This class cannot be derived from by any other classes, nor can an instance of this class be created.

public class Scholars

 {

 // Declare a private constructor

 private Scholars()

 {

 }

 // Declare a static variable field

 public static int count_scholars;

 

 // Declare a static method

 public static int scholars_Count()

 {

 return ++count_scholars;

 }

}

    Static Constructor:

Static constructors are designed to be used just once to initialize static class fields or data.


class scholars {


// It is invoked before the first

// instance constructor is run.

static scholars()

{


 // The following statement produces

 // the first line of output,

 // and the line occurs only once.

 Console.WriteLine("Static Constructor");

}

}

7. SOLID Principle



8. Delegate with Example

9. Type of Routing

    Conventional Routing and Attributal Routing

10. Sealed Class Vs Static Class

    



11. MVC filter

 After MVC 5 Authentication filter is also available




12. Action Results



13. Tempdata - Peek Vs Keep


  • Not Read
  • Normal Read
  • Read and Keep
  • Peek and Read

14. As Vs Is

  • IS keyword is helpful to check if the object is that type or not.
  • AS keyword is helpful too if we want to convert one type to another type.
  • IS keyword type is boolean and AS keyword is not a boolean type.
  • The operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type.

15. Extenstion Methods

16. Overloading (Compile-Time) Vs Overrding(Run-Time)





17.Generic Collections(Array, IDictory,List ,IList)

Generic is a type to be specified later. They are instantiated when needed for a specific type provided as parameters. In other words, a Generic allows you to write a class or method that can work with any data type(System.Collection.Generic namespace)



18. Icollections Vs IEnumerable



19. DI Life Time and DI in .NET core

20. CORS

21. React Hook

22. React Life Cycle

23. Thirdparty React - Router, Redux , Axios

24. SQL Optimization (Exection Plan tab check ,etc.)

25. Handle Error 

      .NET using log4net Vs .NET Core Serilogger

26. Struc Vs Class



Monday, 30 September 2024

Word reversing without any build in features in C#

 Console.WriteLine("Enter Word reversing: ");

string s1=Console.ReadLine();

string s2= string.Empty; 

for (int i = s1.Length -1; i > -1; i--)

{

    s2 += s1[i].ToString();

}

Console.WriteLine(s2);

OUTPUT



Checking of string contains word contains on another string

 Console.WriteLine("Enter First word: ");

string s1 = Console.ReadLine();

Console.WriteLine("Enter Second word: ");

string s2 = Console.ReadLine();

int j = 0;

for (int i = 0; i < s2.Length; i++)

{

    s1.Contains(s1[i]);

    j++;

}


string s3 = j == s1.Length ? "Word in First word is also present  in the second" : "Word in First word is not present  in the second";


Console.WriteLine(s3);





Sunday, 7 April 2024

SQL Deadlock

Types of Deadlock

exclusive lock(X), shared lock(S), update lock (U), intent lock (I), schema lock (SCH) and bulk update lock (BU)

select * from sys.dm_tran_locks

 The first time a user sees the following message, the result of an unhandled deadlock error in SQL Server, it can come as quite a shock.

Msg 1205, Level 13, State 56, Line 10

Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Two or more sessions were waiting to acquire a lock on a resource already locked by another session in the same locking chain. The result is a 'circular chain' where no session can complete, and so SQL Server is forced to intervene to clear up the mess. It automatically chooses one of the sessions as the 'victim', kills it and rolls back its transaction. It means that the other sessions may proceed, but that is little comfort to the hapless victim, and if that victim happens to be a session running a critical business process, then it may soon be of little comfort to the DBA.

Deadlock monitoring Two Type of methods

Deadlock Fixing

Redux in react

 React Redux 8.x requires React 16.8.3 or later / React Native 0.59 or later, in order to make use of React Hooks.

React Redux includes a <Provider /> component, which makes the Redux store available to the rest of your app:

import React from 'react'

import ReactDOM from 'react-dom/client'

import { Provider } from 'react-redux'

import store from './store'

import App from './App'

// As of React 18

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(

  <Provider store={store}>

    <App />

  </Provider>,

)


useSelector reads a value from the store state and subscribes to updates, while useDispatch returns the store's dispatch method to let you dispatch actions.

import React from 'react'

import { useSelector, useDispatch } from 'react-redux'

import {

  decrement,

  increment,

  incrementByAmount,

  incrementAsync,

  selectCount,

} from './counterSlice'

import styles from './Counter.module.css'


export function Counter() {

  const count = useSelector(selectCount)

  const dispatch = useDispatch()


  return (

    <div>

      <div className={styles.row}>

        <button

          className={styles.button}

          aria-label="Increment value"

          onClick={() => dispatch(increment())}

        >

          +

        </button>

        <span className={styles.value}>{count}</span>

        <button

          className={styles.button}

          aria-label="Decrement value"

          onClick={() => dispatch(decrement())}

        >

          -

        </button>

      </div>

      {/* omit additional rendering output here */}

    </div>

  )

}

Redux Toolkit