/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu




Monday, December 21, 2015

C# Interview Question OOPS - Top 50

1.       What is OOPS?
OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
2.       Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.
  1. Abstraction.
  2. Encapsulation.
  3. Inheritance.
  4. Polymorphism.
3.       What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.
4.       What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.
5.       What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.
Levels are Public, Protected, Private, Internal and Protected Internal.
6.       What is Polymorphism?
Polymorphism is nothing but assigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.
7.       What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class. Inheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritances.
8.       What are manipulators?
Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. Examples are endl and setw.
9.       Define a constructor?
Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules for constructor are:
  • Constructor Name should be same as class name.
  • Constructor must have no return type.
10.   Define Destructor?
Destructor is a method which is automatically called when the object is made of scope or destroyed. Destructor name is also same as class name but with the tilde (~) symbol before the name.
11.   What is Inline function?
Inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.
12.   What is a virtual function?
Virtual function is a member function of class and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.
Virtual function can be achieved in C++, and it can be achieved in C Language by using function pointers or pointers to function.             
13.   What is friend function?
Friend function is a friend of a class that is allowed to access to Public, private or protected data in that same class. If the function is defined outside the class cannot access such information.
Friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public or protected.
14.   What is function overloading?
Function overloading is defined as a normal function, but it has the ability to perform different tasks. It allows creation of several methods with the same name which differ from each other by type of input and output of the function.
Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);
15.   What is operator overloading?
Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function , and it has their own precedence to execute.
Example:
class complex {
double real, imag;
public:
complex(double r, double i) :
real(r), imag(i) {}
complex operator+(complex a, complex b);
complex operator*(complex a, complex b);
complex& operator=(complex a, complex b);
}
a=1.2, b=6
16.   What is an abstract class?
An abstract class is a class which cannot be instantiated. Creation of an object is not possible with abstract class, but it can be inherited. An abstract class can contain only Abstract method.
17.   What is a ternary operator?
Ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types, and it is depends on the function. Ternary operator is also called as conditional operator. Condition? First expression: Second expression;
18.   What is the use of finalize method?
Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected, and it is accessible only through this class or by a derived class.
At runtime C#, C++ destructors are automatically converted to finalize method. But in VB.NET you need to override Finalize method, since it does not support destructor.
You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.

19.   What are different types of arguments?
A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function, and it should match with the parameter defined. There are two types of Arguments.
  • Call by Value – Value passed will get modified only inside the function, and it returns the same value whatever it is passed it into the function.
  • Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

20.   What is super keyword?
Super keyword is used to invoke overridden method which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.
It also forwards a call from a constructor to a constructor in the superclass.
21.   What is method overriding?
Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.
22.   What is an interface?
An interface is a collection of abstract method. If the class implements an inheritance,  and then thereby inherits all the abstract methods of an interface.
23.   What is exception handling?
Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.
24.   What are tokens?
Token is recognized by a compiler and it cannot be broken down into component elements. Keywords, identifiers, constants, string literals and operators are examples of tokens.
Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and Parentheses.

25.   Difference between overloading and overriding?
Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments, and it may or may not return the same value in the same class itself.
Overriding is the same method names with same arguments and returns types associates with the class and its child class.
26.   Difference between class and an object?
An object is an instance of a class. Objects hold any information, but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.
Class can have sub-classes, and an object doesn’t have sub-objects.
27.   What is an abstraction?
Abstraction is a good feature of OOPS, and it shows only the necessary details to the client of an object. Means, it shows only necessary details for an object, not the inner details of an object. Example – When you want to switch on television, it is not necessary to show all the functions of TV. Whatever is required to switch on TV will be showed by using abstract class.
28.   What are access modifiers?
Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers, and they are as follows:
  • Private.
  • Protected.
  • Public.
  • Friend.
  • Protected Friend.
