Office 365( O365 ) – Client application registration, authentication and authorization


I am currently working on a client side application (console app) that needs to connect to a O365 site and do some stuff with CSOM.

In this post I will write some basic things you need to do in order to achieve a connection to an O365 site. In my case I am working with a console app but this can be a powershell app also.

At first I recommend you look at this piece of code which you need to use to achieve the communication and authentication with O365:

A basic C# code to connecto O365 and do get a list and its items would look like this:

Uri siteUri = new Uri(ConfigurationManager.AppSettings["SiteCollectionRequests_SiteUrl"]);

 //Get the realm for the URL
 string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);

 //Get the access token for the URL.
 //Requires this app to be registered with the tenant
 string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;

 //Get client context with access token
 using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))

 // Set the time out as high as possible
 ctx.RequestTimeout = int.MaxValue;

 List list = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SiteCollectionRequests_List"]);
 CamlQuery camlQuery = new CamlQuery();
 camlQuery.ViewXml = "your CAML query here";
 ListItemCollection listItems = list.GetItems(camlQuery);

 var itemsCount = listItems.Count;

So before you can use your code you need to do two things in your target site:

  1. Register you client side app. This basically means that in your app config you need to set a clientID and a client secret. Without these values no proper authentication and authorization can done.
    1. Register you app in O365 by using the following URL and replacing the hostname and adding your target site: http://<SharePointWebsite>/_layouts/15/AppRegNew.aspx
  2. After you register the app you need to need to specify in a target site what kind of privileges the app has. In the code sample above you would need to specify at least read rights.
    1. To provide privileges the following url: http://<SharePointWebsite>/_layouts/15/AppInv.aspx
    2. Notice that for this step you need to provide a XML describing the privileges request. The simples way for me was to start up Visual Studio, create an app and define the rights request through the GUI and copy & pasting the XML from the AppMenifest.xml. It would look something like this:
      1. <AppPermissionRequests AllowAppOnlyPolicy=”true”>
        <AppPermissionRequest Scope=”http://sharepoint/content/sitecollection/web/list&#8221; Right=”FullControl” />

Also the last thing which you need to check is to have a proper configurations in the app.config(if you are using an console app):

 <add key="ClientId" value="client id obtained after registration" />
 <add key="ClientSecret" value="client secrect after registration" />
 <add key="SiteCollectionRequests_SiteUrl" value="yoursiteurl"/>
 <add key="SiteCollectionRequests_List" value="listname" />


Also notice that the ClientId and the ClientSecret have to be provided in the app.config for the TokenHelper.cs class to work. The class will search for these settings values automatically.

Additional help here:

Lessons learned from WebAPI and MVC Implementations

My Notes on a painful journey to learn, make and publish a Azure hosted MVC, Sinlge-Page application, Android client app and a WebAPI working with-one another. Software technology can be real pain in the ass!!!

JSON and Self referencing loop

If you get the following error:

Self referencing loop detected for property ‘your model’ with type ‘System.Data.Entity.DynamicProxies


Loop Reference handling in Web API

My Solution:

I used [JsonIgnore] attribute to tell the proper inheritance to JSON serialization.

using Newtonsoft.Json;

public partial class Set
public Set()
this.Exercises = new HashSet<Exercise>();

public long Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }

public virtual ICollection<Exercise> Exercises { get; set; }

public partial class ExerciseRecord
public long Id { get; set; }
public double Record { get; set; }
public System.DateTime Date { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public long ExerciseId { get; set; }

public virtual Exercise Exercise { get; set; }

public partial class Exercise
public Exercise()
this.ExerciseAttributes = new HashSet<ExerciseAttribute>();
this.ExerciseRecords = new HashSet<ExerciseRecord>();

public long Id { get; set; }
public string Name { get; set; }
public double Target { get; set; }
public long SetId { get; set; }
public virtual Set Set { get; set; }
public virtual ICollection<ExerciseAttribute> ExerciseAttributes { get; set; }
public virtual ICollection<ExerciseRecord> ExerciseRecords { get; set; }


MVC loads older script files

This is due to browser script caching. The easiest solution for this is to set the browser which you are using to debug to retrieve the newest versions of web page content on each time you visit a webpage.

Missing Key definition from Model when creating a controller

You might get an error like this: EntityType ‘your type’ has no key defined. Define the key for this EntityType.

To fix such problems simply add this namespace definitions:

using System.ComponentModel.DataAnnotations;

And then define in your data model a key like this:

public class ColumnDataHighChart
public int ID { get; set; }
public String Title { get; set; }
public String SubTitle { get; set; }
public IList<String> xAxisCategories { get; set; }
public String yAxisTitle { get; set; }
public IList<SeriesDataHighChart> Series { get; set; }



Intercepting web requests


I have two ways of doing this:

  1. A delegation handler
  2. Or an action filter for a controller.

Delegation handler

DelegatingHandler Class

Sample code:

public class AuthHandler : DelegatingHandler
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
return response;

Action filter for a controlle

Notice that for MVC and Web API there are two different sets of action filter definitions:

MVC Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);


WebAPI Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

public override System.Threading.Tasks.Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);

public override void OnActionExecuting(HttpActionContext actionContext)
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);

public override System.Threading.Tasks.Task OnActionExecutingAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
return base.OnActionExecutingAsync(actionContext, cancellationToken);


Lambda Expression “Magic” 🙂

Retrieve distinct parent from child elements

As the title suggests I needed to retrieve the parent from a multilevel data set:


First I needed to get the child elements and in this exmaple it is assumed that you have the child elements retrieved.

Once you have the child elements it is time to get the distinct parent elements. for this I needed a way to group the distinct parent from the child elements. Here are my steps:

  • Get child elements:

ExerciseRecordsController exerciseRecordsController = new ExerciseRecordsController();
var exerciseRecordsData = exerciseRecordsController.GetExerciseRecords().Where(er => er.Date > startDate && er.Date < endDate && er.Exercise.Set.UserId.ToLower().CompareTo(this.user.Id.ToLower()) == 0);

  • Define a custom extension named “DistinctBy”

public static class LambdaExtensions
public static IEnumerable<t> DistinctBy<t>(this IEnumerable<t> list, Func<t, object> propertySelector)
return list.GroupBy(propertySelector).Select(x => x.First());
} Original code from:

  • Apply the new extension on the data set

var setsData = exerciseRecordsData.DistinctBy(o => o.Exercise.SetId).Select( o => o.Exercise.Set);

How to create/populate a collection with data with an unknown data type

You may ask yourself why would anyone needs this? Well I do not why would others needs this but I came into a situation where I needed this.

I had a solution where I needed to be able to create data from a back-end server WebAPI to a JS HighCharts JS library without knowing what kind of data I would be processing, also I wanted to have the possibility to extend the back-end code so that it can return any kind of data to the client and let the client figure out what to do with the data.

So how to do this?

In a human language it goes something like this: Use LINQ in your code to go through the data set, select your data and return it as and array of objects, then create a new collection by passing to the constructor your processed data as an array of objects. Ofcourse your collection must store objects as well. The data type information is going to be stored because every class in C# is a descendant of the Object class.

public class SeriesDataHighChart
public long ID { get; set; }
public String Name { get; set; }
public IList<object> Data { get; set; }


// One series corresponds to one set and data for each month
SeriesDataHighChart seriesData = new SeriesDataHighChart();

seriesData.ID = chartSet.Id;
seriesData.Name = chartSet.Name;
var seriesMonthsActivityCountData = (from monthActivityCount in chartSet.ChartSetMonthsData
select new object[] { monthActivityCount.ActivityCount as object });
seriesData.Data = new List<object>(seriesMonthsActivityCountData.ToArray());



You could also return an array of more complex object such as a key value pairs:

var sd = from d in unparsedData
select new object[] { d.Key as object, d.Value as object };

newSeries.Data = new Data(sd.ToArray());

Avoiding “Sequence contains no elements” exception in object initializers

If you have something like this in your code:

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Average(a => a.Record)



The Average lambda expression will throw the above exception error message because the Where clause may return Zero elements back(Notice that for example the Count expression will not throw a similar exception).

To fix(go around the problem, yes there might be other solutions but this was mine at the moment 🙂 ) I created an anonymous function that checks if there are elements returned by the clause and only then perform the Average operation on the elements. The solution is highlighted with the green color.

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = new Func<double>(() => {
double averageRecord = 0;
var exerciseRecordByDateRange = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate);
if (exerciseRecordByDateRange.Count() > 0)
averageRecord = exerciseRecordByDateRange.Average(a => a.Record);

return (averageRecord);

 Get the count for a complex data structure/hierarchy, tree like

A rather simple implementation, choose to retrieve any records inside your main records set with a where:

set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.Month == month)).Count()

Update Azure SQL Database via SQL Server management studio and Generated scripts

  1. Mouse second button on database > Taskas > Generate Scripts > Choose your objects (Chose objects view) > Select “Advanced” button, then in the “Script for the database engine type” select option Windows Azure SQL Database
  2. Next open the database connection with management studio to your Azure SQL Database.
  3. Create a new empty database
  4. Open a new query windows and simply add the generated script to this window and run the script against the new empty database. This will create the structure and data if you selected so.

After deploying your WebAPI you get a following error when accessing your database data “There is already an open DataReader associated with this Command which must be closed first.”

To fix this error simply add the following to your connection strings used in your web api in Azure MultipleActiveResultSets=true.

Enable WebAPI Cross-Origin Resource Sharing (CORS)

You might run into problems after deploying your WebAPI to Azure and trying to access your api from different origins. Here is a solution:

Summary of the article above: Install the following nuget package in your WebAPI project: Microsoft.AspNet.WebApi.Cors

In your webapiconfig add the following(in green):

public static class WebApiConfig
public static void Register(HttpConfiguration config)
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

var cors = new EnableCorsAttribute(“*”, “*”, “*”);

// Web API routes

name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }

config.MessageHandlers.Add(new Handler.AuthHandler());

Next add the following to your ApplicationOAuthProvider.GrantResourceOwnerCredentials function:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
context.OwinContext.Response.Headers.Add(“Access-Control-Allow-Origin”, new[] { “*” });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(user.Id);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, user.UserName);
if (user == null)
context.SetError(“invalid_grant”, “The user name or password is incorrect.”);

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);


Notice that these changes may have undesired effects. Find out if these are suitable to your needs.

Good to Know: Windows Azure and Web Services functionality


Here is my knowledge source listing for Windows Azure and Web Services functionality. Hope it helps someone:

Accessing Data
.NET Framework Data Providers
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Designer
ADO.NET Entity Data Model Tools
Advanced using OData in .NET: WCF Data Services
ASP.NET Application State Overview
ASP.NET Session State Overview
CacheDependency Class
CacheItemPolicy Class
CacheItemPriority Enumeration
ChangeMonitor Class
Code First to an Existing Database
CommandType Enumeration
Configuring Parameters and Parameter Data Types
Create Database Wizard (Master Data Services Configuration Manager)
DataAdapter Class
DataAdapter.AcceptChangesDuringFill Property
DataContractAttribute Class
DataSet Class
DataSet Class
DataTable Class
DbContext Class
DBContext vs ObjectContexts
DbContext.SaveChanges Method
DbContext.Set<TEntity> Method
DbDataAdapter.Fill Method (DataSet)
DbDataAdapter.Update Method (DataSet)
Demystifying Entity Framework Strategies: Loading Related Data (Eager Loading,  Lazy Loading, Explicitly Loading)
EdmEntityTypeAttribute Class
EF Designer TPT Inheritance
Entity Data Model Wizard
Entity Framework
Entity Framework – Database First
Entity Framework (EF) Documentation
Entity Framework 5: Controlling automatic query compilation
Entity Framework- Code First to a New Database
EntityCommand Class
EntityConnection Class
EntityObject Class
EntityTransaction Class
How to: Use Lazy Loading to Load Related Objects
HttpContext.Cache Property
Improve Performance with Entity Framework 5
IsolationLevel Enumeration
LINQ (Language-Integrated Query)
LINQ to Entities: Basic Concepts and Features
LINQ to Objects
LINQ to XML [from BPUEDev11]
LINQ to XML Overview
Loading Related Entities (Eager Loading,  Lazy Loading, Explicitly Loading)
Model-First in the Entity Framework 4
ObjectCache Class
ObjectContext Class
ObjectContext management
ObjectQuery Class
ObjectQuery.ToTraceString Method
ObjectQuery<T> Class
Object-relational impedance mismatch
OData protocol
Open Data Protocol by Example
Plain Old CLR Object(POCO)
Precompiling LINQ Queries
Queries in LINQ to Entities
Relational database management system
Retrieving Data Using a DataReader
SerializableAttribute Class
SQL Server Connection Pooling (ADO.NET)
SqlCommand Class
SqlCommand.CommandText Property
SqlCommand.ExecuteReader Method
SqlCommand.ExecuteScalar Method
SqlConnection Class
SqlConnectionStringBuilder Class
SqlDataAdapter Class
SqlDataReader Class
SqlDataReader.Read Method
SqlParameter Class
SqlTransaction Class
System.Data.EntityClient Namespace
System.Data.SqlClient Namespace
System.Transactions Namespace
System.Xml Namespaces
Table-per-Type vs Table-per-Hierarchy Inheritance
The ADO.NET Entity Framework Overview
TransactionScope Class
Understanding ASP.NET View State
Understanding Service-Oriented Architecture
Update Model Wizard (Entity Data Model Tools)
Using the DbContext API
Using the REST Interface
Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data
WCF Data Services 4.5
WCF Data Services Overview
Working with Datasets in Visual Studio
Working with POCO Entities
XElement Class
XML Documents and Data
XmlDocument Class
XmlReader Class
XmlWriter Class
XPath Examples
Designing and implementing WCF Services – Create, Configure, Secure, Consume
Accessing Services Using a WCF Client
Azure Service Bus
Basic [WCF Samples]
BasicHttpBinding Class
BinaryMessageEncodingBindingElement Class
Binding [WCF Samples]
Chapter 7: Message and Transport Security
Choosing a Message Exchange Pattern
CompositeDuplexBindingElement Class
Configuration Editor Tool (SvcConfigEditor.exe)
Configuring Services Using Configuration Files
Creating the Web Service Proxy
Custom Binding Samples
Custom Bindings
Data Contract Known Types
DataContractAttribute Class
DataMemberAttribute Class
Difference between BasicHttpBinding and WsHttpBinding
Endpoints: Addresses, Bindings, and Contracts
EnumMemberAttribute Class
Extending Dispatchers
Extensibility [WCF Samples]
Fault Contract
Fault Contract – Handling Errors in WCF and A Very Simple WCF Service Implementation
Getting Started Tutorial
Host WCF in an Azure worker role (CSAzureWCFWorkerRole)
Hosting WCF Services
How to: Create a Transactional Service
How to: Create a Windows Communication Foundation Client
How to: Expose a Metadata Endpoint
How to: Implement a Windows Communication Foundation Service Contract
How to: Inspect or Modify Messages on the Client
How to: Set the Security Mode
How to: Use the ChannelFactory
IClientMessageInspector Interface
IDispatchMessageInspector Interface
KnownTypeAttribute Class
Message Inspectors
Message Patterns in WCF Services
Message Security in WCF
MetadataExchangeBindings Class
MtomMessageEncodingBindingElement Class
NetMsmqBinding Class
NetNamedPipeBinding Class
OneWayBindingElement Class
OperationBehaviorAttribute Class
OperationContractAttribute Class
Programming WCF Security
Publishing Metadata
Reliable Sessions Overview
ReliableSessionBindingElement Class
Scenario [WCF Samples]
Securing and Authenticating a Service Bus Connection
SecurityBindingElement Class
Service Bus Bindings
Service Bus Queues, Topics, and Subscriptions
ServiceBehaviorAttribute Class
ServiceContractAttribute Class
ServiceHost Class
ServiceModel Metadata Utility Tool (Svcutil.exe)
Sessions, Instancing, and Concurrency
Simplified Configuration
Simplified Configuration for WCF Services
SslStreamSecurityBindingElement Class
Status codes
System-Provided Bindings
TextMessageEncodingBindingElement Class
TransactionFlowBindingElement Class
Transactions in WCF Services
Types Supported by the Data Contract Serializer
Using Data Contracts
WCF Configuration Tools
WCF Extensibility – IParameterInspector
WCF Extensibility: Parameter Inspectors
Versioning Strategies
Windows Communication Foundation Endpoints
Windows Communication Foundation Tools
WindowsStreamSecurityBindingElement Class
WSHttpBinding Class
Creating and consuming Web API-based services – Design, Implement, Secure, Host and Manage, Consume
A WebAPI Basic Authentication Authorization Filter
AcceptVerbsAttribute Class
ActionFilterAttribute Class
Add Models and Controllers
Async Streaming in ASP.NET Web API
Asynchronous Programming with Async and Await (C# and Visual Basic)
Authentication and Authorization in ASP.NET Web API
Basic Authentication in ASP.NET Web API
Content Negotiation in ASP.NET Web API
Cross-Site Request Forgery (CSRF)
Dependency Injection in ASP.NET Web API 2
Enabling Cross-Origin Requests in ASP.NET Web API 2
Enabling CRUD Operations in ASP.NET Web API 1
Forms Authentication in ASP.NET Web API
Getting Started with ASP.NET Web API 2 (C#)
How to host your web API.
HTTP Authentication: Basic and Digest Access Authentication
HttpClient Class
HttpClient.GetAsync Method (String)
HttpMessageHandler Class
HttpResponseException Class
HttpResponseMessage Class
Integrated Windows Authentication
JSON and XML Serialization in ASP.NET Web API
Makecert.exe (Certificate Creation Tool)
Media Formatters in ASP.NET Web API 2
Media Formatters in ASP.NET Web API 2
Parameter Binding in ASP.NET Web API
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API
Preventing CSRF Hacks in ASP.NET WebAPI
Routing Service
Routing Services [WCF Samples]
synchronous Streaming in ASP.NET WebApi
Using Asynchronous Methods in ASP.NET MVC 4
Working with SSL in Web API
Deploying web applications and services
Azure Guest OS Releases and SDK Compatibility Matrix
Azure Service Definition Schema (.csdef File)
Configuring a Web Server for Web Deploy Publishing (Remote Agent)
Configuring Parameters for Web Package Deployment
Configuring Step 1: Install IIS and ASP.NET Modules
Continuous Delivery for Cloud Services in Azure
Continuous delivery to Azure using Visual Studio Online
Export a Package through IIS Manager
Get Started with Azure Cmdlets
Get started with Azure Websites and ASP.NET
How to Configure Cloud Services
How to Deploy an Azure Website
IIS Information
Installing and Configuring Web Deploy on IIS 7
Installing NuGet
Manage Deployments in Azure
NetworkConfiguration Schema
Nuspec Reference
Package Manager Console Powershell Reference
Reference for the Web Application Package
Shadow Copying Assemblies
Step 1: Examining the Configuration Files
Swap Deployment
Team Build + Web Deployment + Web Deploy + VS 2010 = Goodness
Web Deploy Command Line Syntax
Web Deployment Overview for Visual Studio and ASP.NET
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio

Good to know!?: .NET – Accessing, Querying and Manipulating data with Entity Framework


I gathered some links and resources on data manipulation with the .NET Framework. Hope this helps and works as a reference card what is available:

Entity Framework
Configuring Parameters and Parameter Data Types
.NET Framework Data Providers
DataSet Class
Retrieving Data Using a DataReader
Entity Framework – Database First
Entity Framework- Code First to a New Database
ADO.NET Entity Data Model Designer
Entity Data Model Wizard
Create Database Wizard (Master Data Services Configuration Manager)
Update Model Wizard (Entity Data Model Tools)
Using the DbContext API
Table-per-Type vs Table-per-Hierarchy Inheritance
Relational database management system
ObjectContext Class
DBContext vs ObjectContexts
DbContext Class
ObjectContext management
How to: Use Lazy Loading to Load Related Objects
EntityObject Class
EdmEntityTypeAttribute Class
SerializableAttribute Class
DataContractAttribute Class
Entity Framework (EF) Documentation
OData protocol
Open Data Protocol by Example
WCF Data Services Overview
Using the REST Interface
Understanding Service-Oriented Architecture
WCF Data Services 4.5
Advanced using OData in .NET: WCF Data Services
ObjectCache Class
HttpContext.Cache Property
ASP.NET Application State Overview
ASP.NET Session State Overview
Understanding ASP.NET View State
CacheItemPolicy Class
CacheItemPriority Enumeration
ChangeMonitor Class
CacheDependency Class
System.Transactions Namespace
EntityTransaction Class
EntityCommand Class
EntityConnection Class
SqlTransaction Class
System.Data.EntityClient Namespace
IsolationLevel Enumeration
TransactionScope Class
System.Xml Namespaces
XmlWriter Class
XML Documents and Data
XmlDocument Class
XmlReader Class
XPath Examples
LINQ to XML [from BPUEDev11]
LINQ to XML Overview
XElement Class
LINQ (Language-Integrated Query)
DbContext.SaveChanges Method
DbContext.Set<TEntity> Method
Object-relational impedance mismatch
Loading Related Entities (Eager Loading,  Lazy Loading, Explicitly Loading)
Demystifying Entity Framework Strategies: Loading Related Data (Eager Loading,  Lazy Loading, Explicitly Loading)
Precompiling LINQ Queries
Entity Framework 5: Controlling automatic query compilation
Improve Performance with Entity Framework 5
Queries in LINQ to Entities
LINQ to Entities: Basic Concepts and Features
LINQ to Objects
SqlConnectionStringBuilder Class
ObjectQuery<T> Class
ObjectQuery Class
ObjectQuery.ToTraceString Method
System.Data.SqlClient Namespace
SqlConnection Class
SQL Server Connection Pooling (ADO.NET)
DataTable Class
DataSet Class
DataAdapter Class
SqlCommand Class
SqlCommand.CommandText Property
CommandType Enumeration
SqlDataAdapter Class
SqlCommand.ExecuteScalar Method
SqlCommand.ExecuteReader Method
SqlDataReader Class
SqlDataReader.Read Method
DbDataAdapter.Fill Method (DataSet)
DbDataAdapter.Update Method (DataSet)
DataAdapter.AcceptChangesDuringFill Property
Working with Datasets in Visual Studio
SqlParameter Class
EF Designer TPT Inheritance
Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data
Code First to an Existing Database
Model-First in the Entity Framework 4
ADO.NET Entity Data Model Designer
The ADO.NET Entity Framework Overview
ADO.NET Entity Data Model Tools
Plain Old CLR Object(POCO)
Working with POCO Entities

Good to know!? C# 5.0 Key Features Reference – Part 2


This are copy notes from the main key-points found in the MS 70-483 prep book. This might be useful to someone. A checklist of things in C#.

Also check out the exam link and the actual book:

Exam Ref 70-483: Programming in C#

Implement multithreading and asynchronous processing
Using multiple threads can improve responsiveness and enables you to make use of multiple processors.
The Thread class can be used if you want to create your own threads explicitly. Otherwise, you can use the ThreadPool to queue work and let the runtime handle things.
A Task object encapsulates a job that needs to be executed. Tasks are the recommended way to create multithreaded code.
The Parallel class can be used to run code in parallel.
PLINQ is an extension to LINQ to run queries in parallel.
The new async and await operators can be used to write asynchronous code more easily.
Concurrent collections can be used to safely work with data in a multithreaded (concurrent access) environment.
Manage multithreading
When accessing shared data in a multithreaded environment, you need to synchronize
access to avoid errors or corrupted data.
 Use the lock statement on a private object to synchronize access to a piece of code.
 You can use the Interlocked class to execute simple atomic operations.
 You can cancel tasks by using the CancellationTokenSource class with a
Implement program flow
 Boolean expressions can use several operators: ==, !=, <, >, <=, >=, !. Those operators
can be combined together by using AND (&&), OR (||) and XOR (^).
 You can use the if-else statement to execute code depending on a specific condition.
 The switch statement can be used when matching a value against a couple of options.
56 Chapter 1 Manage program flow
The for loop can be used when iterating over a collection where you know the number of iterations in advance.
A while loop can be used to execute some code while a condition is true; do-while should be used when the code should be executed at least once.
foreach can be used to iterate over collections.
Jump statements such as break, goto, and continue can be used to transfer control to another line of the program.
Create and implement events and callbacks method
 Delegates can be instantiated, passed around, and invoked.
 Lambda expressions, also known as anonymous methods, use the => operator and
form a compact way of creating inline methods.
 Events are a layer of syntactic sugar on top of delegates to easily implement the
publish-subscribe pattern.
 Events can be raised only from the declaring class. Users of events can only remove
and add methods the invocation list.
 You can customize events by adding a custom event accessor and by directly using the
underlying delegate type.
Implement exception handling
 In the .NET Framework, you should use exceptions to report errors instead of error
 Exceptions are objects that contain data about the reason for the exception.
 You can use a try block with one or more catch blocks to handle different types of
 You can use a finally block to specify code that should always run after, whether or not
an exception occurred.
 You can use the throw keyword to raise an exception.
 You can define your own custom exceptions when you are sure that users of your code
will handle it in a different way. Otherwise, you should use the standard .NET Framework
Create types
 Types in C# can be a value or a reference type.
 Generic types use a type parameter to make the code more flexible.
 Constructors, methods, properties, fields, and indexer properties can be used to create
a type.
 Optional and named parameters can be used when creating and calling methods.
 Overloading methods enable a method to accept different parameters.
 Extension methods can be used to add new functionality to an existing type.
 Overriding enables you to redefine functionality from a base class in a derived class.
Consume types
 Boxing occurs when a value type is treated as a reference type.
When converting between types, you can have an implicit or an explicit conversion.
An explicit conversion is called casting and requires special syntax.
You can create your own implicit and explicit user-defined conversions.
The .NET Framework offers several helper methods for converting types.
The dynamic keyword can be used to ease the static typing of C# and to improve
interoperability with other languages.
Enforce encapsulation
Encapsulation is important in object-oriented software. It hides internal details and
improves the usability of a type.
Data can be encapsulated with a property.
Properties can have both a get and a set accessor that can run additional code, commonly
known as getters and setters.
Types and type elements can have access modifiers to restrict accessibility.
The access modifiers are public, internal, protected, protected, internal, and private.
Explicit interface implementation can be used to hide information or to implement
interfaces with duplicate member signatures.
Create and implement a class hierarchy
Inheritance is the process in which a class is derived from another class or from an interface.
An interface specifies the public elements that a type must implement.
A class can implement multiple interfaces.
A base class can mark methods as virtual; a derived class can then override those methods to add or replace behavior.
A class can be marked as abstract so it can’t be instantiated and can function only as a base class.
A class can be marked as sealed so it can’t be inherited.
The .NET Framework offers default interfaces such as IComparable, IEnumerable, IDisposable and IUnknown.
Find, execute, and create types at runtime by using reflection
A C# assembly stores both code and metadata.
Attributes are a type of metadata that can be applied in code and queried at runtime.
Reflection is the process of inspecting the metadata of a C# application.
Through reflection you can create types, call methods, read properties, and so forth.
The CodeDOM can be used to create a compilation unit at runtime. It can be compiled or converted to a source file.
Expression trees describe a piece of code. They can be translated to something else (for example, SQL) or they can be compiled and executed.
Manage the object life cycle
 Memory in C# consists of both the stack and the heap.
 The heap is managed by the garbage collector.
 The garbage collector frees any memory that is not referenced any more.
 A finalizer is a special piece of code that’s run by the garbage collector when it removes
an object.
 IDisposable can be implemented to free any unmanaged resources in a deterministic
 Objects implementing IDisposable can be used with a using statement to make sure
they are always freed.
 A WeakReference can be used to maintain a reference to items that can be garbage
collected when necessary.
Manipulate strings
A string is an immutable reference type.
When doing a lot of string manipulations, you should use a StringBuilder.
The String class offers a lot of methods for dealing with strings like IndexOf, LastIndexOf, StartsWith, EndsWith, and Substring.
Strings can be enumerated as a collection of characters.
Formatting is the process of displaying an object as a string.
You can use format strings to change how an object is converted to a string.
You can implement formatting for your own types.
Validate application input
 Validating application input is important to protect your application against both
mistakes and attacks.
 Data integrity should be managed both by your application and your data store.
 The Parse, TryParse, and Convert functions can be used to convert between types.
 Regular expressions, or regex, can be used to match input against a specified pattern
or replace specified characters with other values.
 When receiving JSON and XML files, it’s important to validate them using the built-in
types, such as with JavaScriptSerializer and XML Schemas.
Perform symmetric and asymmetric
 An asymmetric algorithm uses a public and private key that are mathematically linked.
 Hashing is the process of converting a large amount of data to a smaller hash code.
 Digital certificates can be used to verify the authenticity of an author.
 CAS are used to restrict the resources and operations an application can access and
 System.Security.SecureString can be used to keep sensitive string data in memory.
Manage assemblies
An assembly is a compiled unit of code that contains metadata.
An assembly can be strongly signed to make sure that no one can tamper with the content.
Signed assemblies can be put in the GAC.
An assembly can be versioned, and applications will use the assembly version they were developed with. It’s possible to use configuration files to change these bindings.
A WinMD assembly is a special type of assembly that is used by WinRT to map non-native languages to the native WinRT components.
Debug an application
Visual Studio build configurations can be used to configure the compiler.
 A debug build outputs a nonoptimized version of the code that contains extra instructions
to help debugging.
 A release build outputs optimized code that can be deployed to a production
 Compiler directives can be used to give extra instructions to the compiler. You can use
them, for example, to include code only in certain build configurations or to suppress
certain warnings.
 A program database (PDB) file contains extra information that is required when debugging
an application.
Implement diagnostics in an application
 Logging and tracing are important to monitor an application that is in production and
should be implemented right from the start.
 You can use the Debug and TraceSource classes to log and trace messages. By configuring
different listeners, you can configure your application to know which data to send
 When you are experiencing performance problems, you can profile your application to
find the root cause and fix it.
 Performance counters can be used to constantly monitor the health of your applications.
Perform I/O operations
 You can work with drives by using Drive and DriveInfo.
 For folders, you can use Directory and DirectoryInfo.
 File and FileInfo offer methods to work with files.
 The static Path class can help you in creating and parsing file paths.
 Streams are an abstract way of working with a series of bytes.
 There are many Stream implementations for dealing with files, network operations,
and any other types of I/O.
 Remember that the file system can be accessed and changed by multiple users at the
same time. You need to keep this in mind when creating reliable applications.
 When performing network requests, you can use the WebRequest and WebResponse
classes from the System.Net namespace.
 Asynchronous I/O can help you create a better user experience and a more scalable
Consume data
 ADO.NET uses a provider model that enables you to connect to different types of
 You use a DbConnection object to create a connection to a database.
 You can execute queries that create, update, read, and delete (CRUD) data from a
 When creating queries it’s important to use parameterized queries so you avoid SQL
Objective 4.3: Query and manipulate data and objects by using LINQ CHAPTER 4 291
You can consume a web service from your application by creating a proxy for it.
You can work with XML by using the XmlReader, XmlWriter, XPathNavigator, and XmlDocument classes.
Query and manipulate data and objects by using LINQ
 LINQ, which stands for Language Integrated Query, is a uniform way of writing queries
against multiple data sources.
 Important language features when working with LINQ queries are implicit typing, object
initialization syntax, lambdas, extension methods, and anonymous types.
 You can use LINQ with a method-based syntax and the query syntax.
 LINQ queries are deferred-execution, which means that the query executes when it is
first iterated.
 You can use LINQ to XML to query, create, and update XML.
Serialize and deserialize data
 Serialization is the process of transforming an object to a flat file or a series of bytes.
 Deserialization takes a series of bytes or a flat file and transforms it into an object.
 XML serialization can be done by using the XmlSerializer.
 You can use special attributes to configure the XmlSerializer.
 Binary serialization can be done by using the BinaryFormatter class.
 WCF uses another type of serialization that is performed by the DataContractSerializer.
 JSON is a compact text format that can be created by using the DataContractJsonSerializer.
Store data in and retrieve data from collections
 The .NET Framework offers both generic and nongeneric collections. When possible,
you should use the generic version.
 Array is the most basic type to store a number of items. It has a fixed size.
 List is a collection that can grow when needed. It’s the most-used collection.
 Dictionary stores and accesses items using key/value pairs.
 HashSet stores unique items and offers set operations that can be used on them.
 A Queue is a first-in, first-out (FIFO) collection.
 A Stack is a first-in, last-out (FILO) collection.
 You can create a custom collection by inheriting from a collection class or inheriting
from one of the collection interfaces.

Good to know!? C# 5.0 Key Features Reference – Part 1

Hi here is my reference links to C# 5.0. hope it helps someone!! 🙂

Manage program flow – Multithreading, asynchronous processing, events and callbacks, exception handling

Asynchronous Programming with Async and Await (C# and Visual Basic)
C# Operators
CancellationTokenSource Class
Covariance and contravariance
Delegate.GetInvocationList Method
Exceptions and Exception Handling (C# Programming Guide)
Flow Control
Interlocked Methods
Jump Statements
Lambda Expressions (C# Programming Guide)
lock Statement (C# Reference)
Parallel LINQ (PLINQ)
System.Collections.Concurrent Namespace
System.Threading.Tasks Namespace
Thread Class
ThreadLocal<T> Class
ThreadPool Class
Using Delegates (C# Programming Guide)
Volatile Class

Types – Create types, Consume types, encapsulation, class hierarchy, reflection, string/text manipulation

Abstract and Sealed Classes and Class Members (C# Programming Guide)
Access Modifiers (C# Reference)
Anonymous Methods (C# Programming Guide)
Attributes (C# and Visual Basic)
Basic String Operations
Best Practices for Using Strings in the .NET Framework
C# – Understanding The NET Garbage Collector
Constructor Design
CultureInfo Class
Enumeration Types (C# Programming Guide)
ExceptionDispatchInfo Class
Expression Trees (C# and Visual Basic)
Extension Methods (C# Programming Guide)
Finalize Methods and Destructors
Generics (C# Programming Guide)
IDisposable Interface
Immutability in C# Part One: Kinds of Immutability
Interfaces (C# Programming Guide)
IUnknown interface
Managed Extensibility Framework (MEF)
Operator Keywords (C# Reference)
Properties (C# Programming Guide)
The Big Ball of Mud and Other Architectural Disasters
Types (C# Programming Guide)
unsafe (C# Reference)
Using Conversion Operators (C# Programming Guide)
using Statement
Using the CodeDOM
Using the StringBuilder Class
Using Type dynamic (C# Programming Guide)
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
WeakReference Class
virtual (C# Reference)

Application management and development and security – Validation, encryption, assemblies, debugging, diagnostics

.NET Framework Cryptography Model
.NET Framework Cryptography Model
.NET Framework Regular Expressions
Analyzing Application Performance by Using Profiling Tools
Beginners Guide to Performance Profiling
C# Preprocessor Directives
Code Access Security
Conditional (C# Programming Guide)
Debug Class
Debugger Roadmap
Debugging, Tracing, and Profiling
EventLog Class
Gacutil.exe (Global Assembly Cache Tool)
JavaScriptSerializer Class
Makecert.exe (Certificate Creation Tool)
Object.GetHashCode Method
Parsing Strings
PDB Files (C# and Visual Basic)
PerformanceCounter Class
Regular Expression Language – Quick Reference
Runtime Profiling
SecureString Class
Sn.exe (Strong Name Tool)
Step 1: Examining the Configuration Files
Stopwatch Class
Symbol Server and Symbol Stores
System.ComponentModel.DataAnnotations Namespace
System.Diagnostics Namespace
TraceSource Class
Using DebuggerDisplay Attribute
XML Schema Definition Tool (Xsd.exe)

Data access and manipulation – I/O operations, consume data, LINQ data manipulation, serialization, collections

101 LINQ Samples
ADO.NET Architecture
ADO.NET DataSets
Arrays Tutorial
BinaryFormatter Class
Collections (C# and Visual Basic)
Collections and Data Structures
ConfigurationManager Class
DataContractSerializer Class
DataContractSerializer Sample
DbConnection, DbCommand and DbException
DbConnectionStringBuilder Class
Directory Class
DirectorySecurity Class
DriveInfo Class
Encoding Class
Entity Framework
Examples of XML Serialization
File Class
FileInfo Class
FileStream Class
Getting Started with LINQ in C#
How to: Extend the Async Walkthrough by Using Task.WhenAll (C# and Visual Basic)
How to: Parse XML with XmlReader
HttpClient Class
Implementing an Implicit Transaction using Transaction Scope
MemoryStream Class
NonSerializedAttribute Class
Parameters and Execution Plan Reuse
Path Class
Retrieving and Modifying Data in ADO.NET
Serialization (C# and Visual Basic)
SQL Injection
SqlCommand Class
SqlConnection Class
SqlDataReader Class
StreamReader Class
StreamWriter Class
System.IO.Compression Namespace
System.Net Namespace
Using Data Contracts
Using the DbContext API
var (C# Reference)
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio
WebRequest Class
WebResponse Class
What Is Windows Communication Foundation
XML Standards Reference
XmlAttributes.XmlArray Property
XmlAttributes.XmlArrayItems Property
XmlAttributes.XmlAttribute Property
XmlAttributes.XmlElements Property
XmlAttributes.XmlIgnore Property
XmlSerializer Class

Other important links:

Visual Studio Plugins
Database ConnectionStrings

Charts in Microsoft .NET web applications and SharePoint with JavaScript and JQuery components – HighCharts and Google Charts

If you want to add charts to your .NET web applications or your SharePoint site I’ve found two different options that might be useful to you:

  1. HighCharts =>
  2. Google Charts =>

Both are pretty similar in functionality and implementation.

Here are the good and the bad for both of them:


The good:

  • The .NET tools at the moment are more highly advanced in the .NET implementation and configuration of the charting tool. If you want high ,NET coding and maintenance for low or no JS/JQuery implementation this might be your choice.
  • While there is a licence fee for commercial use, a single developer license fee allows a usage to as many web apps, intranet, SaaS apps as you want to create as a developer in your environment or your clients environment. Licensing info:
  • Free for non-commercial use

The Bad:

  • It does require a license fee for commercial usage
  • HighCharts does seem to be more heavy when used in different browsers and devices. Not sure about this one. You need to do some testing of your own.

Google Charts:

The good:

  • No licensing fee
  • Also has .NET implementation although they are not as nearly as sophisticated as the HighCharts counterparts.
  • Google Charts seem to be faster in different browsers and devices. Again this needs to be tested by you.

The bad:

  • The .NET implementations available need some extra work if you want to have the same degree of high customization through .NET code or even lets say styling. This might take you extra time and adjust your timetables accordingly.

Other good things about both tools are:

  • The good thing about these both charting tools IS that the .NET implementations have their code available to be customized to add new features.
  • Both charting tools can be configured to work with JQuery Mobile to be used and fit on smaller screen devices.

Here are the tools:


HighCharts .NET

Google Visualizations (Charts,Graphs,Timelines) for NET

Google DataTable .Net Wrapper

Google Charts, ASP.NET, jQuery, AJAX – Quick & Easy

jQuery Mobile Charts

Documentation for the tools:

Using Google Charts

Highcharts documentation

Resources for SharePoint Search Results Customization

Recently I had to modify a clients search results page to show the search results as a table and not as a list. After a long battle I found a few sources which I would like to share with other people. They might come in handy.


First link:

This is a great link from which I got alot of help. With this XSL file you can show your search results as a table.

Second link:

When you are working with search result you need sometimes to get a hold of the actual search results in XML format that is used by the xsl to be displayed to your page users. The following XSL piece of code copied and pasted in the search results webpart is going to show you the result in XML.

<xsl:stylesheet version=”1.0″
<xsl:output method=”xml” version=”1.0″ encoding=”UTF-8″ indent=”yes”/>
<xsl:template match=”/”>
  <xmp><xsl:copy-of select=”*”/></xmp>

I recommend the following link for more info:

It is a bit old 🙂 BUT still the information applies.

Lastly I want to share a solution I had to conjure up for the XSL file. My client wanted to have a link to a search document so that when you press that link it does not open you the document BUT it opens the document metadata properties in view mode. This was simple enough, just make an URL that points to the documents location, add the item ID to the view page of that library to show you the documents properties. One of the problems it that out of the box the ID field of the XSL is not the ID of the document in its library BUT the ID of the search result. Meaning that if you get 14 search results the ID is the position of the search result in the order it is in the retrieved through the search.

So to get it to work I had to create a new search “Metadata property” named ListItemID. This property uses the crawled property named “ows_ID” to get the documents REAL ID in the library it is located. Then I simply used this new search metadata property in my XSL and everything worked like a charm.

ANYWAY 🙂 below if the piece of XSL and HTML to display a link that allows a user to access the document properties in view mode. Alter it to get your desired functionality.

<a href=”{sitename}/Forms/DispForm.aspx?ID={number(ListItemID)}”>

I’ll explain a bit the above piece of code. The {sitename} will retrieve the list location where this item is located. The DispForm.aspx is a page that can be used to view documents. {number(ListItemID)} is simply a function that converts the ListItemID metadata property value into a number. You have to provide the document ID value to the aspx page. This way the ASPX page will retrieve the proper document information.

Hiding Custom SharePoint fields from edit mode, new window or display mode

A quick post:

Lets say that you do not want to allow users to possibility to edit and insert values to a custom field in one of your lists. To do this you can set the values of one of the following properties of a SPField object:

  1. ShowInEditForm
  2. ShowInDisplayForm
  3. ShowInNewForm

You can do this programmatically at any time, below is a link on how to do it:

#Get the web and site column objects
$web = Get-SPWeb http://portal
$column = $web.Fields["Test Column"]

#Set the PushChangesToLists property for the changes to be applied
#to lists where the column has already been added
$column.PushChangesToLists = $true

#Change the ShowInEditForm and other properties and update objects
$column.ShowInEditForm = $false
$column.ShowInNewForm = $false
$column.ShowInDisplayForm = $true
$column.ShowInViewForms = $true


Remember to check that the change is applied to the list field also. If not then do the change directly to the list field.


Or by XML definition:

<Field Type=”Number” ShowInEditForm=”FALSE” ShowInNewForm=”FALSE” DisplayName=”Counter” Required=”FALSE” EnforceUniqueValues=”FALSE” Indexed=”FALSE” Group=”My Group” ID=”{7f111eff-569d-4852 8bf2-ba0fcee6c69a}” SourceID=”{b1498d8e-4ad9-4d0d-8584-53d9a5de8c11}” StaticName=”Counter” Name=”Counter”>

Links to MSDN about the properties: