Monday, 18 May 2020

Interview Questions on CSharp Basics

CSharp Basics Questions and Answers

1. Can You Allow A Class To Be Inherited, But Prevent A Method From Being Overridden In C#?
Ans :Yes. By Declaring the class public and making the method sealed.

2. You Declare An Overridden Method To Be Static If The Original Method Is Not Static?
Ans :No. Two virtual methods must have the same signature.

3. Can You Inherit Private Members Of A Class?
Ans :No, we cannot inherit private members of a class because private members 
are accessible only to that class and not outside that class

4. Is It Possible To Execute Two Catch Blocks?
Ans :No. Whenever, an exception occurs in your program, 
 the correct catch block is executed and the control goes to the finally block.

5. Can You Prevent A Class From Overriding?
Ans :Yes. You can prevent a class from overriding in C# by using the sealed keyword;

6. What Is 'this' Pointer?
Ans :'this' pointer refers to the current object of a class.

7. Can 'this' Be Used Within A Static Method?
Ans :No.

8. Is It Possible For A Class To Inherit The Constructor Of Its Base Class?
Ans :No. A class cannot inherit the constructor of its base class.

9. What's The Difference Between The 'ref' And 'out' Keywords?
Ans :An argument passed as "ref" must be initialized before passing to the method whereas "out" parameter needs not to be initialized before passing to a method, and it will be initialized inside the method.

10. Difference Between Const, Readonly And Static Readonly In C# ?
Ans :
1)Constant variables are declared and initialized at compile time. The value can't be changed after words.
2)Readonly variables will be initialized only from the non-static constructor of the same class.
3)Static Readonly variables will be initialized only from the static constructor of the same class.

You can find more blogs on our website: Trigya Technologies

Sunday, 17 May 2020

Singleton Design Pattern


Singleton Design Pattern:
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.


Singleton Design Pattern by Sanjay D Gangurde


Standard Singleton implementation
To ensure the class has only one instance, we mark the constructor as private. 
So, we can only instantiate this class from within the class.

We create a static variable that will hold the instance of the class.

Then, we create a static method that provides the instance of the singleton class. 
This method checks if an instance of the singleton class is available. 
It creates an instance, if its not available; Otherwise, it returns the available instance.

public class Singleton {

private static Singleton instance;

private Singleton() {}

public static Singleton GetInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}


public class Singleton {

 private static Singleton instance;

 private Singleton() {}

 public static Singleton GetInstance(){
 if(instance == null){
 instance = new Singleton();
 }
 return instance;
 }
}

Issues with the standard implementation
The standard singleton implementation code works fine in Single threaded environment.

But in multithreaded environment, the GetInstance() code breaks :

public static Singleton GetInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}


public static Singleton GetInstance(){
 if(instance == null){
 instance = new Singleton();
 }
 return instance;
 }

If two threads enter the if condition at the same time, then two instances of Singleton will be created.

Handling Multithreading issue with standard singleton implementation
We can synchronize the method. So that only one thread can access it at a time.
In the below implementation, the thread locks out the shared object, 
and then checks whether or not the instance has been created before creating the instance.

 public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object Instancelock = new object();

        private Singleton() {}

        public static Singleton GetInstance
        {
            get
            {
                lock (Instancelock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                    return instance;
                }
            }
        }
}

 public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object Instancelock = new object();

        private Singleton() {}

        public static Singleton GetInstance
        {
            get
            {
                lock (Instancelock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                    return instance;
                }
            }
        }
}
This solves the multithreading issue. But it is slow since only one thread can access GetInstance() method 
at a time.

We can use following approaches for this :

1: Double checked locking
In this approach, we first check if the instance is created. If not, we synchronize.

public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object Instancelock = new object();

        private Singleton() {}

        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                {
                    lock (Instancelock)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }

                    }
                }
                return instance;
            }
        }


public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object Instancelock = new object();

        private Singleton() {}

        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                {
                    lock (Instancelock)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }

                    }
                }
                return instance;
            }
        }

2: Early instance creation
We can choose to create the instance of Singleton class when the class is loaded.This is thread-safe without using locking.

public class EarlySingleton {
//create instance eagerly
private static EarlySingleton instance = new EarlySingleton();

private EarlySingleton() {}

public static EarlySingleton GetInstance(){
return instance;//just return the instance
}
}


public class EarlySingleton {
 //create instance eagerly
 private static EarlySingleton instance = new EarlySingleton();

 private EarlySingleton() {}