29.   What is sealed modifiers?
Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members. 
30.   How can we call the base method without creating an instance?
Yes, it is possible to call the base method without creating an instance, and that method should be
Static method. Doing inheritance from that class. Use Base Keyword from derived class.
31.   What is the difference between new and override?
The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, override modifier helps to override the base class function.
32.   What are the various types of constructors?
There are three types of constructors, and they are as follows:
-          Default Constructor – With no parameters.
-          Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.
-          Copy Constructor – Which creates a new object as a copy of an existing object?
33.   What is early and late binding?
Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.
34.   What is ‘this’ pointer?
THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.
35.   What is the difference between structure and a class?
Structure default access type is public, but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are exclusively used for data and it doesn’t require strict validation, but classes are used to encapsulates and inherit data which requires strict validation.
36.   What is the default access modifier in a class?
The default access modifier of a class is Private by default.
37.   What is pure virtual function?
A pure virtual function is a function which can be overridden in the derived class but cannot be defined. A virtual function can be declared as Pure by using the operator =0.
Example -
Virtual void function1() // Virtual, Not pure
Virtual void function2() = 0 //Pure virtual
38.   What are all the operators that cannot be overloaded?
Following are the operators that cannot be overloaded -.
  1. Scope Resolution (:: )
  2. Member Selection (.)
  3. Member selection through a pointer to function (.*)

39.   What is dynamic or run time polymorphism?
Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name, same signature but with different implementation.
40.   Do we require parameter for constructors?
No, we do not require parameter for constructors.
41.   What is a copy constructor?
This is a special constructor for creating a new object as a copy of an existing object. There will be always only one copy constructor that can be either defined by the user or the system.
42.   What does the keyword virtual represented in the method definition?
It means, we can override the method.
43.   Whether static method can use non static members?
False
44.   What are base class, sub class and super class?
Base class is the most generalized class, and it is said to be a root class.
Sub class is a class that inherits from one or more base classes.
Super class is the parent class from which another class inherits.
45.   What is static and dynamic binding?
Binding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time, and it is also called as early Binding.
Dynamic binding is a binding in which name can be associated with the class during execution time, and it is also called as Late Binding.
46.   How many instances can be created for an abstract class?
Zero instances will be created for an abstract class.
47.   Which keyword can be used for overloading?
Operator keyword is used for overloading.
48.   What is the default access specifies in a class definition?
Private access specifier is used in a class definition.
49.   Which OOPS concept is used as reuse mechanism?
Inheritance is the OOPS concept that can be used as reuse mechanism.
50.   Which OOPS concept exposes only necessary information to the calling functions?
Data Hiding / Abstraction

Read More »

Thursday, December 10, 2015

Part-2 SQL SERVER - 2008 - Configure Database Mail - Send Email From SQL Database Sending Mail in HTML Format

Part-2 SQL SERVER - 2008 - Configure Database Mail - Send Email From SQL Database Sending Mail in HTML Format


I am just providing the steps that are enough to give you the basic undrstanding to create HTML Format


-- Creating HTML Format Using Stored Procedures for sending email from database the following Stored Procedures Required


-- 1) Create DataSourceCheck stored procedures

CREATE PROCEDURE [dbo].[DataSourceCheck]

@dataSource varchar (100) = NULL,

@db varchar(50) = NULL output,

@table varchar(100) = NULL output

AS

BEGIN

DECLARE

@buffer varchar(100),

@object varchar(100),

@objectId bigint,

@schema varchar(50),

@rcd_cnt int,

@tableHtml varchar(200),

@sql nvarchar(1000)

SET @buffer = @dataSource;

--cannot accesss a local temp table. Return.

IF SUBSTRING (@buffer, 1, 1) = '#' and SUBSTRING (@buffer, 2, 1) <> '#'

BEGIN

--use LEFT 25 to make sure the local temp table name isn't too long for the @table varchar(100) variable.

SET @table = '
Table ' + LEFT (@dataSource, 25) + ' is a local temp table. Must use a global temp or permanent table.
';

RETURN;

END;

--set up the object name in the right format so you can check the OBJECT_ID

ELSE IF (SUBSTRING (@buffer, 1, 2) = '##')

BEGIN

SET @db = 'tempdb';

SET @table = @dataSource;

SET @object = @db + '..' + @table; --need to include tempdb so OBJECT_ID finds the temp table

END;

ELSE

BEGIN

--deal with schema

SET @db = SUBSTRING (@buffer, 1, charindex ('.', @buffer) - 1);

