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
Tuesday, December 9, 2014
the type or namespace name 'expression' could not be found
Thursday, April 3, 2014
The maximum message size quota for incoming messages (65536) has been exceeded
Saturday, February 22, 2014
set entity framework connection string programmatically
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
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");
Sunday, October 16, 2011
Design Patterns which are used in .NET Framework base class library
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
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 | Run-time |
compile-time | Run-time |
A compile-time constant is replaced with the value of that 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 | Runtime constants are evaluated at runtime. The IL generated 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 |
compile-time constant cannot initialize using the new operator, | runtime constants can be of any type, They must |
Compile-time constants can be used only for primitive types
These are the only types that enable you to assign meaningful
As we know that for “const” type in compiler-generated IL the | runtime Read-only values are also constants, in that they cannot be has executed. But read-only values are different in that they |
Compile-time | Run-time constants are much more flexible but its performance |
Compile-time constants are, by definition, static | readonly values can be used for instance constants, for each instance of a class type. |
Every | No need to rebuild Application assembly which is referring a |
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
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
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
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
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
Saturday, June 25, 2011
Why object of abstract class can’t be instantiate
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.
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
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
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
Saturday, May 28, 2011
Can we static methods/class can implement 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
Wednesday, April 20, 2011
What is Endpoints in WCF service
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
How to use vb6 components in .NET
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
Explain STA and MTA
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
Observer design pattern in .NET
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