LINQ Interview Questions and Answers – 1

Q1.  What is LINQ and why to use it?
Ans. LINQ stands for “Language Integrated Query” and pronounced as “LINK”. LINQ was introduced with .NET Framework 3.5 including Visual Studio 2008, C# 3.0 and VB.NET 2008 (VB 9.0). It enables you to query the data from the various data sources like SQL databases, XML documents, ADO.NET Datasets, Web services and any other objects such as Collections, Generics etc. by using a SQL Query like syntax with .NET framework languages like C# and VB.NET.

Why LINQ
LINQ has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET framework languages like C# and VB.NET. This powerful feature helps you to avoid run-time errors.

LINQ also provides a uniform programming model (i.e. common query syntax) to query various data sources. Hence you don’t need to learn the different ways to query different data sources.

Q2.  Which namespace is necessary to use LINQ?
Ans. System.Linq namespace is necessary for writing LINQ queries and to implement it.

Q3.  What are different flavors of LINQ?
Ans. There are following three flavors of LINQ:

1) LINQ to Objects
It enables you to query any in-memory object like as array, collection and generics types. It offers a new way to query objects with many powerful features like filtering, ordering and grouping with minimum code.

2) LINQ to ADO.NET
LINQ to ADO.NET is used to query data from different databases like as SQL Server, Oracle, and others. Further, it can be divided into three flavours:-

I.  LINQ to SQL (DLINQ)
It is specifically designed to work with only SQL Server database. It is an object-relational mapping (ORM) framework that allows 1-1 mapping of SQL Server database to .NET Classes. These classes are automatically created by the wizard based on database table and we can use these classes immediately.

II.  LINQ to Datasets
It is an easy and faster way to query data cached in a Dataset object. This allows you to do further data manipulation operations (like searching, filtering, sorting) on Dataset using LINQ Syntax. It can be used to query and manipulate any database (like Oracle, MySQL, DB2 etc.) that can be query with ADO.NET.

III.  LINQ to Entities
In many ways, it looks like LINQ to SQL. It is an object-relational mapping (ORM) framework that allows 1-1 mapping , 1-many mapping and many-many mapping of a database to .NET Classes. Unlike LINQ to SQL, it can be used to query any database (like Oracle, MySQL, and DB2 etc.) including SQL Server. Now, it is called ADO.NET Entity Framework.

3)  LINQ to XML (XLINQ)
This allows you to do different operations on XML data source like  querying or reading, modifying, manipulating, and saving changes to XML documents.  System.Xml.Linq namespace contains classes for LINQ to XML.

4) Parallel LINQ (PLINQ)
PLINQ was introduced with .NET Framework 4.0. It is a parallel implementation of LINQ to Objects. PLINQ use the power of parallel programming which targets the Task Parallel Library. PLINQ helps you to write a LINQ query which will be execute simultaneously or parallel on different processors.

Q4.  What are advantages of LINQ?
Ans. There are following advantages of using LINQ:

  1. It provides a uniform programming model (i.e. common query syntax) to query data sources (like SQL databases, XML documents, ADO.NET Datasets, Various Web services and any other objects such as Collections, Generics etc.)
  2. It has full type checking at compile-time and IntelliSense support in Visual Studio. This powerful feature helps you to avoid run-time errors.
  3. It supports various powerful features like filtering, ordering and grouping with minimum code.
  4. Its Query can be reused.
  5. It also allows debugging through .NET debugger.

Q5.  What are disadvantages of LINQ?
Ans. There are following disadvantages of using LINQ:

  1. LINQ is not good to write complex queries like SQL.
  2. LINQ doesn’t take the full advantage of SQL features like cached execution plan for stored procedure.
  3. Performance is degraded if you don’t write the LINQ query correctly.
  4. If you have done some changes in your query, you have to recompile it and redeploy its dll to the server.

Coding Questions

Please answer one or both of the following questions. Please do not use existing class libraries in your answer(s):