SET @buffer = replace (@buffer, @db + '.', '');

IF SUBSTRING (@buffer, 1, 1) = '.'

BEGIN

SET @schema = '..';

SET @buffer = replace (@buffer, '.', '');

END

ELSE

BEGIN

SET @schema = SUBSTRING (@buffer, 1, charindex ('.', (@buffer)) - 1);

SET @buffer = replace (@buffer, @schema + '.', '');

END

SET @table = @buffer;

SET @object = @dataSource;

END;

--does our data source exist? Check the object_id. If object does not exist, return.

SET @objectId = OBJECT_ID (@object, 'U');

IF @objectId is NULL

BEGIN

SET @db = NULL;

SET @table = '
Table ' + @dataSource + ' does not exist or is improperly qualified.
';

RETURN;

END;

--we have a valid data source. Check that it has rows and notify if empty.

SET @sql = 'SELECT @rcd_cnt = count(*) from ' + @dataSource;

EXEC master.sys.sp_executesql @sql, N'@rcd_cnt int OUTPUT', @rcd_cnt OUTPUT;

IF @rcd_cnt = 0

BEGIN

SET @db = NULL;

SET @table = '
Table ' + @dataSource + ' is empty.
';

RETURN;

END;

END

Read More »

SQL SERVER 2008 Configure Database Mail – Send Email From SQL Database Using sp_send_dbmail

SQL SERVER 2008 Configure Database Mail – Send Email From SQL Database


In order to send mail using Database Mail in SQL Server, there are 3 basic steps that need to be carried out:

Create Profile and Account

Configure Email

Send Email

I am just providing the steps that are enough to give you the basic undrstanding to send a mail from the database to your mail hosting server.

Here for example i am using the Gmail SMTP server details to send a test e-mail.


-- 1) First Enable the Database Mail XPs:

sp_helptext sysmail_add_account_sp


USE master
GO
sp_configure 'show advanced options',1
GO
RECONFIGURE WITH OVERRIDE
GO
sp_configure 'Database Mail XPs',1
GO
RECONFIGURE
GO


-- 2) Create a Database Mail account
EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'DBA Mail',
@description = 'Mail account for administrative e-mail.',
@email_address = 'ycuisthebest@gmail.com',
@replyto_address = 'ycuisthebest@gmail.com',
@display_name = 'DBA Mail',
@mailserver_name = 'smtp.gmail.com',
@port = 25,
@username = 'ycuisthebest@gmail.com',
@password = 'xxxxxx',
@enable_ssl = 1


-- 3) Create a Database Mail profile
EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'DBA Mail',
@description = 'Profile used for administrative mail1.'


-- 4) Add the account to the profile
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'DBA Mail',
@account_name = 'DBA Mail',
@sequence_number =1


-- 5) Grant access to the profile to the DBMailUsers role
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'DBA Mail',
@principal_name = 'public',
@is_default = 1


-- Send A Test E-Mail With Plain Text
EXEC msdb.dbo.sp_send_dbmail
@profile_name='DBA Mail',
@recipients='ycuisthebest@gmail.com',
@subject='My First Test message',
@body='Message Sent Successfully'


-- Send A Test E-Mail with query result here i am just sending the current date as a result set
EXEC msdb.dbo.sp_send_dbmail
@profile_name='DBA Mail1',
@recipients='yogeshsangrajani@gmail.com',
@subject = 'Current date time Values',
@query = N'NOCOUNT ON SELECT getdate();',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'Memory Values.txt',
@body='Message with date Sent Successfully'


--  Send A Test E-Mail with query result in HTML Format 
DECLARE @Body NVARCHAR(MAX),
    @TableHead VARCHAR(1000),
    @TableTail VARCHAR(1000)  

SET @TableTail = '
' ;
SET @TableHead = '' + '' + '' + '' + 'Report generated on : '
    + CONVERT(VARCHAR(50), GETDATE(), 106) 
    + '
    + '
PO Date
'
    + '
ID
'
    + '
Name
'
    + '
Department
'
    + '
Age
'
    + '
Salary
'
    + '
Location
' ;

