Showing posts with label C#.NET and VB.NET Interview Questions. Show all posts
Showing posts with label C#.NET and VB.NET Interview Questions. Show all posts

Wednesday, December 10, 2014

'System.Linq.IQueryable' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Linq.IQueryable' could be found

Error: 'System.Linq.IQueryable' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Linq.IQueryable' could be found

Solution: Add namespace System.Data.Entity; 
Actually Include is not an extension method on Queryable, so it doesn't come with all the usual LINQ methods. 
If you are using Entity Framework, you need to import namespace System.Data.Entity:
Read More

Tuesday, December 9, 2014

the type or namespace name 'expression' could not be found

To remove error "the type or namespace name 'expression' could not be found" Add namespace System.Linq.Expressions. as normally System.Linq is there in using part by default and expression class is under system.Linq.Expressions so we have to make it also in using.
Read More

Thursday, April 3, 2014

The maximum message size quota for incoming messages (65536) has been exceeded


System.ServiceModel.CommunicationException: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. Just increase the MaxReceivedMessageSize if its in client (who is accessing wcf ) then got to app config and change that size like:
Read More

Saturday, February 22, 2014

set entity framework connection string programmatically


set entity framework connection string programmatically Error: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception Solution:
   public static string GetConnectionString(ProfileMaster profile)
        {
            //return string.Format("data source={0};initial catalog={1};user id={2};password={3} multipleactiveresultsets=True;App=EntityFramework", profile.DatabaseIP, profile.DatabaseName, profile.UserName, profile.Password);
            string providerName = "System.Data.SqlClient";
            string serverName = profile.DatabaseIP;
            string databaseName = profile.DatabaseName;

            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
            new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = true;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
            new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/Models.MoviesDB.csdl|
                        res://*/Models.MoviesDB.ssdl|
                        res://*/Models.MoviesDB.msl";
            return entityBuilder.ToString();
        }

Compiled By: Rajesh Rolen

Read More

Monday, January 13, 2014

Overwrite Appsetting in ASP.NET MVC

  var config = WebConfigurationManager.OpenWebConfiguration("~");
  config.AppSettings.Settings["appSettingKey"].Value ="Updated value";
  config.Save(ConfigurationSaveMode.Minimal, false);
  ConfigurationManager.RefreshSection("appSettings");

Read More

Sunday, October 16, 2011

Design Patterns which are used in .NET Framework base class library

As we know that .net is an OOPs based language so we can easily implement design patterns in our projects but some times it comes to mind that, which all design patters microsoft .NET Base Class Library is using internally.
NOTE: This question also popular in interviews.
Lets walk through few Design patterns used in .NET BCL:

Observer Pattern:
This observer design pattern is used for delegates and events.

Iterator Pattern:
Iterator design pattern used in foreach in C# and For Each in Visual Basic .NET

Decorator Pattern:
System.IO.Stream :Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction.

CryptoStream :System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

Adapter Pattern:
By allowing managed classes and COM components to interact despite their interface differences, RCWs are an example of the Adapter pattern. The Adapter pattern lets you adapt one interface to another. COM doesn't understand the System.String class, so the RCW adapts it to something that it can understand. Even though you can't change how a legacy component works, you can still interact with it. Adapters are frequently used like this.

Factory Pattern:
System.Convert: System.Convert class contains a host of static methods that work like factory design pattern.

System.Net.WebRequest:
This class is used to request and receive a response from a resource on the Internet.FTP, HTTP, and file system requests are supported by default. To create a request, call the Create method and pass in a URI. The Create method itself determines the appropriate protocol for the request and returns the appropriate subclass of WebRequest: HttpWebRequest, FtpWebRequest, or FileWebRequest. The caller doesn't need to know the specifics of each protocol, only how to invoke the factory and work with the WebRequest that gets returned. If the URI changes from an HTTP address to an FTP address, the code won't have to change at all.

Strategy Pattern:
Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. Strategy Design Pattern is used with Array and Arraylist to sort them using different strategy without changing any client code using IComparable interface

Composite Pattern in ASP.NET:
ASP.NET has lots of controls. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.

Because the domain of controls is so diverse, there are several intermediate derived classes like WebControl and BaseDataList that serve as base classes for other controls. Though these classes expose additional properties and methods, they still retain the child management functions and core operations inherited from Control. In fact, the use of the Composite pattern helps to hide their complexity, if desired. Regardless of whether a control is a Literal or a DataGrid, the use of Composite means you can just call Render and everything will sort itself out.

Template Method Pattern:
custom controls are example of Template Method Pattern.


Reference: http://msdn.microsoft.com/en-us/magazine/cc188707.aspx

Compiled By: Rajesh Rolen

Read More

Sunday, September 4, 2011

Constants in .NET


There are two types of constants available in c#:
Compile-time constants and runtime constants. They have different behaviors and
using wrong one will cost you performance or correctness.


