Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 28 March 2016

Files still read-only when refactoring using ReSharper

Problem

ReSharper refactoring operations fail in Visual Studio with the message:

Refactoring Failed

Files still read-only:

Here is an example:

image

This occured with ReSharper Ultimate v10.0.2 and Visual Studio Community Edition 2013 (Version 12.0.300101.00) and the .

Solution

In Visual Studio go to Tools > Options > Source Control > Plug-in Selection and set the source control plug-in to None.

image

Sunday, 20 July 2014

Null-coalescing operator in C#

It feels like I’ve been using C# forever. When you’ve been doing something for a long time it’s easy to fall into habits and miss or forget about techniques that could make your life a little easier so it doesn’t hurt to remind ourselves of things from time to time.

I have used many DI containers like Spring.Net, Unity, NInject etc. but I recently started using StructureMap for the first time. I added it to an MVC project using NuGet and when I looked at the code that had been added to my project I saw code like this:

protected override IEnumerable<object> DoGetAllInstances(Type serviceType) 
{
	return (this.CurrentNestedContainer ?? this.Container).GetAllInstances(serviceType).Cast<object>();
}

It really struck me that I couldn’t remember the last time I used the null-coalescing operator (??). Some quick revision:

“The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.” [1]

The C# Reference goes on to describe more features of the ?? operator:

  • You can use the ?? operator’s syntactic expressiveness to return an appropriate value when the left operand has a nullable type whose value is null.
  • If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error.
  • If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.
  • The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

So, by way of example, the following statements are all equivalent:

return nullableValue ?? someOtherValue;

return nullableValue != null ? nullableValue : someOtherValue;

if(nullableValue != null)
{
    return nullableValue;
}
else
{
    return someOtherValue;
}

References

Sunday, 20 July 2014

Friday, 9 March 2012

Login failure when accessing Active Directory

I hate wasting time, especially when it’s because of an obvious error that’s staring me in the face but I just can’t see it. Well, it happened today so I thought I’d make a note so it never happens again. Take the following code:

var principalContext = new PrincipalContext(ContextType.Domain, domain);
var validated = principalContext.ValidateCredentials(userName, password);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);

My problem was that an exception was being thrown on the last line. “How is this possible?” I asked myself. “The call to ValidateCredentials worked so why the error on FindByIdentity?”

Firstly, the exception:

Exception thrown autenticating the user.
System.DirectoryServices.DirectoryServicesCOMException (0x8007052E): Logon failure: unknown user name or bad password.

   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_AdsObject()
   at System.DirectoryServices.PropertyValueCollection.PopulateList()
   at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
   at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
   at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
   at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
   at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
   at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue)
   at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
   at GL.AnglianWater.WIRM.Core.Membership.LdapAuthentication.Authenticate(String userName, String password, String domain, String requiredGroup)

Drilling into the exception details in Visual Studio 2010 yielded a bit more information:

ExtendedError = -2146893044
ExtendedErrorMessage = "8009030C: LdapErr: DSID-0C0904DC, comment: AcceptSecurityContext error, data 52e, v1db1"

After scratching my head for an age the solution turned out to be so obvious as to be embarrassing; simply create the PrincipleContext by passing in the username and password too:

var principalContext = new PrincipalContext(ContextType.Domain, domain, userName, password);
var validated = principalContext.ValidateCredentials(userName, password);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);

Doh!

Sunday, 12 June 2011

A few useful exception types

Sometimes it’s useful to throw exceptions from your code, for example if an incoming method argument is incorrect for some reason. Throwing Exception isn’t very specific so what should we throw and when? Here’s a quick aide-mémoire for a few exception types I use:

Exception type When to use it
ArgumentException The exception that is thrown when one of the arguments provided to a method is not valid.
InvalidOperationException The exception that is thrown when a method call is invalid for the object's current state.
FormatException The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.
NotImplementedException The exception that is thrown when a requested method or operation is not implemented.

References

http://msdn.microsoft.com/en-us/library/system.systemexception.aspx
Sunday, 12 June 2011,

Thursday, 3 March 2011

Properties versus direct access to fields

I was recently required to pick up some legacy code that included public fields along these lines:
public class SomeClass
{
    public int someInt;

    // ... snip ...
}
I have grown used to using auto-implemented properties under such circumstances:
public class SomeClass
{
    public int SomeInt { get; set; }

    // ... snip ...
}
To make matters worse different classes had different casing so sometimes public fields started with a capital and sometimes not (trivial but annoying). After my initial gasps of horror I got to thinking about the difference between exposing fields directly versus using properties. What really are the pros and cons?
MSDN describes properties in the following terms:
“A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.”
It turns out that Jeff Atwood is quite opinionated about the subject. Jeff acknowledges some arguments in favour of using properties over fields such as the following:
  • Reflection works differently on fields than on properties. If you rely on reflection properties are a more natural fit.
  • You can't databind against a field.
  • Changing a field to a property is a breaking change requiring client code to be recompiled.