SET @Body = ( SELECT    td = E.ID, '',
                        td = E.Name, '',
                        td = E.Dept, '',
                        td = E.Age,'',
                        td = E.Salary,'',
                        td = E.Location, ''                      
              FROM      employee E                                      
            FOR   XML RAW('tr'),
                  ELEMENTS
            )  
SELECT  @Body = @TableHead + ISNULL(@Body, '') + @TableTail
  
EXEC msdb.dbo.sp_send_dbmail
@profile_name='DBA Mail1',
@recipients='yogeshupr@gmail.com',  
@subject='Query Result',
@body=@Body,
@body_format = 'HTML' ;   


Some other aspect that will definitely required in the testing phase
You can update the smtp server setting within the following TABLE msdb.dbo.sysmail_server

SELECT * FROM msdb.dbo.sysmail_server
UPDATE msdb.dbo.sysmail_server SET enable_ssl =1, port=25 --etc.,


Usefull table that are required to monitoring the send mail details
Quick troubleshooting queries for Database Mail

SELECT * FROM msdb.dbo.sysmail_server
SELECT * FROM msdb.dbo.sysmail_allitems
SELECT * FROM msdb.dbo.sysmail_account
SELECT * FROM msdb.dbo.sysmail_faileditems
SELECT * FROM msdb.dbo.sysmail_configuration
SELECT * FROM msdb.dbo.sysmail_mailitems


-- Check to see if the service broker is enabled (should be 1):


SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'


-- Check to see if Database Mail is started in the msdb database:


EXECUTE msdb.dbo.sysmail_help_status_sp


-- Start Database Mail if necessary:


EXECUTE msdb.dbo.sysmail_start_sp


-- Check the status of the mail queue:


EXECUTE msdb.dbo.sysmail_help_queue_sp @queue_type = 'Mail'


-- Check the Database Mail event logs:


SELECT * FROM msdb.dbo.sysmail_event_log


-- Check the mail queue for the status of all items (including sent mails):


SELECT * FROM msdb.dbo.sysmail_allitems


It Can Happens: Following Error Solution Link Given Below:


The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 (2015-12-10T10:24:09). Exception Message: Cannot send mails to mail server. (The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at). )


-- Usefull References: http://www.technologycrowds.com/2015/05/smtp-server-authentication-server-response-5-5-1-Authentication-Required-in-Gmail.html


-- Code Project Using Wizard: http://www.codeproject.com/Articles/29060/SQL-SERVER-Configure-Database-Mail-Send-Email
Read More »

SQL Server Generate Week Dates for a Year and Month in SQL Server

SQL Server Generate Week Start Dates End Dates for a Year or Month in SQL Server

Sometimes, you might require Start & End dates for all the weeks in a given year or month to generate week-wise report starting from Monday to Sunday

I have developed a Table-Valued function where you have to pass year and it would return a table with all the weeks and its Start & End Dates for a given year.


Getting Month Week Start Date and End Date

- - Totals by Week 

CREATE FUNCTION dbo.GetWeekDatesForMonth
        (@Year SMALLINT, @Month TINYINT)
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN WITH 
 cteMonth AS   (SELECT  MonthStart     = DATEADD(mm,(@Year-1900)*12+@Month-1,0)
                       ,MonthEnd       = DATEADD(mm,(@Year-1900)*12+@Month,0)-1)
,cteWeeks AS   (SELECT  MonthStart
                       ,MonthEnd
                       ,FirstWeekStart = DATEADD(dd,DATEDIFF(dd,0,MonthStart)/7*7,0)
                       ,LastWeekStart  = DATEADD(dd,DATEDIFF(dd,0,MonthEnd  )/7*7,0)
                  FROM cteMonth)

 SELECT  [Week]       = 'Week'+LEFT(ca.Wk+1,1)
        ,StartDate    =  CAST(
                            CASE 
                            WHEN ca.Wk > 0 
                            THEN DATEADD(dd,Ca.Wk*7,FirstWeekStart) 
                            ELSE MonthStart
                            END
                        AS DATE)
        ,EndDate      = CAST(
                            CASE
                                WHEN DATEADD(dd,Ca.Wk*7+6,FirstWeekStart) <= MonthEnd 
                                THEN DATEADD(dd,Ca.Wk*7+6,FirstWeekStart) 
                                ELSE MonthEnd 
                            END 
                        AS DATE)
   FROM cteWeeks
  CROSS APPLY (SELECT TOP (DATEDIFF(dd,FirstWeekStart,LastWeekStart)/7+1)
                      t.N
                 FROM (VALUES (0),(1),(2),(3),(4),(5))t(N))ca(Wk);


Using GetWeekDatesForMonth 
-- Lets' execute the script and check the output 

SELECT * FROM dbo.GetWeekDatesForMonth(2015,12)


-- OR You can use the following function to get week start and end date

CREATE FUNCTION dbo.udf_GetWeekDatesForMonth(
    @Year  SMALLINT
    , @Month TINYINT
)
RETURNS @WeekDates TABLE (
    Week  VARCHAR(5)
    , StartDate DATE
    , EndDate DATE
)
AS
BEGIN
    DECLARE @MonthStartdate        DATE
            , @MonthEnddate        DATE
            , @WeekStartDate    DATE
            , @WeekEndDate        DATE
            , @ctr                INT = 0

    SET @MonthStartdate = CAST(CAST(@Year*100+@Month AS VARCHAR)+'01' AS DATE)
    SET @MonthEnddate = DATEADD(d,-1,DATEADD(m,1, @MonthStartdate))

    SET @WeekStartDate = @MonthStartdate
    SET @WeekEndDate = DATEADD(d, (8 - datepart(WEEKDAY, @WeekStartDate)), @WeekStartDate)

    WHILE @WeekStartDate < @MonthEnddate
    BEGIN
        SET @ctr = @ctr + 1
        SET @WeekEndDate = (CASE WHEN @WeekEndDate > @MonthEnddate THEN @MonthEnddate ELSE @WeekEndDate END)

        INSERT INTO @WeekDates
        SELECT 'Week' + cast(@ctr as varchar), @WeekStartDate, @WeekEndDate

        SET @WeekStartDate = DATEADD(d, 1, @WeekEndDate)
        SET @WeekEndDate = DATEADD(d, 6, @WeekStartDate)
    END
    RETURN
END

- -Lets' execute the script and check the output 
SELECT * FROM dbo.udf_GetWeekDatesForMonth(2015,12)


Generate Week Dates for a Year in SQL Server


CREATE FUNCTION dbo.udf_GetWeekDatesForYear(
    @Year  SMALLINT 
)
RETURNS @WeekDates TABLE (
    Week  VARCHAR(10)
    , StartDate DATE
    , EndDate DATE
)
AS
BEGIN
    DECLARE @YearStartdate  DATE
            , @YearEnddate  DATE
            , @WeekStartDate DATE
            , @WeekEndDate  DATE
            , @ctr    INT = 0

    SET @YearStartdate = CAST(CAST(@Year AS VARCHAR)+'0101' AS DATE)
    SET @YearEnddate = DATEADD(day,-1,DATEADD(year,1, @YearStartdate))

    SET @WeekStartDate = @YearStartdate
    SET @WeekEndDate = DATEADD(day, (8 - datepart(WEEKDAY, @WeekStartDate)), @WeekStartDate)

    WHILE @WeekStartDate < @YearEnddate
    BEGIN
        SET @ctr = @ctr + 1
        SET @WeekEndDate = (CASE WHEN @WeekEndDate > @YearEnddate THEN @YearEnddate ELSE @WeekEndDate END)

        INSERT INTO @WeekDates
        SELECT 'Week-' + cast(@ctr as varchar), @WeekStartDate, @WeekEndDate

        SET @WeekStartDate = DATEADD(d, 1, @WeekEndDate)
        SET @WeekEndDate = DATEADD(d, 6, @WeekStartDate)
    END
    RETURN
END

- -Lets' execute the script and check the output 

SELECT * FROM dbo.udf_GetWeekDatesForYear(2015)
Read More »

Generate Week Dates for a Month in SQL Server - IT Developer Zone

Read More »

Recent Posts

My Blog List