Write me a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function

   1: using System;

   2:  

   3: namespace CubicType

   4: {

   5:     class Program

   6:     {

   7:         public enum CubicType

   8:         {

   9:             Scalene = 1, // no sides same length

  10:             Isosceles = 2, // 2 sides same length

  11:             Equilateral = 3, // 3 sides same length

  12:             Error = 4,

  13:         }

  14:  

  15:         private static CubicType GetCubicType(int a, int b, int c) {

  16:             if (a <= 0 || b <= 0 || c <= 0) {

  17:                 return CubicType.Error;

  18:             }

  19:  

  20:             if ((a == b) && (b == c)) {

  21:                 return CubicType.Equilateral;

  22:             }

  23:  

  24:  

  25:             if ((a == b) || (a == c) || (b == c)) {

  26:                 return CubicType.Isosceles;

  27:             }

  28:  

  29:  

  30:             if (((a + b) < c) || ((a + c) < b) || ((b + c) < a)) {

  31:                 return CubicType.Error;

  32:             }

  33:             else {

  34:                 return CubicType.Scalene;

  35:             }

  36:  

  37:         }

  38:  

  39:         static void Main(string[] args) {

  40:  

  41:             CubicType result;

  42:  

  43:             /*

  44:              * Test cases

  45:              * 1. valid scalene triangle?

  46:              * 2. valid equilateral triangle?

  47:              * 3. valid isosceles triangle?

  48:              * 4. 3 permutations of previous?

  49:              * 5. side = 0?

  50:              * 6. negative side?

  51:              * 7. one side is sum of others (1, 2, 3)?

  52:              * 8. 3 permutations of previous?

  53:              * 9. one side larger than sum of others (1, 2, 4)?

  54:              * 10. 3 permutations of previous?

  55:              * 11. all sides = 0?

  56:              * 12. non-integer input?

  57:              * 13. wrong number of values?

  58:              * 14. for each test case: is expected output specified?

  59:              * 15. check behaviour after output was produced?

  60:              * 

  61:             */

  62:             result = GetCubicType(1, 1, 1);

  63:             Console.WriteLine("(1, 1, 1) = {0}", result.ToString()); // Equilateral triangle

  64:  

  65:             result = GetCubicType(2, 1, 1);

  66:             Console.WriteLine("(2, 1, 1) = {0}", result.ToString()); // Isosceles triangle

  67:  

  68:             result = GetCubicType(1, 2, 1);

  69:             Console.WriteLine("(1, 2, 1) = {0}", result.ToString()); // Isosceles triangle

  70:  

  71:             result = GetCubicType(1, 1, 2);

  72:             Console.WriteLine("(1, 1, 2) = {0}", result.ToString()); // Isosceles triangle

  73:                        

  74:             

  75:             result = GetCubicType(1, 2, 25);

  76:             Console.WriteLine("(1, 2, 25) = {0}", result.ToString()); // Error

  77:  

  78:             result = GetCubicType(1, 0, -1);

  79:             Console.WriteLine("(1, 0, -1) = {0}", result.ToString());

  80:  

  81:             result = GetCubicType(4, 5, 6);

  82:             Console.WriteLine("(4, 5, 6) = {0}", result.ToString());

  83:             

  84:             result = GetCubicType(2147483647, 2147483647, 2147483647);

  85:             Console.WriteLine("(2147483647, 2147483647, 2147483647) = {0}", result.ToString());

  86:  

  87:         }

  88:     }

  89: }

 

1) Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5: using System.Threading;

   6:  

   7: namespace ThreadSafeCircularQueue

   8: {

   9:     /// <summary>

  10:     ///  CircularQueue

  11:     /// </summary>

  12:     public class CircularQueue

  13:     {

  14:         private int head;

  15:         private int tail;

  16:         private int[] queue;

  17:         private int length;

  18:  

  19:         private static Object QueueLock = new Object(); // Make the Queue thread safe

  20:  

  21:         /// <summary>

  22:         ///  Queue Constructor

  23:         /// </summary>

  24:         /// <param name="lengh"> Length of Queue</param>

  25:         public CircularQueue(int lengh)

  26:         {

  27:             Initialize(length);

  28:         }

  29:  

  30:         public CircularQueue()

  31:         {

  32:  

  33:         }

  34:  

  35:         /// <summary>

  36:         /// Initializes the Queue

  37:         /// </summary>

  38:         /// <param name="length"> length </param>

  39:         private void Initialize(int length)

  40:         {

  41:             head = -1;

  42:             tail = -1;

  43:  

  44:             this.length = length;

  45:             queue = new int[length];

  46:  

  47:             Console.WriteLine("Queue size: {0}", length);

  48:         }

  49:  

  50:         /// <summary>

  51:         /// Adds a new int element to the tail of the Queue

  52:         /// </summary>

  53:         /// <param name="value">The integer value of the element to be queued</param>

  54:         /// <returns>The index of the queued element or failure</returns>

  55:         public int Enqueue(int value)

  56:         {

  57:             lock (QueueLock) {

  58:                 if ((head == 0 && tail == length - 1) || (tail + 1 == head)) {

  59:                     Console.WriteLine("Queue is full.");

  60:                     return -1;

  61:                 }

  62:                 else {

  63:                     if (tail == length - 1)

  64:                         tail = 0;

  65:                     else

  66:                         tail++;

  67:  

  68:                     queue[tail] = value;

  69:  

  70:                     if (head == -1)

  71:                         head = 0;

  72:  

  73:                     return tail;

  74:                 }

  75:  

  76:             }

  77:         }

  78:  

  79:         /// <summary>

  80:         /// Gets the first element's value

  81:         /// </summary>

  82:         /// <returns></returns>

  83:         public int Dequeue()

  84:         {

  85:             lock (QueueLock) {

  86:                 int value;

  87:  

  88:                 if (head == -1) {

  89:                     value = -1;

  90:                 }

  91:                 else {

  92:                     value = queue[head];

  93:                     queue[head] = 0;

  94:  

  95:                     if (head == tail)

  96:                         head = tail = -1;

  97:                     else

  98:                         if (head == length - 1)

  99:                             head = 0;

 100:                         else

 101:                             head++;

 102:                 }

 103:  

 104:                 return value;

 105:             }

 106:         }

 107:  

 108:         /// <summary>

 109:         /// Gets a formatted string of the queue elements

 110:         /// </summary>

 111:         /// <returns>Queue elements</returns>

 112:         public string ShowQueue()

 113:         {

 114:             lock (QueueLock) {

 115:                 int i;

 116:                 string result = " Queue Emelemnts: ";

 117:  

 118:                 if (head == -1) {

 119:                     result = "No elements(empty)";

 120:                 }

 121:                 else {

 122:                     if (tail < head) {

 123:                         for (i = 0; i <= length - 1; i++)

 124:                             result += queue[i] + " ";

 125:                     }

 126:                     else

 127:                         for (i = 0; i <= tail; i++)

 128:                             result += queue[i] + " ";

 129:                 }

 130:                 return result + "\n";

 131:             }

 132:         }

 133:  

 134:         /// <summary>

 135:         /// Test

 136:         /// </summary>

 137:         public void QueueTest()

 138:         {

 139:             Initialize(3);

 140:             Enqueue(1);

 141:             Console.Write(ShowQueue());

 142:             Enqueue(2);

 143:             Console.Write(ShowQueue());

 144:             Enqueue(3);

 145:             Console.Write(ShowQueue());

 146:             Enqueue(4);

 147:             Console.Write(ShowQueue()); 

 148:             Dequeue();

 149:             Console.Write(ShowQueue());

 150:             Dequeue();

 151:             Console.Write(ShowQueue());

 152:             Dequeue();

 153:             Console.Write(ShowQueue());

 154:             Dequeue();

 155:             Console.Write(ShowQueue());

 156:             Enqueue(4);

 157:             Console.Write(ShowQueue());

 158:             Dequeue();

 159:             Console.Write(ShowQueue());

 160:             Dequeue();

 161:             Console.Write(ShowQueue());

 162:         }

 163:  

 164:     }

 165:  

 166:     class Program

 167:     {

 168:         static void Main(string[] args)

 169:         {

 170:             CircularQueue circularQueue = new CircularQueue();

 171:  

 172:             Thread[] threads = new Thread[5];

 173:  

 174:             for (int i = 0; i < threads.Length; i++) {

 175:                 threads[i] = new Thread(new ThreadStart(circularQueue.QueueTest));

 176:             }

 177:  

 178:             for (int i = 0; i < threads.Length; i++) {

 179:                 threads[i].Start();

 180:             }

 181:             Console.ReadLine();

 182:         }

 183:     }

 184: }

