How to add MEX endpoints programmatically
The Metadata Exchange Endpoint (MEX) is a special endpoint in WCF that exposes metadata used to describe a service.Without the MEX, you will not be able to use svcutil.exe to automatically generate a proxy class. Fortunately, it is a simply process to enable the MEX for your service. Here is the code which will add Mex endpoint programmatically.
var metadataBehavior = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>()
?? new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(metadataBehavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(),
"http://localhost:8080/IService/Mex");
It should be noted that you are not required to enable HttpGet. SvcUtil will still be able to access the MEX without it. However, it is useful if you want to view the WSDL from a browser by going to the address of the service. You cannot do so without enabling the HttpGet.
How to queue a new build using TFS API
Another post on TFS API, my last post was related to how to get build Definitions and Build Details from TFS 2010, and this post is about how to queue a new build in TFS 2010 Server.
As earlier you need to add reference of following assemblies
- Microsoft.TeamFoundation.dll
- Microsoft.TeamFoundation.Client.dll
- Microsoft.TeamFoundation.Build.Client.dll
which will be available under – C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\ location.
And here is the code snippet
var tfsName = "http://dotnetthoughts:8080/tfs/defaultcollection";
var tfs = new TeamFoundationServer(tfsName, new UICredentialsProvider());
tfs.EnsureAuthenticated();
if (tfs.HasAuthenticated)
{
var buildServer = tfs.GetService(typeof(IBuildServer)) as IBuildServer;
var buildDefinition = buildServer.GetBuildDefinition("", "");
buildServer.QueueBuild(buildDefinition);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
throw;
}
Here is how it works, we are connecting and getting the TFS Server, then getting the Build Server using GetService method. And to get the build definition instead of the earlier post(to get all the Build definitions, we are passing “*”), we need to specify the Team project and Build name(Build definitions are unique per team project in TFS). Then we can call QueueBuild() method on Build server object, with build definition as the parameter, which will queue the build definition default values.
Happy coding
How to use .Net assembly in VBScript
Few days before I got a requirement to use a .Net assembly in VBScript, but it was not working. But today I got the solution. It was related to my 64bit OS.
In this post I am discussing how to create and use a .net assembly in VBScript or Javascript.
First we need to create a class library. Set the ComVisible attribute to true in the AssemblyInfo.cs manually.
[assembly: ComVisible(true)]
Or you can do it using Properties > Application Tab and select Assembly Information, from the Assembly Information dialog, Check the Make assembly COM-Visible check box.

Make Assembly COM Visible option from Assembly Information dialog
Build the assembly. Now we need register the assembly. We can do it using RegAsm.exe. If your OS in 64 bit, then you need to use Regasm command from Framework64 folder(Normally it will be C:\Windows\Microsoft.NET\Framework64\ folder). For running RegAsm command it is recommended to sign the assembly. You can Sign the assembly Properties > Signing Tab.