But Runtime constants are always preferable over
compile-time constants. Though the compile-time constants are slightly faster
but they are not flexible with compare to runtime constants.


The compile-time constants are preferable when performance
is really required and you don’t have any requirements to change the value of
that constant.


Compile-time constant are declared using “const” keyword:


Eg: public const int a=10;


Run-time constants are declared using “readonly” keyword:


Eg: public readonly int a=10;



compile-time – “Const”


run-time – “readonly”


compile-time
constant
can be declared at class level


Run-time
constant
can be declared at class level


compile-time
constant
can be declared at method level


Run-time
constant
Cannot be declared at method level


A compile-time constant is replaced with the value of that
constant in object code.

Eg:

public const int a=10;

int b=20;

if(b==a)

compiles to the same IL as if you had written this:

if(b==10)// means instead of comparing with variable ‘a’ it
will write its value in compiler-generated IL. Which increase speed but for
various situations its not preferable.


Runtime constants are evaluated at runtime. The IL generated
when you reference a read-only constant references the “
readonly “
variable,
not the value.

Eg:

public const int a=10;

int b=20;

if(b==a)

compiles to the same IL as if you had written this:

if(b==a)// so instead of placing its value as like it do with
“const”,  its place variable for “readonly” variables in compiler-generated
IL.


compile-time constant cannot initialize using the new operator,
even when the type being initialized is a value type.


runtime constants can be of any type, They

must
be initialized using constructor, or using initializer.


Compile-time constants can be used only for primitive types
(built-in integral and floating-point types), enums, or strings.

 

These are the only types that enable you to assign meaningful
constant values in initializers.

 

As we know that for “const” type in compiler-generated IL the
variables get replaces with vales so,these primitive types are the only ones
that can be replaced with literal values. in the compiler-generated IL.


runtime
constants can be of any type.

Read-only values are also constants, in that they cannot be
modified after the constructor

has executed. But read-only values are different in that they
are assigned at runtime.


Compile-time
constants are much more better in performance but less flexible with compare
to run-time constants.


Run-time constants are much more flexible but its performance
is slower with compare to compile-time constants.


Compile-time constants are, by definition,

static
constants.


readonly values can be used for instance constants,
storing different values

for each instance of a class type.


Every
time application assembly need to be rebuilt whenever library assembly which
contains constant gets its constant value changed ( as the compiler-generated
IL contains values of compile-time constants instead of referring variable)


No need to rebuild Application assembly which is referring a
library assembly which contains run-time constants whose value is changed and
its assembly is rebuilt.


 


The final advantage of using const over readonly is
performance: Known constant values can generate slightly more efficient code
than the variable accesses necessary for readonly values.
However, any gains are slight and should be weighed against the decreased
flexibility. Be sure to profile performance differences before giving up the
flexibility.



Compiled By: Rajesh Rolen

Read More

Wednesday, August 10, 2011

What is difference between Dictionary and Hashtable



The fact is that dictionary is a hashtable.
The main difference is that dictionary is a hashtable where as hashtable is not.
That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out.
its almost similar what difference between array list and generic list.

Compiled By: Rajesh Rolen

Read More

Tuesday, August 2, 2011

Find all possible combinations of a string



Using below function we can find all possible combinations of any string.

  static void Combination(string left, string right)
        {
            if (right.Length == 1)
            {
                Console.Write(left);
                Console.Write(right);
                Console.WriteLine();
                return;
            }
            else
            {
                for (var index = 0; index < right.Length; index++)
                {
                    Combination(left + right[index], right.Remove(index, 1));
                }
            }
        }

you can call above function like:

 Combination("", Console.ReadLine());

Compiled By: Rajesh Rolen

Read More

Monday, August 1, 2011

Convert Integers to Binary, Octal or Hexadecimal

Console.WriteLine(Convert.ToString(value, 2));      // Outputs "10101010"
Console.WriteLine(Convert.ToString(value, 8));      // Outputs "271"
Console.WriteLine(Convert.ToString(value, 16));     // Outputs "b9"

Compiled By: Rajesh Rolen

Read More

Monday, July 18, 2011

Will finally blocks be executed if returning from try or catch blocks



Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.

The return value is determined before the finally block is executed though, so if you did this:
int Test()
{
    int result = 4;
    try
    {
        return result;
    }
    finally
    {
        // Attempt to change value result
        result = 1;
    }
}

the value 4 will still be returned, not 1 .

- the assignment in the finally block will have no effect the return result but it will be executed.

A finally block will always be executed and this will happen before returning from the method, so you can safely write code

Compiled By: Rajesh Rolen

Read More

Saturday, June 25, 2011

Why object of abstract class can’t be instantiate

We all knows that object of abstract class can be created but cannot be instantiated, but important question is why its not allowed to instantiate the object of abstract class?

Lets understand it with an example:
 public abstract  class cal
    {
        public cal()
        {

        }
        public cal(int a)
        {

        }
        public abstract int add(int a, int b);

    }