Technical Questions 1

1) Which is better – singly linked list or doubly linked list? What are the pros and cons of using each?

Singly-linked list:

Pros: Simple in implementation, requires relatively lesser memory for storage, assuming you need to insert/delete at next node; insertion/deletion is faster.

Cons: Cannot be iterated in reverse, need to maintain a handle to the head node of the list else, the list will be lost in memory. If you’re deleting previous node or inserting at previous node, you will need to traverse list from head to previous node to be able to carry out those operations – O(N) time.

That should be used when you have lesser memory and your main purpose is insertion/deletion and not searching elements.

Doubly-linked list:

Pros: Can be iterated in forward as well as reverse direction. In case of needing to delete previous node, there is no need to traverse from head node, as the node to be deleted can be found from ‘.previous’ pointer.

Cons: Relatively complex to implement, requires more memory for storage (1 ‘.previous’ pointer per node). Insertions and deletions are relatively more time consuming (assigning/reassigning ‘.previous’ pointer for neighbor nodes)

That should be used when you have no minimal limitations on memory, and your main purpose is to search for elements.

2) What’s the difference between Managed code and Native code? Give examples of each you have worked on.
The big difference is memory management. With Native Code, you need to do your own resource (RAM / Memory) allocation and cleanup. If you forget something, you end up with what’s called a “Memory Leak” that can crash the computer. A Memory Leak is a term for when an application starts using up (eating up) Ram/Memory but not letting it go so the computer can use if for other applications; eventually this causes the computer to crash. With Managed Code, all the resource (RAM / Memory) allocation and cleanup are done for you and the risk of creating “Memory Leaks” is reduced to a minimum. This allows more time to code features instead of spending it on resource management.

  • · Managed code runs under CLR whereas native code does not run under CLR.
  • · Managed code takes advantages of memory management, security and threading services CLR provides, whereas these are missing for native code that directly runs on the machine.
  • · The managed code is the one generated by C# and other .NET language compilers (IL) and gets finally converted to native code by JIT. The code in languages prior to .NET like VC++ get converted directly to native code and runs on the machine.eg COM components

Over the past two years, I developed web applications for extending the server by modules which are developed in two ways (We have specific requirements that demand native code development and would like to convert our existing native ISAPI components, take advantage of this API to build server components.):

a) Using managed code, and the ASP.NET server extensibility APIs

b) Using native code, and the IIS native server extensibility APIs

3) What is thread safe code? Give an example of times you’ve used thread safe code.
Thread-safety is a computer programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous executions by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least astonishment. Thread-safety is a property aimed for so as to minimize surprising behavior by re-establishing some of the correspondences between the actual flow of control and the text of the program.

General-purpose types are rarely thread-safe in their entirety, for the following reasons:

  • · The development burden in full thread safety can be significant, particularly if a type has many fields (each field is a potential for interaction in an arbitrarily multithreaded context).
  • · Thread safety can entail a performance cost (payable, in part, whether or not the type is actually used by multiple threads).
  • · A thread-safe type does not necessarily make the program using it thread-safe, and often the work involved in the latter makes the former redundant.