Sign Assembly option
As RegAsm command add / update information to Windows Registry, you need to run the RegAsm command as Administrator, otherwise it will not work.
You can register the assembly using following command, like this
regasm /codebase assemblyname.dll
You can unregister the assembly using RegAsm command, like this
regasm /u assemblyname.dll
That’s it. Now you can create the object of the .net assembly in VBScript. Like this, it will add 10 and 20 using C# Add method and returns the value.
Dim calcLib
Set calcLib = CreateObject("CalcLib.Math")
Dim result
result = calcLib.Add (10 , 20)
msgbox result
And here is the C# Class, which we are invoked from VBScript.
namespace CalcLib
{
public class Math
{
public int Add(int number1, int number2)
{
return number1 + number2;
}
}
}
Happy Coding
How to get Build Definitions and Build Details from TFS 2010
This snippet which will connect to TFS Server and get all running builds for all build definitions, using TFS Client API.
try
{
var tfsName = "http://dotnetthoughts:8080/tfs/defaultcollection";
var tfs = new TeamFoundationServer(tfsName, new UICredentialsProvider());
tfs.EnsureAuthenticated();
if (tfs.HasAuthenticated)
{
var bs = tfs.GetService(typeof(IBuildServer)) as IBuildServer;
//Select all Build definitions
var spec = bs.CreateBuildQueueSpec("*", "*");
var buildResults = bs.QueryQueuedBuilds(spec);
foreach (IQueuedBuild queuedBuild in buildResults.QueuedBuilds)
{
Console.WriteLine("Status :{0} - {1} - Requested by : {2} Controller :{3}",
queuedBuild.Status, queuedBuild.BuildDefinition.Name,
queuedBuild.RequestedBy, queuedBuild.BuildController.Name);
}
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
throw;
}
Please make sure you are adding of the following assemblies.
- Microsoft.TeamFoundation.dll
- Microsoft.TeamFoundation.Build.Client.dll
- Microsoft.TeamFoundation.Build.Common.dll
- Microsoft.TeamFoundation.dll
which will be available under – C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\ location.
Happy GREEN builds
Introduction to Code First development with Entity Framework
The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model. You may then change relations using the Designer (or the XML mapping files) later to further optimize the model. The priority is the database – the code and the model are only secondary. When your priority is the code and you want to begin from scratch without any existing schema or XML mapping files using source code, then the approach is called CodeFirst. Code-First enables an easy development workflow. It enables you to:
- Develop without opening the designer or mapping in XML files.
- Define model objects by simply writing POCO(Plain old CLR object) with no base classes required
- Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
You can download the latest version of code first from this url : ADO.NET Entity Framework 4.1 – Update 1.
You can also install via NuGet.
install-package entityframework
Quick CRUD example with EF Code first.
First we will create the model classes.
public class Task
{
public int TaskId { get; set; }
public string TaskDescription { get; set; }
public DateTime TaskDate { get; set; }
public short TaskPriority { get; set; }
public bool TaskIsDone { get; set; }
}
Now we need to create a Context for this. Context is required to use the POCO classes for DataAccess. It can be implemented by deriving it from DbContext class. The DbContext class is available under System.Data.Entity namespace.
public class TaskContext : DbContext
{
public DbSet Tasks { get; set; }
}
We are done.
Now we can use this class for communicating to Database.
Inserting records to Database.
using (TaskContext taskContext = new TaskContext())
{
taskContext.Tasks.Add(new Task()
{
TaskDate = DateTime.Today,
TaskDescription = "Create a blog post",
TaskIsDone = false,
TaskPriority = 1
});
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task added.");
}
}
Updating records, updating the first task from Tasks, if the Task date is today.
using (TaskContext taskContext = new TaskContext())
{
var currentTask = taskContext.Tasks.Where
(task => task.TaskDate == DateTime.Today).FirstOrDefault();
currentTask.TaskIsDone = true;
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task updated.");
}
}
Removing records, removing first task from Tasks, if the Task is completed.
using (TaskContext taskContext = new TaskContext())
{
var completedTask = taskContext.Tasks.Where
(task => task.TaskIsDone == true).FirstOrDefault();
taskContext.Tasks.Attach(completedTask);
taskContext.Tasks.Remove(completedTask);
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task Deleted.");
}
}
And retriving records, retriving all the tasks.
using (TaskContext taskContext = new TaskContext())
{
var tasks = taskContext.Tasks.Where
(task => task.TaskDate == DateTime.Today);
tasks.ToList().ForEach(task =>
Console.WriteLine("Task : {0} IsCompleted : {1}",
task.TaskDescription, task.TaskIsDone));
}
It is very easy right? Another interesting question is where this data is getting stored? Because we didn’t specified any Database, or Connection string. By default the database will be created on local instance of SQLEXPRESS (localhost\SqlExpress). The database is named after the fully qualified name of your derived context, in our case that it will be “EFCodeFirst.TaskContext”. You can control this by providing connection string or by setting DefaultConnectionFactory.
You can provide connectionstring either in App.Config / Web.Config file or in code.
If you are providing the connection string in config, file the name of the connection string element should be same as Context class name. Like this
<connectionStrings> <add name="TaskContext" connectionString="Server=.\SqlExpress; Integrated Security=SSPI; Database=TaskDb;" providerName="System.Data.SqlClient"/> </connectionStrings>
And if you want to use your own connection string name, you can do this using CreateConnection() method of the DefaultConnectionFactory class. You can also specify the connection string. You need to provide this information before creating the instance of task context.
Database.DefaultConnectionFactory.CreateConnection("TaskDbConnection");
using (TaskContext taskContext = new TaskContext())
{
//Code.
}
Entity Framework also supports various databases also, like SQL CE, MySql etc. This can be achive either using the provider name is the config settings or by using DefaultConnectionFactory propery of Database class. Following statement helps to use SqlCe database instead of Sql Server
Database.DefaultConnectionFactory =
new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (TaskContext taskContext = new TaskContext())
{
//Code.
}
Model validations also supported by entity framework. I may cover them in another post.
Happy 2012