 public static EarlySingleton GetInstance(){
 return instance;//just return the instance
 }
}

3: Fully Lazy Instantiation
Here, instantiation is triggered by the first reference to the static member of the GetInstance class, 
which only occurs in Instance.

public sealed class Singleton
  {
    private Singleton()
    {
    }

    public static Singleton GetInstance { get { return GetInstance.instance; } }
        
    private class GetInstance
    {
        // Explicit static constructor to tellcompiler
        // not to mark type as beforefieldinit
        static GetInstance()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }

public sealed class Singleton
  {
    private Singleton()
    {
    }

    public static Singleton GetInstance { get { return GetInstance.instance; } }
        
    private class GetInstance
    {
        // Explicit static constructor to tellcompiler
        // not to mark type as beforefieldinit
        static GetInstance()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }

4: Singleton Implementation using Generics
This will give you a single instance and will effectively be lazy, 
because the static constructor doesn’t get called until Build() is called.

public class GenericSingleton<T> where T : new()
    {
        private static T ms_StaticInstance = new T();

        public T GetInstance()
        {
            return ms_StaticInstance;
        }
    }


    GenericSingleton<SimpleType> instance = new GenericSingleton<SimpleType>();
    SimpleType simple = instance.GetInstance();

public class GenericSingleton<T> where T : new()
    {
        private static T ms_StaticInstance = new T();

        public T GetInstance()
        {
            return ms_StaticInstance;
        }
    }


    GenericSingleton<SimpleType> instance = new GenericSingleton<SimpleType>();
    SimpleType simple = instance.GetInstance();

5: using Lazy<T> type
You need to pass a delegate to the constructor which calls the Singleton constructor – 
which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton GetInstance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton GetInstance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

Even though we avoided multiple instance creation of singleton class 
by using Double checked locking or Eager instance creation, instances can still be created by :
– cloning
– reflection
– Sub-classing singleton class

How to avoid Singleton instance creation by cloning ?
We can create a copy of an object using clone() method.

To avoid creating a clone of our singleton class, we can do the following :

– Implement MethodwiseClone()

– Override the clone() method and throw CloneNotSupportedException from it.

 protected object MemberwiseClone()
    {
        throw new Exception("Cloning a singleton object is not allowed");
    }


How to avoid Singleton class instance creation through Reflection ?
To avoid instance creation through reflection, throw an exception from constructor if it already has an instance.

private Singleton()
    {
        if (instance != null)
        {
            throw new Exception("Cannot create singleton instance through reflection");
        }
    }


How to avoid a subclass creating singleton instance ?
If you just provide a private constructor, a subclass cannot instantiate it to create another instance.

Uses of Singleton Design Pattern :
Logger :
Singleton pattern is a good option for the Logger class when we want to create 
one log file with the logged messages. 
If we have more than one instances of Logger in the application, 
a new log will be created with every instance.

Cache :
We can use Singleton pattern to implement caches as that provides a single global access to it.

Why singleton pattern is considered an Anti-pattern ?
– Singletons aren’t easy to handle with unit tests. You can’t control their instantiation and they may retain state across invocations.
– Memory allocated to an Singleton can’t be freed.
– In multithreaded environment, access to the singleton object may have to be guarded (e.g. via synchronization).
– Singletons promote tight coupling between classes, so it is hard to test

Difference between Static class and Singleton Pattern:
– In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for some business reason or IoC purposes, you can use the Singleton pattern without a static class.
– You can clone the object of Singleton but, you can not clone the static class object
– Singleton object stores in Heap but, static object stores in stack
– A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded

You can find more blogs on our website: Trigya Technologies

Saturday, 16 May 2020

Custom Format Data Export to Excel in C#

Custom Format Data Export to Excel in C#

Hello Everyone,

Most of Developers working around the world faces a scenario where they need to export the data from database to Excel. So today, i will show you how to export the data into excel in C#.
These are easy steps to export and display the data into custom design to excel using C#.


Here are the easy steps,

1. Open the Visual Studio and Create new Website/Web Application
2. Here I've added a button (Export) on my Default.aspx page,

Custom Format Data Export to Excel in C#



3. In the code behind, Add the required namespace,
Custom Format Data Export to Excel in C#



4. Create a object of class StringBuilder as shown below,
Custom Format Data Export to Excel in C#




5. Add the below source code for Button click event,
Custom Format Data Export to Excel in C#








6. Create content to display in an excel,
Custom Format Data Export to Excel in C#
















7. Run the Application, you will find the below mentioned output,
Custom Format Data Export to Excel in C#



















Please post your comments and Queries if you have any queries in SQL Server.

Thank You!
Connect me on: FacebookTwitterInstagram  

You can find more blogs on our website: Trigya Technologies

SQL Query optimization techniques in SQL Server




Sql Statements (queries) are used to retrieve data from the database. The best query is important when performance is considered for that SQL query tuning is required. 

Here are the few techniques which we can use regularly use to optimize the query,

1. The sql query becomes faster if you specify columns names in SELECT statement instead of than '*'.

Eg:
SELECT [ProductID]
      ,[Title]
      ,[ProductName]
      ,[ProductDesp]
      ,[ProdImage]
FROM [dbo].[ProductDetails]

Instead of:
SELECT *

FROM [dbo].[ProductDetails]

2. HAVING clause is used to filter the rows after all the rows are selected. Do not use HAVING clause for any other purposes.

Eg: 
SELECT ProductName, count(ProductName)
FROM ProductDetails
WHERE Title != 'Copper'
AND Title != 'Silver'
GROUP BY Title;

Instead of:
SELECT ProductName, count(ProductName)
FROM ProductDetails
GROUP BY Title

HAVING Title!= 'Copper' AND Title!= 'Silver';

3. There can be more than one subqueries in your main query. Try to minimize the number of subquery block in your query.

For Eg:
SELECT Name
FROM Students
WHERE (score, age ) = (SELECT MAX (score), MAX (age)
FROM StudentsDetails)
AND dept = 'Electronics';

Instead of:
SELECT Name
FROM Students
WHERE score = (SELECT MAX(score) FROM StudentsDetails)
AND age = (SELECT MAX(age) FROM StudentsDetails)
AND dept = 'Electronics';

4. Use operator EXISTS, IN and table joins in a query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.

For Eg

Select * from ProductDetails p
where EXISTS (select * from Items o
where o.ProductId = p.ProductId)

Instead of:

Select * from ProductDetails p
where ProductId IN
(select ProductId from Items)

5. Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.

For Eg:
SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);

Instead of:
SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;

6. Try to use UNION ALL in place of UNION.

For Eg:
SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;

Instead of:
SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;

7. Be careful while using conditions in WHERE clause.

For Eg:
SELECT id, first_name, age FROM student_details WHERE age > 10;

Instead of:

SELECT id, first_name, age FROM student_details WHERE age != 10;

8. Instead of using Temp Table using Table Variable to store data temporary if you don't have record more than 1000 to read the data.

Eg:
SELECT ProductName,Category,Description FROM @TempProduct 

Instead

SELECT ProductName,Category,Description FROM #TempProduct 

9. Avoid LIKE searches with prefix wildcards

Eg:
SELECT
    ProductName,
    Category
FROM
    ProductDetails
WHERE
    ProductName LIKE '%Mar%'

Having a wildcard '%' at the beginning of the pattern will prevent the database from using an index for this column's search. Such searches can take a while.

10. Apply Indexes on tables wherever required.
1. Clustered Index (By Default on Primary Key Column is applied)
2. Non Clustered Index 


Please post your comments and Queries if you have any queries in SQL Server.

Thank You!

Connect me on: FacebookTwitterInstagram  

You can find more blogs on our website: Trigya Technologies

Friday, 15 May 2020

How to Set Keyboard Shortcuts in SQL Server

How to Set Keyboard Shortcuts in SQL Server

Web Developers/SQL Developers usually face challenges in writing SQL Queries again and again during development and updating the new and existing system.

So, Today i will show you few techniques which will be used to solve the problem and accomplish the task more efficiently.

To set the Keyboard Shortcuts in SQL Server. Please find below steps,

Step 1: Go To Tools Menu










Steps 2: Select Options from Tools Menu
How to Set Keyboard Shortcuts in SQL Server


Step 3: Select Keyboard -> Query Shortcuts
How to Set Keyboard Shortcuts in SQL Server


Step 4: Add the Shortcuts and Press OK
How to Set Keyboard Shortcuts in SQL Server

The Shortcuts will be saved.
You can open a new query window and type table name and press Ctrl + 3 by selecting the table name your query for SELECT * FROM TableName  will be fired.

Please post your comments and Queries if you have any queries in SQL Server.

Thank You!


Connect me on: Facebook, Twitter, Instagram  


You can find more blogs on our website: Trigya Technologies

Steps to resolve VAPT Issues

    1. Error: Web Parameter Tampering Resolution:   Add attribute " enableViewStateMac = " false " " inside  <pages...