I also think that using a property signifies intent; it identifies that you intended the encapsulated field to be exposed outside the class. In effect by using a property you are declaring part of a contract, which is probably why you can declare properties in interfaces. This opinion seems to be confirmed by Jon Skeet:
“A property communicates the idea of "I will make a value available to you, or accept a value from you." It's not an implementation concept, it's an interface concept. A field, on the other hand, communicates the implementation - it says "this type represents a value in this very specific way". There's no encapsulation, it's the bare storage format. This is part of the reason fields aren't part of interfaces - they don't belong there, as they talk about how something is achieved rather than what is achieved.” - http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx
Properties also allow you to use combined access modifiers should you need to (note the private setter here):
public class SomeClass
{
    public int SomeInt { get; private set; }

    // ... snip ...
}
More verbose than simple public fields they may be, but I like properties.
Thursday, 3 March 2011,

Friday, 3 September 2010

When to use delegates

I was recently asked to describe delegates and when they should be used. As is often the case with simple questions like this trying to explain what I know got me in a bit of a knot, so…

Read A reminder about delegates first!

MSDN has an interesting little article about When to Use Delegates Instead of Interfaces. This draws a parallel between interfaces and delegates that I hadn’t considered before. The article states:

“Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method.”

It goes on to suggest that a delegate should be used when:

  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.

It also occurred to me that delegates could be used to implement the coroutine pattern by exposing an IEnumerable of Action types.

The MSDN article goes on to suggest that Interfaces should be used when:

  • There is a group of related methods that may be called.
  • A class only needs one implementation of the method.
  • The class using the interface will want to cast that interface to other interface or class types.
  • The method being implemented is linked to the type or identity of the class: for example, comparison methods.
Friday, 3 September 2010

Friday, 23 July 2010

A reminder about boxing and unboxing in C#

Here is a quick reminder about boxing and unboxing in C#. MSDN documentation contains this concise description of boxing and unboxing:

“Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.” *

All primitive types (byte, char, int, long, etc.) and structures are value-based types derived from System.ValueType. Because value types are stored on the Stack they can be created and accessed more efficiently than reference types. Reference types are stored on the Heap and must be accessed using references.

An example of boxing and unboxing:

int i = 123;
object o = (object)i; // boxing
int j = (int)o; // unboxing

Why is this important?

Boxing and unboxing operations are computationally expensive in relation to other simple assignments (for example, when a value type is boxed, a new object must be allocated and constructed). If you have code which undertakes a lot of boxing operations you may run into performance issues.

Determining which methods and properties will cause boxing is possible by checking their their signatures. If a method takes an argument of type object or the argument is an interface then if you were to pass in a value type instance it will be boxed.

Note it is very easy to slip into boxing operations:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("Boxing: {0}, {1}", i, i + 1); // Boxing here   
}

You could get around this by calling the ToString() method early to prevent allocation on the heap:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("No boxing: {0}, {1}", i.ToString(), (i + 1).ToString()); // No boxing   
}

Value types and reference types

Again MSDN documentation provides a description of value types:

“Variables that are based on value types directly contain a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.” **

There are 2 main categories of value types:

  • Structs (e.g. numeric types: integral types, floating-point types and decimal; bool; user defined structs)
  • Enumerations

In essence, value types are lightweight objects that are allocated on the current thread's stack (see Stack and heap below). There are exceptions to this (e.g. when a value type is allocated as an element of an array or is a field of a reference type). When an instance of a value-type is created a single space in memory is allocated to store the value. When instantiating a reference type an object is created in memory and is handled through a reference (somewhat like a pointer).

Stack and heap

The Stack can be thought of as being responsible for keeping track of what's executing in the code (the call stack). When a method is called (a Frame) data is pushed onto the Stack. Once the method executes the data is popped off the Stack and is discarded. Only the ‘top’ item is available in the Stack (typical behaviour for a stack being a last-in-first-out memory structure).

The Heap can be thought of as being responsible for keeping track of the objects referenced by the code. Any element in the Heap can be accessed directly.

Garbage collection

The Stack does not require garbage collection. It is self-maintaining because items are popped off the stack and discarded as they are used during program execution. On the other hand the Heap is subject to garbage collection.

* Boxing and Unboxing (C# Programming Guide)
** Value Types (C# Reference)

Friday, 23 July 2010

Monday, 3 May 2010

Features new to C# 4

Here’s a smattering of what’s new in C# 4.

Dynamic support

There is a new keyword – dynamic. This keyword allows you to create dynamic objects and let their types (and therefore operations) be determined at run time. This feature facilitates interoperability with other languages including dynamic languages and COM Interop.

The dynamic keyword is easy to use:

dynamic myObject = new SomeObject();
myObject.MyProperty = "SomeValue";
myObject.DoSomething();

Note that with dynamic objects the compiler won’t catch typos in member names etc. Everything is evaluated at runtime.

“The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).” - http://msdn.microsoft.com/en-us/library/dd264736%28VS.100%29.aspx

There is also a new ExpandoObject class (part of the DLR):

“The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").” - http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28VS.100%29.aspx

You can just add new members on the fly to ExpandoObject instances:

dynamic sampleObject = new ExpandoObject();
sampleObject.test = “Dynamic Property”;

Optional/default parameters

This language feature enables you to specify a parameter value to be used if the parameter is omitted from a call.

Example method declaration:

public static void SomeMethod(int optional = 0) { }

Example method calls:

SomeMethod(); // 0 is used in the method.
SomeMethod(10);

This might be useful with MVC action methods where previously nullable parameters were used for optional URL parameters.

Named arguments

This language feature could be useful in conjunction with optional parameters.

“Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.” - (my italics) http://msdn.microsoft.com/en-us/library/dd264739%28VS.100%29.aspx

Example method declaration:

public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)

Example method calls:

anExample.ExampleMethod(3); // one required parameter, 2 optional

anExample.ExampleMethod(3, optionalint: 4); anExample.ExampleMethod(3, optionalstr: “test”); anExample.ExampleMethod(3, optionalint: 4, optionalstr: “test”);

Covariance and contravariance

Covariance enables you to use a more derived type than that specified by the generic parameter, whereas contravariance enables you to use a less derived type.

See http://msdn.microsoft.com/en-us/library/ee207183.aspx.

See also http://msdn.microsoft.com/en-us/library/dd469484.aspx for the in keyword and http://msdn.microsoft.com/en-us/library/dd469487.aspx for the out keyword.

Explained nicely in this web cast: http://channel9.msdn.com/posts/bruceky/Whirlwind-13-Whats-new-in-C-4-Covariance--Contravariance/.

Tuesday, 3 November 2009

Assembly resource URI format

I can never remember the URI format for resources embedded in assemblies.  So:

assembly://<assemblyname>/<namespace>/<resource>

The <namespace> part can include folder names separated from the base assembly namespace by dots (.). For example a Spring configuration file located in a SpringConfig folder for an application with a default namespace of Mail.Merge.Console would have a resource definition of:

assembly://Mail.Merge.Console/Mail.Merge.Console.SpringConfig/SpringDataAccess.xml

Friday, 16 October 2009

Func and Action

Func(TResult) is a delegate type that encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
MSDN documentation states:
“You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.”
The documentation goes on to point out that if you need a delegate type that does not have a return type use Action instead.
There are 4 further delegate types related to Func(TResult):
  • Func(T, TResult)
  • Func(T1, T2, TResult)
  • Func(T1, T2, T3, TResult)
  • Func(T1, T2, T3, T4, TResult)
Each of these encapsulates a method that takes one or more parameters of various types and which returns TResult.
There are equivalent Action types for encapsulating delegates that do not have a return type.
This is all very interesting when you consider you can assign a lambda expression to a Func, e.g.
Func<int, int, int> function = (a,b) => a + b;
…and that you can also create an Expression from a lambda represented as a Func.
Expression<Func<int, int, int>> expression = (a,b) => a + b;
More to follow on Expression.
Friday, 16 October 2009,

A reminder about delegates

A delegate is a reference type used to encapsulate a method with a specific signature and return type. You can encapsulate any matching method in that delegate.

From MSDN documentation:

“A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value…

…Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.”

The documentation goes on to state that delegates have the following properties (and others):

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.

Delegate creation syntax:

// define the delegate
public delegate void MyDelegate(object sender, EventArgs e);

// The public member variable myDelegate is an instance of a MyDelegate delegate
public MyDelegate myDelegate;

// assign method SomeMethod to myDelegate
myDelegate = SomeMethod(object myObject, new EventArgs());

Note that this removes any previously assigned methods from the delegate and assigns the new one. You can use an alternative syntax to add more than one method to a delegate. You can then execute all methods in one delegate call:

public delegate  void MyDelegate(object sender, EventArgs e);
public MyDelegate myDelegate;
 
myDelegate += SomeMethod(object myObject, new EventArgs()); 
myDelegate += SomeOtherMethod(object myObject, new EventArgs());
 
//Call both methods
myDelegate(obj, args);

Events

The event keyword restricts how delegates are used. Events are delegates that:

  • Can only be registered with += and not with the assignment operator (=)
  • Can only be called by methods of the class that defines the event
public delegate  void MyDelegate(object sender, EventArgs e);
public event MyDelegate myDelegate;
 
myDelegate += SomeMethod(object myObject, new EventArgs()); 
myDelegate += SomeOtherMethod(object myObject, new EventArgs());

// Compilation error here! Can't asign to an event.
myDelegate = YetAnotherMethod(object myObject, new EventArgs());
 
//Call both methods
myDelegate(obj, args);

Thursday, 17 September 2009

Defining closed vs open generic types

Generic types can be open or closed. A closed generic type is defined as follows:
"A constructed generic type that has no unspecified generic type parameters, either of its own of or any enclosing types or methods. Closed generic types can be instantiated. See also: constructed generic type, generics, generic type, generic type parameter, open generic type."
Conversely an open generic type is defined as follows:
"A constructed generic type in which one or more of the generic type arguments substituted for its generic type parameters is a type parameter of an enclosing generic type or method. Open generic types cannot be instantiated. See also: closed generic type, constructed generic type, generics, generic type argument, generic type parameter."
So, IList<Person> is a closed generic type, IList<T> is an open generic type.
Thursday, 17 September 2009,