Mohammed Omar's Blog

Just another WordPress.com site

Tag Archives: TFS

Validating TFS 2017 Workitem using TeamFoundationRequestFilter

One of the ways to enforce workitem validation is creating a Team Foundation Request Filter, In my opinion you should always try your best to enforce your rules using workitem template customization, however in case there is some business logic that you need to validate whenever a workitem is edited or added, then one of your options would be to create a Team Foundation Request Filter.

Team Foundation Request Filter lets you intercept TFS Requests to add your own logic to every request. you do that by Implementing:

ITeamFoundationRequestFilter 

This will allow you to intercept the request on the following points


public void BeginRequest(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

public void EndRequest(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

public void EnterMethod(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

public void LeaveMethod(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

public Task PostLogRequestAsync(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

public Task RequestReady(IVssRequestContext requestContext)
 {
 throw new NotImplementedException();
 }

 

 

The method we are interested in here is the BeginRequest, using this method we can stop the request by throwing a RequestFilterException.

TFS Clients (Web portal,VS,VSMAc, etc ) use TFS Restful APIs to communicate with the server, when you Add/Edit a workitem from the portal or from any where, you will be actually making a request with the following URL:

“/tfs/DefaultCollection/_api/_wit/updateWorkItems”

and a bunch of json objects, What we need to do here is to first check if the request is calling the mentioned url , and then parse the json and put our logic, here we are simply checking if Priority is bigger than 2 and through an Request Filter Exception with our message

public void BeginRequest(IVssRequestContext requestContext)
 {
 if (!requestContext.ServiceHost.HostType.HasFlag(TeamFoundationHostType.ProjectCollection)) return;
 if (HttpContext.Current.Request.Url.ToString().Contains("/tfs/DefaultCollection/_api/_wit/updateWorkItems"))
 {
 string content = ReadHttpContextInputStream(HttpContext.Current.Request.InputStream);
 content = HttpUtility.UrlDecode(content);
 var serializer = new JavaScriptSerializer();
 serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic Workitem = serializer.Deserialize(content.Split('=')[1].Split(new string[] { "&__RequestVerificationToken" }, StringSplitOptions.None)[0], typeof(object));
 if (Workitem[0].fields["10157"]>2)
 {
 throw new ValidationRequestFilterException("Priorities grater than 2 are not allowed.");
 }
 }
 }

Notice here we are not throwing a regular exception, however we are throwing our own custom exception which implement RequestFilterException as following:

class ValidationRequestFilterException : RequestFilterException
 {
 public ValidationRequestFilterException(string x, bool isWeb)
 : base(x, System.Net.HttpStatusCode.OK)
 {
 }

public ValidationRequestFilterException(string x)
 : base(x)
 {
 }
 }

also notice I’m using the following DynamicJsonConverter to convert json to a dynamic object. “all credits for DynamicJsonConverter class goes to Drew Noakes answer here


public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}

#region Nested type: DynamicJsonObject

private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;

public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}

public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}

private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:\"{1}\"", name, value);
}
else if (value is IDictionary<string, object>)
{
new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
}
else if (value is ArrayList)
{
sb.Append(name + ":[");
var firstInArray = true;
foreach (var arrayValue in (ArrayList)value)
{
if (!firstInArray)
sb.Append(",");
firstInArray = false;
if (arrayValue is IDictionary<string, object>)
new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
else
sb.AppendFormat("{0}", arrayValue);

}
sb.Append("]");
}
else
{
sb.AppendFormat("{0}:{1}", name, value);
}
}
sb.Append("}");
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length == 1 && indexes[0] != null)
{
if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

return base.TryGetIndex(binder, indexes, out result);
}

private static object WrapResultObject(object result)
{
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
return new DynamicJsonObject(dictionary);

var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
return arrayList[0] is IDictionary<string, object>
? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))
: new List<object>(arrayList.Cast<object>());
}

return result;
}
}

#endregion
}

 

Get the complete solution from here

 

Advertisements

What is New in Visual Studio 2013 – Git Support!

Introduction to Version Control Models

In Source control Models we have two main Models – Centralized and Distributed – version controls, both have different advantages and disadvantages, lets quickly get through both models to get to know each one in a deeper details.

Centralized Version Control Model

Centralized VC is based on the idea that we have only one repository (Copy of your Project) centralized in one computer which take the role of a server with multiple clients which connect to it to download a working copy of files making changes to it and then upload it back to the server after resolving conflicts if it occurred.

image

one of the things that characterize CVCM is the fact that the server will always have an idea if someone is working on a specific file or not, as you have to let the server know you are going to work on a file (Checking-Out) and also let the server know you are going to commit changes back to the server(Checking-In), this results for following advantages

Advantages
  1. The ability to monitor each and every file in your project at any time, get information like who is working on it, who is the last person who changed it.
  2. Since clients has to request working on a file, you can set several permissions levels on each and every file.
  3. Since we only have one Repository, it means CVCM works best for large scaled projects with millions of files
Disadvantages

However think about enterprise projects with multiple geographical teams working on different modules of the projects, this would mean every developer will have to have connection to the server every time he needs to check-out, check-in a file, which result on heavy load over network not to mention relying on the internet.

What about if you have made a work around over a bug or feature and want to save a copy of it locally ?!

Distributed Version Control Model

image

In distributed version control model whenever a developer clone server repository it means he gets a whole local copy of the repository to his machine, where he can now checkout files from local repository edit it and then commit it to his local repository and then push or pull to the remote server later when needed.

but what this gives us ?

Advantages
  1. Best offline experience ever!, you can even branch, merge locally without having to communicate to the server.
  2. No rely on connections or internet, which allows developer to be more productive when not connected to a network
  3. If the server failed any other local repository is a complete back up to the server with history of changes, logs etc.,
Disadvantages
  1. Initial cloning of the server repository can be slow as the client has to copy the whole repository with history, logs and everything to his local computer.
  2. Unlike CVCM, monitoring which files are being edited or who is working on which files can be hard.

CVCM vs. DVCMManual gear shift

Remember the flame war we used to have every time we discuss which gearbox is better than the other?

Manual(Standard) or Automatic Gearbox, its exactly the same when talking about Centralized verses Distributed, both has its advantages and disadvantages.

Team Foundation Server 2012 or Less

In previous version of Team Foundation Server we had CVCM, that what we loved and used, it allowed one Centralized repository, and worked great for large scale projects,

In Team Foundation Server 2012 Microsoft introduced Local Work-Space as an attempt to overcome CVCM disadvantage of not allowing working offline easily, by providing a way to work offline and enabling developer to edit, delete or rename files and delay informing the server of these changes until they get online, where server would discover pending changes and allow developer to resolve conflicts  and then safely commit his change-sets,

Local Work-Space allowed CVCM to have Edit-Commit model which allows developers to work offline, however CVCM couldn’t beat DVCM on providing the best offline experience. and on the other hand DVCM cant beat CVCM for providing best experience working with large scale projects.

So developer has to only pick one option and fight for it CVCM or DVCM just as drivers had to choose one options Standard or Automatic Gearbox,

Lucky drivers cars manufactures came up with a new gearbox which combine the advantages of the Standard and Automatic Gearbox ! and its called Steptronic !

And this is exactly what happened with Team Foundation Server 2013 !

Team Foundation Server 2013 and Git Support!

Microsoft wanted to combine the advantages of CVCM and DVCM, and give the developer the option to not only choose which Version control model he want to work with but can also combine both (Using Git-TF) !

In Visual Studio 2013 Microsoft introduce full support for Git Repository.

Picking up between TFVC and Git

image

Creating New Team project

image

Team foundation server 2013 can host fully fledged Git Repository, which you can use any native Git Client to connect to it and work with it just as you do with regular Git Server like Git-Hub

As you can see you can still use the same process template to Git Team project not to mention the same tools you used and love inside Team foundation Server 2013 and Visual Studio 2013!

Visual Studio 2013 IDE and Git Support!

Visual Studio 2013 IDE can now be used to connect to any Git Server and act as native Git Client!

image

image

Git-TF

Using TFS2013 you can even have one enterprise Project with two teams working on different Version Control model!

So let’s look at a high level overview over the underlying architecture of VS2013/TFS2013 to see what we can offer at the moment to our Enterprise customers and community

image

Project 1 use Team Foundation Server VC (Centralized Source Control Model) while Project 2 uses Git (Distributed Version Control) both has no awareness if the other team is using different model,  as Git-TF can be used to Sync between both repositories!

every and each developer is free to use the IDE he likes! and the platform he likes !, think of how this will help with projects with different teams background and different platform!

It Doesn’t matter if you are a java developer on Windows or on Mac or an IoS developer you can use the IDE you like and used to and be part of an enterprise geographical project using Team Foundation Server 2013!

[Arabic] Branching and Merging Visualization with TFS2012

In this lab you will be introduced to the branching and merging visualization support in TFS2012. This support makes it much easier to understand a solution branch hierarchy and to propagate changes during the merge process.

And We Are Celebrating Visual Studio 2012 Launch Too!

Hands-On Visual Studio

Its pleasure to announce the HandsOn Visual Studio,… Visit HandsOnVisualStudio.com to experience, learn & practice Visual Studio 2012 via guided, multi-lingual and real-life labs! !

  • Define
  1. Building the Right Software – Generating Storyboards and Collecting Stakeholder Feedback with VS2012
  • Develop
  1. Agile Project Management in Visual Studio Team Foundation Server 2012
  2. Using the Architecture Explorer in Visual Studio Ultimate 2012 to Analyze Your Code
  3. Understanding Class Coupling with Visual Studio Ultimate 2012
  4. Code Discovery using the Architecture Tools in Visual Studio Ultimate 2012
  5. Making Developers More Productive with Visual Studio Team Foundation Server 2012
  6. Branching and Merging Visualization with Visual Studio Team Foundation Server 2012
  7. Unit Testing and Code Clone Analysis with Visual Studio 2012
  8. Using Code Analysis with Visual Studio 2012 to Improve Code Quality
  9. Introduction to PreEmptive Analytics
  10. Debugging with IntelliTrace using Visual Studio Ultimate 2012
  11. Introduction to Test Planning with Microsoft Test Manager 2012
  12. Introduction to Test Case Management with Microsoft Test Manager 2012
  13. Authoring and Running Manual Tests using Microsoft Test Manager 2012
  14. Introduction to Platform Testing with Microsoft Test Manager 2012
  15. Introduction to Coded UI Tests with Visual Studio Ultimate 2012
  16. Exploratory Testing and Other Enhancements in Microsoft Test Manager 2012
  17. Introduction to Web Performance and Load Testing with Visual Studio Ultimate 2012
  • Operate
  1. Diagnosing Issues in Production with IntelliTrace and VS2012
  2. Lab Management Improvements in VS2012

Branching and Merging Visualization with Visual Studio TFS2012 By Mohammed Omar

Get introduced to the branching and merging visualization support in TFS2012. This support makes it much easier to understand a solution branch hierarchy and to propagate changes during the merge process.

Agile Project Management In TFS2012 By Mohammed Omar

In this lab, you’ll learn how TFS2012 can help you quickly plan, manage, and track work across your entire team. You’ll explore the new product backlog, sprint backlog, and task boards which can be used to track the flow of work during the course of an iteration.