Thursday, December 27, 2012

Consider explicitly specifying the type of the range variable

Source

from x in list

Compilation Error:

Could not find an implementation of the query pattern for source type 'System.Collections.IEnumerable'.  'Select' not found.  Consider explicitly specifying the type of the range variable 'x'.

Fix:

Add the desired data type in front of the range variable x like

from Employee x in list

Wednesday, December 26, 2012

Are you missing a reference or a using directive for 'System.Linq'?

If you see the following error, it could be easy to fix it.

 

Could not find an implementation of the query pattern for source type 'System.Collections.Generic.List<string>'.  'Select' not found.  Are you missing a reference or a using directive for 'System.Linq'?

 

Just ensure you have done the following:

  • Reference to System.Core
  • using/Imports to System.Linq

Saturday, December 15, 2012

Returning Plain text from WCF service

Usually WebGet/Web Post will return data as JSON or Xml

 

In some cases, we may have to return a plain text or our own formatted text.

 

To do this, you can use the following steps,

 

1. Change the return type of the Method to Message instead of string

2. Return the text using by invoking WebOperationContext.Current.CreateTextResponse method

Thursday, December 13, 2012

Anonymous types

C# 3.5 supports anonymous types, through which you can declare simple objects with properties without Class definition

var v = new { Name = "Bob", Age = 20 };
Here a new type will be created with two properties Name and Age.
Name will have type String and Age will have type Integer.
var helps here to declare v using automatic type inferencing.
.Net will create a type and will use it implicitly.
 

Exception: Nullable object must have a value.

Exception: If you receive this error, it means you are trying to get a value from nullable object which has no values assigned.

Fix: To fix this you can check HasValue property before accessing the value

Tuesday, December 04, 2012

Type Inference 2

Automatic type inference will work only within code blocks such as constructors, methods, or property get/set blocks.

 

If you try to use type inference with var, the compiler will give the following error

 

The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)

Sunday, December 02, 2012

Reflection: Assembly.GetExecutingAssembly

Consider the following call sequence.

 

Assembly

When we execute the following code

Console.WriteLine("Executing :" + Assembly.GetExecutingAssembly().GetName().Name.ToString());
Console.WriteLine("Calling :" + Assembly.GetCallingAssembly().GetName().Name.ToString());
Console.WriteLine("Entry :" + Assembly.GetEntryAssembly().GetName().Name.ToString());

Output will be



Executing: OneMoreLib


Calling: AnotherLib


Entry: MyApp

Saturday, December 01, 2012

Reflection- Introduction

Reflection provides the way to access assembly, type and member information.

Even using reflection, we can create objects, read and write property values and invoke methods.

Reflection related classes can be found in System.Reflection Namespace, mscorlib assembly.

Reflection- Assembly

Through System.Reflection.Assembly, we can access assembly related information and also we can load an assembly into memory.
Following methods helps to get the information about the assembly.

System.Reflection.Assembly.GetExecutingAssembly
System.Reflection.Assembly.GetCallingAssembly
System.Reflection.Assembly.GetEntryAssembly
System.Reflection.Assembly.GetAssembly

Following methods helps to load an assembly into memory


System.Reflection.Assembly.Load
System.Reflection.Assembly.LoadFile
System.Reflection.Assembly.LoadFrom
System.Reflection.Assembly.LoadWithPartialName
System.Reflection.Assembly.ReflectionOnlyLoad
System.Reflection.Assembly.ReflectionOnlyLoadFrom
System.Reflection.Assembly.UnsafeLoadFrom

Saturday, September 15, 2012

Enumerable.Range

To loop through a sequence of numbers we can use Enumerable.Range static method.

var x= (from i in Enumerable.Range(0,12)

select i).ToArray();

Above code will create array of integers with values from 0 to 11.

 

Note:

  • First argument is start index
  • Second argument is Count

Thursday, September 13, 2012

Dictionary- An item with the same key has already been added.

If you try to add same key to a Dictionary you may encounter this error

var ht = new Dictionary<String,String>();
ht.Add("key", "Data1");
.
.
.
ht.Add("key", "Data2");

To avoid this use you can simply change this code like

var ht = new Dictionary<String,String>();
ht["key"] = "Data1";
.
.
.
ht["key"] = "Data2";

This indexer will add the key, if it is not in the Dictionary, else will just update the value

Item has already been added. Key in dictionary: 'key' Key being added: 'key'

If you try to add same key to a hashtable you may encounter this error

var ht = new Hashtable();
ht.Add("key", "Data1");
.
.
.
ht.Add("key", "Data2");

To avoid this use you can simply change this code like


var ht = new Hashtable();
ht["key"] = "Data1";
.
.
.
ht["key"] = "Data2";

This index will add the key, if it is not in the hashtable, else will just update the value

Wednesday, September 12, 2012

Extension method must be static

Compilation Error:

Extension method must be static

Cause.

Extension methods (with this keyword in the first parameter), should be marked as static. Non static methods cannot be extension methods.

Collection classes

Following classes we can use for storing collection of Data.

  • System.Array
    • To store same type of data
    • Specific size
    • Direct Access
  • System.Collections.ArrayList
    • To store different types of data
    • Variable size
    • Direct Access
  • System.Collections.Generic.List<T>
    • To store specific types of data
    • Variable Size
    • Direct Access
  • System.Collections.Queue
    • To store different types of data.
    • Variable Size
    • First In First Out data access
  • System.Collections.Generic.Queue<T>
    • To store specific types of data.
    • Variable Size
    • First In First Out data access
  • System.Collections.Stack
    • To store different types of data.
    • Variable size
    • Last In First Out data access
  • System.Collections.Generic.Stack<T>
    • To store specific types of data.
    • Variable size
    • Last In First Out data access
  • System.Collections.Generic.HashSet<T>
    • Generic type
    • To store specific types of data
    • Variable Size
    • Direct Access
    • Supports Set operations such as Intersect, Union

Wednesday, September 05, 2012

The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)

If you encounter this compilation error, it means, you are trying var keyword outside a code block. var works only within code blocks, such as methods and property get and set.

Wednesday, August 15, 2012

0x800a139e - Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load.

You may encounter this error in MVC applications.
Ajax libraries are rendered to the client side as axd file requests, in turn it actually returns javascript files.
MVC url routing blocks axd files by default.
To avoid this you can add the following line in Application_Start method Global.asax.cs/vb
CS
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
VB
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

Saturday, August 11, 2012

Standard Date Time Formatting

Date values can be formatted to particular format using ToString method

 

Example

var str = dt.ToString(“o”)

 

Format Code Sample output Format Name
d 10-08-2012 Short Date
f 10 August 2012 14:20 Full Date Time Short
g 10-08-2012 14:20 General Short
m 10 August Day Month Pattern
o 2012-08-10T14:20:30.1230000 Round trip date time
r Fri, 10 Aug 2012 14:20:30 GMT RFC1123
s 2012-08-10T14:20:30 Sortable date time
t 14:20 Short time
u 2012-08-10 14:20:30Z Universal sortable
y August, 2012 Month Year
D 10 August 2012 Long Date
F 10 August 2012 14:20:30 Full Date Time Long
G 10-08-2012 14:20:30 General Long
M 10 August Day Month Pattern
O 2012-08-10T14:20:30.1230000 Round trip date time
R Fri, 10 Aug 2012 14:20:30 GMT RFC1123
T 14:20:30 Long Time
U 10 August 2012 08:50:30 Universal sortable
Y August, 2012 Month Year

Thursday, August 09, 2012

Extension method must be defined in a non-generic static class

Extension methods (with this keyword in the first parameter), should be containing only within the class is Non Generic and Static.

Containing class

Should Not be generic class

Should be defined as static

Thursday, July 12, 2012

Foreach loop

Foreach loops provides ability to loop through a collection of data.

.Net framework itself uses IEnumerable and IEnumerator interfaces to implement the foreach loop.

Even we can make our own classes to be used in foreach by implementing IEnumerable.

Tuesday, June 12, 2012

Best Practices: Generic lists

ArrayList and Collection class can store Object data.

As Objects are base class for all types, you can store any kind of data within ArrayList and Collections. But mostly we will store specific type of data within collections. So we probably will use casting while retrieving data, which will impact the performance. To avoid this, we can use Generic class such as List<T> and Dictionary<K,V>

Tuesday, June 05, 2012

Generics- Introduction

Generics is the concept of applying types to members such as fields, properties and method signatures when user access it and not when the class designer defines the class.

 

Advantages

  • Performance
  • No need to create similar classes that one varies by member types

 

Introduced in .Net framework 2.0

Thursday, May 24, 2012

Best Practices: Avoid using DataTables

DataTables will take huge memory like multiples of actual needed. So try to use Plain Old Class Objects and DataReader.

Wednesday, May 16, 2012

String to Number, DateTime and Boolean conversion

.Net value type classes mostly have a built in static method Parse to convert a String to specific data types.

Example:

Integer.Parse

Long.Parse

Decimal.Parse

Boolean.Parse

DateTime.Parse

Wednesday, May 09, 2012

Object. ToString method

Object is the base class for all the .Net data types

It has one important method ToString which basically can give the string representation of an Object. Implementation of ToString in Object class basically returns the Type name of the given object. When we call ToString on a class that does not override ToString will just return Type name of the given object.

Monday, March 12, 2012

Type inference

You don’t have to specify the exact type when initializing variable with a type specific value

Example:

Instead of

int i = 10;

you can use

var i = 10;

 

Note:

This can only be used inside a code block (methods, property get set blocks, etc)

Friday, February 10, 2012

3 Pillars of Object Oriented Programming

There are three pillars in Object Oriented Programming

  • Encapsulation- Grouping related properties, methods, events, and fields in a single unit or object.
  • Inheritance- Creating new classes based on an existing class, which provides ability to reuse existing features of a base class, adding new members and/or modifying existing members
  • Polymorphism- provides the ability to assign a derived class to base class and to access the derived class members through the base class.

Friday, January 20, 2012

Authentication modes for Microsoft SQL Server

Microsoft SQL Server provides two authentication modes.

  • Windows Authentication Mode (Default)
    • Users can access SQ Server databases based n their windows login credentials
  • SQL Serer Authentication Mode
    • Separate credentials are created within SQL Server.

ADO.NET: Intro

ADO.NET is the abbreviation of ActiveX Data Objects for .Net Framework
ADO.NET is a common library designed by Microsoft to provide generalized classes and interfaces for extending data access client objects.
There are many data providers implemented ADO.NET. Major implementations are.
  • ADO.NET for ODBC- Microsoft
  • ADO.NET for OLEDB- Microsoft
  • ADO.NET for Microsoft SQL Server- Microsoft
  • ODP.NET (Oracle Data Provider for .Net Framework)- Oracle
  • ADO.NET for IBM DB2- IBM

Converting byte[] to integer

You can convert an integer value to byte array using BitConverter.ToInt32 method

Converting integer to byte[]

You can convert an integer value to byte array using BitConverter.GetBytes method

 

Thursday, January 19, 2012

String in Memory

In .Net Framework, string data type always holds Unicode data in memory.