Example: Methods used in Logger, to write a log file, should be threading safe for an application that runs under multi-threading environment.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

   1: public static class SharedLogger

   2: {

   3:     private static LogToFile _writer = new LogToFile();

   4:     private static object _lock = new object();

   5:     public static void Write(string text)

   6:     {

   7:         lock (_lock)

   8:         {

   9:             _writer.LogToFile(string text);

  10:         }

  11:     }

  12: }

Technical Questions

1) Which is better – singly linked list or doubly linked list? What are the pros and cons of using each?
Singly linked list has smaller memory requirement because singly linked list can only be traversed in one direction. Doubly linked lists require more space for each element in the list and elementary operations such as insertion and deletion is more complex since they have to deal with two references. But doubly link lists allow easier manipulation since it allows traversing the list in forward and backward directions.

Singly Linked List vs. Doubly Linked List

· Elements in singly linked list are linked to only the next element in the series while elements are linked with previous and next both elements in doubly linked list.

· Singly linked lists need lesser space while doubly linked list need more space for every block in the list.

· Basic functions like addition or deletion are complicated in doubly linked list because there are two links to deal with but you can easily manipulate the data because you can cross over the list and move back and forth in the list.

2) What’s the difference between Managed code and Native code? Give examples of each you have worked on.

Managed Code:

Managed code runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. Managed code takes advantages of memory management, security and threading services CLR provides.

The managed code is the one generated by C# and other .NET language compilers (IL) and gets finally converted to native code by JIT. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it’s optional.

Native Code:

Native code does not run under CLR and compiles straight to machine code. No free memory management or anything else the CLR provides. Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

I wrote some web applications in C and C++ on the apache on Linux. These are native code applications whose memory is not “managed”, as in, memory isn’t freed (C++’ delete and C’s free, for instance), no reference counting, no garbage collection. I had to take care of these to free allocated memory.

3) What is thread safe code? Give an example of times you’ve used thread safe code.

Thread Safe code is one which runs in a manner that when multiple threads are running simultaneously and are in need of using shared memory, they do not step onto each other or in other words access the shared memory exclusively.

By using thread-safe routines, the risk that one thread will interfere and modify data elements of another thread is eliminated by circumventing potential data race situations with coordinated access to shared data.

Online References for implementing checklist

 

C# Performance:
Microsoft:
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx
http://msdn.microsoft.com/en-us/library/ff647813.aspx
http://msdn.microsoft.com/en-us/library/ms973839.aspx
http://msdn.microsoft.com/en-us/library/ms973839
http://msdn.microsoft.com/en-us/library/ms973852
http://msdn.microsoft.com/en-us/magazine/cc163510.aspx
http://msdn.microsoft.com/library/ms973837.aspx
http://msdn.microsoft.com/library/ms973858.aspx

Others:
http://www.techgalaxy.net/Docs/Dev/5ways.htm
http://www.codeproject.com/KB/cs/effective1.aspx

Blogs:
http://blogs.msdn.com/b/ricom/

ASP .Net Performance:
http://msdn.microsoft.com/en-us/magazine/cc163854.aspx
http://msdn.microsoft.com/en-us/library/ff647787.aspx
http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx
http://www.realsoftwaredevelopment.com/20-tips-to-improve-aspnet-application-performance/
http://wiki.asp.net/page.aspx/31/performance/

WCF Performance:
http://support.microsoft.com/kb/982897
http://msdn.microsoft.com/en-us/library/ee377061(v=bts.10).aspx
http://msdn.microsoft.com/en-us/library/ms735098.aspx

Blogs:
http://www.askives.com/wcf-performance.html
http://blog.thekieners.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/
http://merill.net/2008/10/wcf-performance-optimization-tips/
http://weblogs.asp.net/sweinstein/archive/2009/01/03/creating-high-performance-wcf-services.aspx
http://metallemon.hubpages.com/hub/WCF-Service-Performance
http://www.aspnet101.com/2010/08/wcf-performance-best-practices/
http://blogs.msdn.com/b/stcheng/archive/2011/01/05/wcf-wcf-performance-testing-information-share.aspx
http://webservices20.blogspot.com/2009/01/wcf-performance-gearing-up-your-service.html
http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx

MVC Performance:
http://www.codeproject.com/KB/aspnet/How_to_improve_performanc.aspx
http://weblogs.asp.net/gunnarpeipman/archive/2010/02/07/asp-net-mvc-performance-ii-optimizing-resources.aspx
http://www.slideshare.net/rudib/aspnet-mvc-performance
http://msmvps.com/blogs/kenlin/archive/2010/05/14/mvc-performance-in-iis-part-ii.aspx
http://blogs.msdn.com/b/marcinon/archive/2011/02/07/mvc-performance-tips.aspx

Thread Safe code

Thread-safety is a computer programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous execution by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. It was once only a concern of the operating system programmer but has of late become a commonplace issue to be tackled by the everyday programmer. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least astonishment. Thread-safety is a property aimed for so as to minimize surprising behavior by re-establishing some of the correspondences between the actual flow of control and the text of the program.