public class c2 
    {
            cal c;// Yes we can create object of abstract class
            c = new cal() // error, we can't instantiate object of abstract class.

       
    }

as we can see in above example that we cannot instantiate the object of an abstract class, this is because if it allows to instantiate the object of abstract class and if you will call its function named "add" (abstract) then what will happen? as there is no function body/functionality is defined for that "add" method, as its functionality will be defined in its child class so CLI not allows us to instantiate the object of abstract class.

An abstract class has a protected constructor (by default) allowing derived types to initialize it.

An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
Read More

Friday, June 24, 2011

What is use of parameterized constructor in abstract class? As Abstract classes cannot be instantiated



public abstract class ABC
{

int _a;

  public ABC(int a)
  {
    _a = a;

   }

public abstract void computeA();

};
The above question is little bit tricky, it wants to make you confuse by emphasizing on keyword “Abstract”, where as it has got nothing to do with abstract class.
First of all its essential to understand the constructor call chain. Whenever an object of a class created, its constructor gets called and that constructor calls its parent class’s constructor then this calling chain continuous till super most class’s constructor get called, then first the super most class’s constructor gets executed first then its child class’s constructor (of same chain) and at last the constructor of class whose object has been created will execute.
In the above example scenario where we have only parameterized constructor and no default “Non Parameterized” constructor, the child/inherited class will have to call constructor of its parent abstract class and will have to pass parameters in it.
Like:
public class Foo : ABC
{
    // Always pass 123 to the base class constructor
    public Foo() : base(123)
    {
    }
}
So you don't necessarily need to pass any information to the derived class constructor, but the derived class constructor must pass information to the base class constructor, if that only exposes a parameterized constructor. Also the child class have to override all abstract functions of its parent class.

Compiled By: Rajesh Rolen

Read More

Thursday, June 16, 2011

What is difference between Private and Sealed Classes



Sealed Class:

"Sealed" keyword provide us facility to prevent a class to be inherited by other classes, so "Sealed" classes cannot be inherited by any other class.

You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

"Sealed" class can have constructor, and they can only be used by its object (non-static methods).

Private Class:

Private class cannot be used directly under any namespace, means we can only create private class as a nested class, to make it available only to class to whom its nested.

the only/mostly use of Private class/structure is to create a user-defined type, which you wants to be accessible to that class only.

NOTE:Nested/inner class can be public also and that can be accessible to inherited class or by object where as private nested/inner class is only accessible to its outer class .


Compiled By: Rajesh Rolen

Read More

Thursday, June 9, 2011

Cast Int to Enum and vice-versa


Many of times we face a situation where we are to cast integer/string value to Enum or vice-versa


Cast Int To Enum

From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

From an int:
YourEnum foo = (YourEnum)yourInt;

From number you can also:
YourEnum foo = Enum.ToObject(typeof(YourEnum) , yourInt);


Cast Enum To Int

int something = (int)Question.Role;

Get Enum type as a string: YourEnumName.ItsOption.ToString()

Compiled By Rajesh Rolen

Read More

Saturday, May 28, 2011

Can we static methods/class can implement Interface

No, Method of interface cannot be implemented as a static methods because Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.

The core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code

Interfaces specify behavior of an object.

Static methods do not specify a behavior of an object, but behavior that affects an object in some way.

Compiled By: Rajesh Rolen

Read More

Wednesday, April 20, 2011

What is Endpoints in WCF service

Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.
in simple language using Endpoint the client application can communicate with your WCF service.

Compiled By Rajesh Rolen

Read More

How to use vb6 components in .NET

as we all know vb6 components work on STA and .NET works on MTA.

To use vb6 dll in .net we will have to follow below steps.
- first create dll in vb6.
- you need to register the DLL. Select the Start menu's Run command and execute the statement:

regsvr32 VB6Project.dll

-Next start a Visual Basic .NET project. Select the Project menu's Add Reference command. Click the COM tab and find the DLL or click the Browse button to select it. Now the .NET application can use the DLL's public classes as we use .net classes. i mean just create its object and call its function with object.function();

http://dotnetacademy.blogspot.com/2011/04/explain-sta-and-mta.html

http://blogs.msdn.com/b/robgruen/archive/2004/11/09/254602.aspx
Read More

Explain STA and MTA

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of it's runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Compiled By Rajesh Rolen

Read More

Observer design pattern in .NET

Using Delegates and events we can implement observer design pattern in .net easily.
Delegates and events provides a new and powerful means of implementing the Observer pattern without developing specific types dedicated to support this pattern. In fact, as delegates and events are first class members of the CLR, the foundation of this pattern is incorporated into the very core of the .NET Framework.

References:
http://msdn.microsoft.com/en-us/library/ff648108.aspx
http://msdn.microsoft.com/en-us/library/ee817669.aspx


Compiled By Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates