Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework. November 2013 Entries
LINQ performace considerations
Outside of LINQ statements such as .Any(predicate) and .First(predicate) short circuiting execution when a matching element is found, the library does not inherently do any underlying optimizations due to the limits of what is available to it. Since LINQ only works with IEnumerables, the only thing that can be done is to loop through the elements in the collection, therefore, no index access, saving of local properties such as Length, etc. is possible. It is important to keep in mind that each time ......

Posted On Thursday, November 21, 2013 4:30 PM

Cyclomatic Complexity of Methods
Cyclomatic Complexity is a widely used software metric that is used to compute the number of decisions being made by a piece of code. In its simplest form, the complexity number is equal to: 1 + {the number of expressions in the method}. Different tools interpret the definition of “expressions” differently, thus the slightly varying metrics based on the tool being used, but in general the statement used for making decisions are counted.In general, the following are treated as expressions in C#: if, ......

Posted On Thursday, November 21, 2013 12:41 PM

Breaking on Exception with Debugger
Here are the steps you need to take to get this feature enabled in your local Visual Studio instance: 1. First select Ctrl+Alt+E, or Debug à Exceptions, to bring up the Exceptions dialog 2. Make sure that all of the check-boxes in the “User-unhandled” column are checked a. Specifically the “Common Language Runtime Exceptions” box must be checked 3. If you see this column, you are done. If not, please continue on to the next steps. 4. Close the Exceptions dialog and select Debug à Options and Settings. ......

Posted On Thursday, November 21, 2013 12:25 PM

Testing Workflow Events
Imagine you are testing a method that returns or processes a Workflow event. Normally, you would generate a fake instance of the class and insert it into the method using Moq. However, creating a fake Workflow event is difficult, as Workflow events do not expose any public constructors. You can generate Workflow events using Microsoft.Activities.UnitTe... Note: this is a package that must be installed. Here is an example of generating “WorkflowApplicationComplet... Basically, run a workflow ......

Posted On Thursday, November 21, 2013 12:12 PM

Unit tests for HttpClient using HttpMessageHandler
You can unit test a class that uses HttpClient by giving that HttpClient a mock HttpMessageHandler. This way, you can capture the request and prevent it from actually going over the wire. Here is an example using Moq. HttpClient depends on HttpMessageHandler’s SendAsync() method, so give SendAsync() a stub implementation and use Moq’s Callback() to capture arguments. var handler = new Mock<HttpMessageHandler&... handler.Protected() .Setup<Task<HttpRespo... ......

Posted On Wednesday, November 20, 2013 4:32 PM

Properties vs. Methods
One of the decisions a developer needs to make while designing a class is when to use a property and when to use a method. Methods typically represent an action or an operation whereas, properties represent pieces of data associated with a class / instance. Properties are typically used to allow accessibility (getting and/or setting) to private class fields. Cases where the use of a property is recommended: Ø When the member represents a logical attribute of the type. E.g. Message is a property of ......

Posted On Wednesday, November 20, 2013 4:31 PM

Usage of Arrays
Although both arrays and collections are used in a similar fashion, there are some performance considerations when choosing one over the other. Below are some design guidelines: 1- You should not return an internal instance of an array. This allows calling code to change the array. The following example demonstrates how the array delimiters can be altered by the calling code. public sealed class DocParser { private DocParser(){} private static char[] delimiters = {',', '-', ' '} public char[] Delimiters ......

Posted On Wednesday, November 20, 2013 4:29 PM

Unit Testing Non-Public Methods
Before we proceed any further, I should say this, Testing through this public API should be your first choice.Alternative for Abstract Base Classes One common case is when an abstract base class defines functionality in some protected methods, and there are a series of inheriting classes using those methods without overriding them. In this case, rather than choosing one inheriting member at random to test the methods, you can simply create a “Fake” class locally in your test project that inherits ......

Posted On Wednesday, November 20, 2013 4:03 PM

Assembly Initialize
AssemblyInitialize is very similar to the ClassInitialize and TestInitialize attributes, but rather than executing before classes/methods are run it executes before the any method marked with TestMethod, ClassInitialize, or TestInitialize inside this assembly. Only one method in an assembly can be annotated with this attribute. Code that belongs in the method decorated with AssemblyInitialize is any code that sets up shared resources that are used by tests across the assembly. Tests should not change ......

Posted On Monday, November 18, 2013 7:13 PM

Use of Byte/Short
In terms of performance some developers jump to the conclusion that Byte and Short would be generally more efficient since they require less room on the stack, but actually this is a common misnomer. Int32 (int) is actually more efficient than both Int16 (short) and Byte (byte) in most situations due to the fact that modern processors are optimized for use of 32 and 64 bit values. When a short (16 bit) or byte (8 bit) is read, the processor must read the entire 32 bits anyway and then apply a mask ......

Posted On Monday, November 18, 2013 7:11 PM

Deferred Execution with LINQ
One of the best features of LINQ is the fact that it is lazy. Lazy or Deferred Execution allows you to specify all the conditions of your LINQ statement (Where, OrderBy, Select, etc), without actually executing those functions on the given collection until the results are needed. An example of where you can see this lazy execution in action is when using the Visual Studio Debugger. Let’s say you have an IEnumerable<int> that you want to execute a LINQ statement on and inspect the resulting ......

Posted On Monday, November 18, 2013 6:56 PM

Returning Multiple Values from a Method
As a developer, you have probably run into the situation where you want to return more than 1 value from a method. Even though this can often be a flag for bad function design, there are certain cases where returning 2+ values makes sense. In order to accomplish this functionality in other programming languages like Java, you often would have to create a Data Transfer Object which can become a pain and feel unnecessary. Fortunately C# provides a couple different ways to have “multiple return values”. ......

Posted On Monday, November 18, 2013 6:54 PM

LINQ in Performance Intensive Situations
As most of you know LINQ provides a set of great extension methods for common functions on .NET Collections. In most cases LINQ is simply the “prettier”, abstracted out implementations of the lower level .NET language features like loops and conditionals. Even though LINQ often increases readability, it does come with a little more overhead. This additional overhead is negligible in most cases, but when performance is a primary concern in your function every millisecond counts. In these scenarios, ......

Posted On Monday, November 18, 2013 6:42 PM

Filtering Duplicates from a Collection with LINQ
Often times there are requirements to ensure there are no duplicate entries in a collection. If you are familiar with SQL you would probably immediately think of the “distinct” keyword. LINQ also provides a Distinct() method that uses an objects Equals() method to test equality. IEnumerable<int> intArr = new[] { 1, 2, 2, 3 }; intArr = intArr.Distinct(); //Has size 3 This works great for value types, common reference types (like string), and for classes where you have access to override the ......

Posted On Monday, November 18, 2013 6:34 PM

Flattening Collection Hierarchies with LINQ
Ever run into the situation where you want to retrieve a single collection of objects from a hierarchy like the one below? IEnumerable<ClassA> { ClassA{ IEnumerable<ClassB> } } The first thing most people try is to use the LINQ Select () statement like so: var classBCollection = classACollection.Select(a => a.ClassBCollection); But when inspecting the type of classBCollection, we see it has type IEnumerable<IEnumerable&... and NOT the desired type of simply IEnumerable<ClassB>. ......

Posted On Monday, November 18, 2013 6:33 PM

Moq – Return a Parameter
Moq provides an additional overload for the Returns method that takes a lambda expression with the same parameters as the method signature. When this overload is used, Moq will inject the parameters passed to the Setup method into the Returns as its lambda expression parameters. Note: The parameters for the lambda expression must match up in both number and ordering to the method signature. Example 1: public interface ITestInterface { string SomeMethod(string str); } … mockTestInterface.Setup(i => ......

Posted On Monday, November 18, 2013 6:27 PM

.Single() vs. .SingleOrDefault()
The goal of both the Single and SingleOrDefault methods is the same: get one element in the collection that matches the provided predicate. The difference between the two lies in their behavior when no matching element is found. The Single method will throw an error saying something like “Sequence contains no elements”, while the SingleOrDefault() method will return the default value of the collection’s type. For reference types and nullable, it will return null and for value types it will return ......

Posted On Monday, November 18, 2013 6:17 PM

.Any() vs. .Count() > 0
The Any method is an expression that will check the collection that was called on to see if there are “any” elements matching the given criteria. Criteria can be provided as a predicate (function/lambda expression resulting in a Boolean value) to the Any method as a parameter. When no parameters are provided, .Any() checks to see if there are elements in the collection. For this reason, .Any() is preferred over .Count() > 0 ......

Posted On Monday, November 18, 2013 6:13 PM

Test Initialize vs. Class Initialize
One common oversight we have encountered while working with developers is the mix up of the [TestInitialize] and [ClassInitialize] Attributes. When using these methods, be conscience of their differences. The Class Initialize attribute executes the decorated method once before the first test in the class is run, while the Test Initialize attribute executes before each test is run. There are different scenarios for when to use each, and putting code incorrectly in one or the other can cause unexpected ......

Posted On Monday, November 18, 2013 6:10 PM

Media Type Formatter Exception
Have you seen this error message when making a call to a Web API Service Endpoint? No MediaTypeFormatter is available to read an object of type ‘' from content with media type 'text/html'. Unfortunately this is a very misleading error message and developers complain about it a good amount. Most of the time it means that some sort of error occurred during your Service call back to the Web API. The caller is expecting a response of type XML or JSON so it can deserialize it back into the response object, ......

Posted On Monday, November 18, 2013 1:02 PM

Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net