The requirement for thread-safety highlights the inherent tension in multi-threaded programming: the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:

  • Accessing global variables or the heap.
  • Allocating/freeing resources that have global limits (files, sub-processes, etc.)
  • Indirect accesses through handles or pointers

A subroutine that only uses variables from the stack, depends only on the arguments passed in, and calls other subroutines with similar properties is reentrant, and thus thread-safe.

As seen in the definition, there are a few ways to achieve thread-safety:

  • Reentrancy: Basically, writing code in such a way as to avoid sharing of data across threads.
  • Mutual exclusion: Access to shared data is serialized using mechanisms that ensure only one thread is accessing the shared data at any time. If a piece of code accesses multiple shared pieces of data, there needs to be an enormous amount of care in using mutual exclusion mechanisms — problems include race conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.

A commonly used idiom combines both approaches:

  • Make changes to a private copy of the data, and finally, atomically update the shared data from the private copy. Thus, most of the code would be close to re-entrant, and the amount of time spent serialized would be small.

The concept of exception safety is closely related, since it again deals with (synchronous) flows of control not directly correlated to the text of a program.

Testing a Web Method Using Sockets

Problem
You want to test a Web method in a Web service by calling the method using sockets.
Design
First, construct a SOAP message to send to the Web method. Second, instantiate a Socket object and connect to the remote server that hosts the Web service. Third, construct a header that contains HTTP information. Fourth, send the header plus SOAP message using the Socket.Send() method. Fifth, receive the SOAP response using Socket.Receive() in a while loop. Sixth, analyze the SOAP response for an expected value(s).

            Console.WriteLine("Calling Web Method GetTitles() using sockets");
            string input = "testing";
            string soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            soapMessage += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchemainstance\"";
            soapMessage += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
            soapMessage += " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
            soapMessage += "<soap:Body>";
            soapMessage += "<GetTitles xmlns=\"http://tempuri.org/\">";
            soapMessage += "<filter>" + input + "</filter>";
            soapMessage += "</GetTitles>";
            soapMessage += "</soap:Body>";
            soapMessage += "</soap:Envelope>";
            Console.WriteLine("SOAP message is: \n");
            Console.WriteLine(soapMessage);
            string host = "localhost";
            string webService = "/TestAuto/Ch8/TheWebService/BookSearch.asmx";
            string webMethod = "GetTitles";
            IPHostEntry iphe = Dns.Resolve(host);
            IPAddress[] addList = iphe.AddressList; // addList[0] == 127.0.0.1
            EndPoint ep = new IPEndPoint(addList[0], 80); // ep = 127.0.0.1:80
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ep);
            if (socket.Connected)
                Console.WriteLine("\nConnected to " + ep.ToString());
            else
                Console.WriteLine("\nError: socket not connected");
            string header = "POST " + webService + " HTTP/1.1\r\n";
            header += "Host: " + host + "\r\n";
            header += "Content-Type: text/xml; charset=utf-8\r\n";
            header += "Content-Length: " + soapMessage.Length.ToString() + "\r\n";
            header += "Connection: close\r\n";
            header += "SOAPAction: \"http://tempuri.org/" + webMethod + "\"\r\n\r\n";
            Console.Write("Header is: \n" + header);
            string sendAsString = header + soapMessage;
            byte[] sendAsBytes = Encoding.ASCII.GetBytes(sendAsString);
            int numBytesSent = socket.Send(sendAsBytes, sendAsBytes.Length,   SocketFlags.None);
            Console.WriteLine("Sending = " + numBytesSent + " bytes\n");
            byte[] receiveBufferAsBytes = new byte[512];
            string receiveAsString = "";
            string entireReceive = "";
            int numBytesReceived = 0;
            while ((numBytesReceived = socket.Receive(receiveBufferAsBytes, 512,
            SocketFlags.None)) > 0)
            {
                receiveAsString = Encoding.ASCII.GetString(receiveBufferAsBytes, 0,
                numBytesReceived);
                entireReceive += receiveAsString;
            }
            Console.WriteLine("\nThe SOAP response is " + entireReceive);
            Console.WriteLine("\nDetermining pass/fail");
            if (entireReceive.IndexOf("002") >= 0 &&
            entireReceive.IndexOf("004") >= 0 &&
            entireReceive.IndexOf("005") >= 0)
                Console.WriteLine("\nPass");
            else
                Console.WriteLine("\nFail");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Windows Azure Resources for Developers

This is a list of helpful resources for developers building on Windows Azure. If you know of other helpful resources, please comment to let me know and I will add them to the list.

Setup a Windows Azure Development Environment

Windows Azure SDK and Tools
To get started developing applications for Windows Azure, you need the Windows Azure SDK and Tools. The SDK includes an emulator for Windows Azure compute and storage. This will enable you to develop on your machine without having to deploy to the cloud. This capability reduces your development time and cost associated with deploying to Windows Azure for development.

Get Windows Azure

To deploy your application to Windows Azure, you will need a Windows Azure account. There are a couple of ways to get development time and resources for Windows Azure.

MSDN Windows Azure Benefits

If you are an MSDN subscriber, you can get up to $3,700 a year in free Windows Azure resources.

FREE 90-day Windows Azure Trial
If you don’t have an MSDN subscription, you can get a free 90-day trial of Windows Azure.

Learn Windows Azure

Learn Windows Azure
Microsoft’s Scott Guthrie, led a one-day “Learn Windows Azure” event in December and the recordings are all available on Channel9.

Windows Azure Training Kit
The Windows Azure Training Kit is loaded with helpful presentations, demos and hands-on labs for working with Windows Azure.

Additional Tools

SQL Azure Migration Wizard
This is an open source tool on CodePlex that helps you migrate SQL Server databases to SQL Azure.

Windows Azure PowerShell Cmdlets
The Windows Azure PowerShell Cmdlets enable you to browse, configure, and manage Windows Azure Compute and Storage services directly from PowerShell.

Red Gate Azure Development Tools
Red Gate creates multiple products that work with Windows Azure and simplifies some aspects of Windows Azure, including Cloud Storage Studio, Azure Diagnostics Manager and SQL Azure Backup.

Shows, Podcasts and Other Web Sites

Cloud Cover
Cloud Cover is your eye on the Microsoft Cloud. Join Wade and Steve as they cover the Windows Azure platform, digging into features, discussing the latest news and announcements, and sharing tips and tricks.

Simulation of Browser Caching during load tests

In a VS load test that contains Web tests, the load test attempts to simulate the caching behavior of the browser. Here are some notes on how that is done:

  • There is a property named on each request in a Web test named “Cache Control” in the Web test editor (and named “Cache” on the WebTestRequest object in the API used by coded Web tests).
  • When the Cache Control property on a request in the Web test is false, the request is always issued.
  • When the Cache Control property is true, the VS load test runtime code attempts to emulate the Internet Explorer caching behavior (with the “Automatically” setting).This includes reading and following the HTTP cache control directives.
  • The Cache Control property is automatically set to true for all dependent requests (typically for images, style sheets, etc embedded on the page).
  • In a load test, the browser caching behavior is simulated separately for each user running in the load test.
  • When a virtual user in a load test completes a Web test and a new Web test session is started to keep the user load at the same level, sometimes the load test starts simulates a “new user” with a clean cache, and sometimes the load test simulates a return user that has items cached from a previous session. This is determined by the “Percentage of New Users” property on the Scenario in the load test. The default for “Percentage of New Users” is 0.

Important Note: When running a Web test by itself (outside of the load test), the Cache Control property is automatically set to false for all dependent requests so they are always fetched; this is so that they can be displayed in the browser pane of the Web test results viewer without broken images.

Replace invalid characters with empty strings by using Regular expression

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace Billing
{
    public class StringUtils
    {
        public static String CleanInput(string str)
        {
            // Replace invalid characters with empty strings.
            return Regex.Replace(str, @"[^\w ]", "");
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

What is REST?

It is rather style or pattern of development resource-oriented web applications. Beauty of REST is that its really easy to understand and basically you are using REST everyday but may not noticing that. REST works on top of HTTP protocol, but is is not protocol itself. It seems to me that it actually appears with HTTP/1.1 but only with Roy Fieldingwork it became well understood, defined and attractive.

REST popularized by such applications as twitter, flickr, bloglines, technorati etc. And of cause, by Ruby On Railsframework.

REST vs. SOAP

Sure, REST is not first who approaches issue of using recourses in Web, it rather trendier new kind in a block. We know bunch of web technologies, SOAP, WSDL, ATOM, WS-*, WCF, ODATA and many many more.. So, what are the difference?

Major difference is that all above are protocols, but REST is style. This has pros and cons. Protocol’s are more strict and heavyweight, with a number of rules, formats etc. SOAP is using XML as data exchange format, REST could work any format depending on client needs. SOAP is using its own security model, REST relies on HTTP and web server security. SOAP requires tools, REST learning curve is small and less less reliance on tools. SOAP designed to handle distributed computing environments, REST assumes a point-to-point communication model.

But my opinion is simplicity always win against complexity. Key popularity of REST is because is simple, easy understand by developers and as a result – implemented in applications. My believe that SOAP and other heavyweight protocols will slightly die more and applications will be using REST.

 ASP.net MVC and REST

Developers of ASP.net MVC framework designed it to be REST compatible. In the level of framework, there is an URL routing system (System.Web.Routing) that allows you easily follow REST design principles. It gives you total control over your URL schema and its mapping to your controllers and actions, with no need to conform to any predefined pattern.

So, basically ASP.net MVC web applications development is: create a controller class (LoginController for instance), implement number of actions (Index, CheckCredentials) and map those actions to particular URL. For instance http://mysite.com/login mapped to LoginController.Index method, that handles GET request from server and return View, containing Login form. http://mysite.com/login/check mapped toLoginController.CheckCredentialsmethod, that handles POST and checks users credentials.

It is much more easier to create web applications API’s with MVC framework. TheActionResult is polymorphic, so it could return HTML, JSON, XML results (and you are free to implement own ActionResult, for any format you might need).

How to: Collect Event Tracing for Windows (ETW) Data

Event Tracing for Windows (ETW) is an efficient kernel-level tracing facility that enables profiler log kernel or application-defined events. The data that is collected from the event provider can be viewed only by using the /Summary:ETW option of the VSPerfReport command-line tool. You can use this report to determine where performance issues occur in the application.

To enable event trace providers
  1. In Performance Explorer, right-click the performance session, and then click Properties.

  2. In the Property Pages, click the Windows Events properties.

  3. In the Select event trace provider to collect data from list, select the event providers that you want to use to profile your application.

Visual Studio 2010 Diagnostic Tool

Visual Studio 2010 add-ins

Productivity Power Tools

  • No More Extension Resets – This version of the Productivity Power Tools will be the last which resets the extensions.
  • Find – Quick find & incremental search now pops up at top right-hand corner of the editor.
  • Enhanced Scrollbar – Icons overlay the scrollbar to show edits, breakpoints, bookmarks, errors, warnings, etc.
  • Middle-Click Scrolling – Use your scroll wheel to quickly scroll through your document.
  • Organize Imports for Visual Basic – Sort the imports logically and remove the ones that aren’t being used.

    Regex Editor

    JScript Editor Extensions

    PowerCommands for Visual Studio 2010

    Microsoft All-In-One Code Framework Sample Browser

    PHP Language Support

  • ASP.NET error CS0016: Could not write to output file

    If you attempt to run an ASP.NET application hosted on IIS7.0 running on Windows Home Basic or Premium (Vista or Windows 7, x86 or x64), you may receive the following error:

    error CS0016: Could not write to output file 

    The problem occurs because Windows Home Basic and Premium lack Windows Authentication. You can solve this problem with a few mouse clicks:

    1.  Run the Internet Information Services (IIS) Manager program.  It can be found in the Start > Administrative Tools menu.  You may have to edit the Start Menu properties to show the Administrative Tools folder.

    2.  Select the Application Pools item in the Connections pane.

    3.  Right-click on the application pool in which you are running your ASP.NET application.  On my PC, this was the DefaultAppPool.

    4.  Select Advanced Settings from the popup menu.

    5.  In the Process Model section, set the Identity to LocalSystem.  Click the OK button.

    Freely Available .NET Libraries

    Ajax

    • Ajax Control Toolkit – Microsoft
    • AJAXNet Pro
    • ASP.NET MVC Project Awesome – a rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form and Pager. Thanks Omu (April 20, 2011)

    Build Tools

    • Prebuild – Generate project files for all VS version, including major IDE’s and tools like SharpDevelop, MonoDevelop, NAnt and Autotools
    • Genuilder – Precompiler which lets you transform your source code during the build. Thanks Harry McIntyre (April 13, 2011)

    Charting/Graphics

    Collections/Generics

    • PowerCollections – is a library that provides generic collection classes that are not available in the .NET framework. Some of the collections included are the Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary, Set, OrderedSet, and OrderedMultiDictionary. Thanks Adam Ralph (April 20, 2011)

    Compression

    Controls

    • Krypton – Free winform controls. Link fixed (April 14, 2011)
    • Source Grid – A Grid control
    • DevExpress – Over 60 Free Controls from DevExpress. Thanks Florian Standhartinger (April 20, 2011)
    • ObjectListView – is a C# wrapper around a .NET ListView. It makes the ListView much easier to use and provides some neat extra functionality. Thanks Florian Standhartinger (April 20, 2011)

    Data Mapper

    Dependency Injection/Inversion of Control

    Design by Contract

    IDE

    • SharpDevelop – is a free IDE for C#, VB.NET and Boo projects. Thanks Florian Standhartinger (April 20, 2011).

    Logging

    ORM

    PDF Creators/Generators

    Automated Web Testing

    Misc Testing/Qualitysupport/Behavoir Driven Development (BDD)

    URL Rewriting

    MS Word/Excel Documents Manipulation

    • DocX to create, read, manipulate formatted word documents. Easy syntax, working nicely, actively developed. No Microsoft Office necessary.
    • Excel XML Writer allows creation of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated. It also provides code generator to create code from already created XLS file (saved as xml). Haven’t tested this but looks very promising. Too bad author is long time gone.
    • Excel Reader allows creation/reading of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated.
    • Excel Package allows creation/reading of .XLSX (Excel 2007) files. No Microsoft Office necessary. Author is gone so it’s out of date.
    • EPPlus is based on Excel Package and allows creation/reading of .XLSX (Excel 2007). It is actually the most advanced even comparing to NPOI.
    • NPOI is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project which can help you read/write xls, doc, ppt files.
    • sharp2word – a Word 2003 XML Documents Generator from C# code without any components or libraries. Thanks dublicator (April 20, 2011)
    • ClosedXML – an actively developed library for generating OpenXML Excel files. Thanks Joseph Robichaud (April 26, 2011)

    Serialization

    • sharpserializer – xml/binary serializer for wpf, asp.net and silverlight
    • Protobuf.NET – fastest serialization port protobuf format into .NET platform. Thanks slava pocheptsov (April 26, 2011)

    Silverlight

    Social Media

    • LinqToTwitter – Linq-based wrapper for all Twitter API functionality in C#
    • Facebook C# SDK – A toolkit for creating facebook applications / integrating websites with Facebook using the new Graph API or the old rest API.

    Package managers for external libraries

    • NuGet (formerly known as NuPack) – Microsoft (developer-focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development)
    • OpenWrap – Sebastien Lambla – Open Source Dependency Manager for .net applications

    Unit Testing/Mocking

    Validation

    Threading

    • Smart Thread Pool – Thread Pool management library
    • Retlang – a high performance C# threading library. Thanks MarcBot (April 13, 2011)
    • bbv.Common – an open source library of software components that makes building multi-threaded, event-based and loosely coupled systems easy. Thanks Urs Enzler (April 14, 2011)
    • PowerThreading – a llibrary (DLL) containing many classes to help with threading and asynchronous programming. Thanks Adam Ralph (April 20, 2011)

    Unclassified

    • CSLA Framework – Business Objects Framework
    • AForge.net – AI, computer vision, genetic algorithms, machine learning
    • Prism – Composit UI application block for WPF, Silverlight and WP7 – Microsoft patterns & practices
    • Enterprise Library 5.0 – Logging, Exception Management, Caching, Cryptography, Data Access, Validation, Security, Policy Injection – Microsoft patterns & practices
    • File helpers library
    • C5 Collections – Collections for .NET
    • Quartz.NET – Enterprise Job Scheduler for .NET Platform
    • MiscUtil – Utilities by Jon Skeet
    • Noda Time – DateTime replacement (idomatic port of Joda Time from Java)
    • Lucene.net – Text indexing and searching
    • Json.NET – Linq over JSON
    • Flee – expression evaluator
    • PostSharp – AOP
    • IKVM – brings the extensive world of Java libraries to .NET.
    • C# Webserver – Embeddable webserver
    • Long Path – Microsoft
    • .NET Engines for the GOLD Parsing System
    • NCQRS – library for event-driven architectures (CQRS).
    • Reactive Extensions for .NET – a library for composing asynchronous and event-based programs using observable collections. Thanks steve (April 14, 2011)
    • Mono.GameMath – a project to develop a highly-performant math library for games, based on XNA APIs. Thanks Alex Rønne Petersen (April 14, 2011)
    • SLSharp – a runtime IL-to-GLSL translation engine, allowing people to write GLSL shaders as C# code. Thanks Alex Rønne Petersen (April 14, 2011)
    • InfusionSoftDotNet – a dll to ease the pain for .Net developers to access the InfusionSoft API. Thanks Michael Gibbs (April 20, 2011)
    • re-mix – provides mixins for C# and Visual Basic .NET. Thanks Stefan Papp(April 20, 2011)
    • Mono.Cecil – a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format. Thanks Florian Standhartinger(April 20, 2011)
    • ImapX – is an modern .NET 2.0 library for management of IMAP folders, supports SSL Connection and different IMAP formats, such as Gmail IMAP, AOL IMAP (November 30, 2011)

    LINQPad

    LINQPad – A free stand-alone LINQ editor/tester created by Joseph Albahari, author of C# 3.0 in a Nutshell. LINQPad is like SQL Query Analyzer, but for LINQ.

    One of the major additions to the Microsoft .NET Framework 3.5 is LINQ, a set of classes and language enhancements designed to offer a universal data-querying syntax. With LINQ to Objects, LINQ to XML, and LINQ to SQL, you can query arrays and collections, XML documents, and database tables using a similar syntax with rich features like IntelliSense and compile-time type checking. LINQ syntax, however, can be downright confusing for developers who have spent the better part of their programming careers using SQL to query data.

    LINQPad’s user interface is divided into four panes. The upper-left pane presents a list of database servers, which you can drill into to view the databases and their tables, views, and stored procedures. To test a LINQ query, type it into the top-right pane. You can enter a LINQ query directly or type in the C# or Visual Basic code that executes a LINQ query. When writing and testing LINQ to SQL queries, you can select the database from the upper-left pane to query against.

    The bottom-right pane displays the results of the query. There are three views: the results, the corresponding lambda expression, and an equivalent SQL statement. The bottom-left pane serves as a workspace to organize your frequently used queries. This pane also includes a Samples tab with more than 200 C# and Visual Basic LINQ examples from Albahari’s book, C# 3.0 in a Nutshell (O’Reilly, 2007). For those new to LINQ, these examples are invaluable learning tools, as is the ability to view the LINQ query’s equivalent SQL statement.

    You can think of LINQPad as a scaled-down, LINQ-based implementation of SQL Server®Management Studio. When writing a SQL query to display data in an application, it is usually easier to write the query in Management Studio and then copy and paste it into your code in Visual Studio than it is to write the query from scratch in Visual Studio. This is due to the fact that testing the query from Visual Studio requires running the application. Much in the same manner, I find it easier to write and test my LINQ queries in LINQPad.

    While the LINQPad editor color codes keywords, variables, strings, and comments and underlines errors with red or blue squiggly lines just as Visual Studio does, it does not yet support IntelliSense. (This is a planned future enhancement.) Despite the lack of IntelliSense, LINQPad’s intuitive and lightweight user interface, its many features, and the plethora of examples make it an excellent tool for learning, writing, and testing LINQ queries.

    LINQPad

    http://www.albahari.com/nutshell/