A few months ago I’ve been working with my colleagues Mr. Angel "Java" Lopez, and Mr. Pablo "Lito" Damiani in the Azure Services Management Tools. I’m really proud to say I’ve been part of this project. We also has been supported by other Southies like Maximiliano Deboli , Sebastian Iacomuzzi, Edgardo Rossetto, Pablo Costantini, Matias Woloski and Paulo Arancibia (our UX great master).

During this project we created a set of tool for enable easy management of the new Microsoft’s Azure Services. Windows Azure Services Platform has been just announced at Microsoft PDC as the Microsoft’s processing platform on the clouds. Now cloud computing takes the center stage.

azure

We could quickly say that Azure is an Software as a Service Platform, that runs on Microsoft Infrastructure.

The Azure Services Management tools that we created allow to manage SQL Data Services, an storage on the clouds, and .NET Services including, Access Control and Workflow Services.

azureArchitecture

This tools include a set of Powershell Commandlets to work with Access Control, Workflow Services and SQL Data Services. We also include an unified Windows Management Console Snap-In as UI to work with this commandlets.

2008-10-27-ManagementTools

This tools has been used at PDC presentation: Identity Roadmap for Software + Services.

Resources

WCF AJAX-Friendly Services

October 30th, 2008

At one of my first jobs as web developer I worked with a friend, Gustavo Miranda, A.K.A Morph, we used PHP language. We maintained three websites at different datacenters, but the owner was the same (my friend’s uncle). At that time, one day, we had an integration request: one of the websites should show data stored at the others.

Right now it’s clear that the use web services is the best solution, but at that time, we were about seventeen years old and we had no idea about ajax or web services because they were not so popular.

So we started to think and research, and finally we found a solution: We had a PHP page that could return plain text, and to call it, we used a hidden IFRAME, and we use java script to read, parse and show the information.

Sometime later I learned about XML, so I started to create POX (Plain Old XML) “Services” (but I didn’t use to call them “POX services” ), and use the XmlHttpRequest object to make requests. After that, SOAP came, and, in my opinion, mistakenly called “Web” Services became popular.

Today, AJAX and Services are in their plenitude, Microsoft has his own AJAX framework, and the creation of services has never been so easy like using WCF.

In this post, I would like to show how easy it is to create & consume AJAX-friendly services combining the new WCF 3.5 service behaviors & bindings and the Microsoft AJAX framework.

Creating the Service

As creating any service, we should start by the contract. In this case, I will use a Meetings Request service. So these will be my DataContracts:

meetingRquestContract personContract

And this will be my ServiceContract:

serviceContract

As you can see I’m providing a Namespace to the ServiceContract attribute, this is important because this namespace will be the one that we will use from javascript. We will focus in the GetMeetingPage method, for demo proposes we will have only one MeetingRequest by page.

Once we have our contracts, let’s create the service; to do this, we will use the AJAX-enabled WCF Service Template:

template 

This will create a Meetings.svc file and its code behind Meetings.svc.cs, it will also create a section in the Web.config file to configure the service, so let’s go step by step.

MeetingsService.svc: The ServiceHost file. The important thing here is the Service property; this property specifies the type that will contain our service functionality.

 serviceHost

The first thing to do inside it is to clean up the service class, located at the code behind, and implement our ServiceContract, IMeetingsService, the result should be the next one:

 meetingsService

Note that the MeetingsService class implements our ServiceContract, IMeetingsService. To keep it simple, I’m using a static class named MeetingsStore to encapsulate the data access logic, just to get notice I’m using mockdata and LinqToObjects to retrieve it.

The next step is to configure our service. The goal of WCF is that we can configure our service through metadata.

To create SOAP services that work through HTTP, we commonly use bindings like basicHttpBinding or wsHttpBinding. But, as you know, negotiating with SOAP messages from javascript is pretty complex, so we need a binding that allow our enpoinds respond to HTTP requests instead of SOAP messages: the solution is the new webHttpBinding, available from WCF 3.5.

webConfig

As you can see in this Web.config screenshot, we set our binding as webHttpBinding, our contract and our behavior. Let’s stop a second in the behavior, as you can see we are using the enableWebScript behavior, this behavior is the one that makes the magic to allow us to consume our service from ASP.NET AJAX web pages, later we will see this in detail.

So, that’s all for our service, let’s consume it…

Consuming the service

To consume the service the first thing to do is create an AJAX-enabled aspx page, by using the “AJAX Web Form” template or just adding a ScriptManager component to any aspx page. If you use Master Pages, the ScriptManager component should be placed in the master page, and the content pages should use the ScriptManagerProxy component.

The first thing to do is to give to the ScriptManager a reference to our service, that’s what you can see in this screenshot:

jsservicereference 

If we run this page, it looks like nothing is happening, but if we research in the generated html code; we will find something like this:

source

What?? It looks like we are adding a javascript file reference, but instead of myLocalJsFile.js we have MeetingsService.svc/jsdebug. Do you remember the enableWebScript behavior? This is exactly it. If we copy & paste this reference in our browser, something will happen…

downladingthemagic

We used enableWebScript behavior in our service, this means that if we append /jsdebug or just /js to our service URI, it will return a file containing a javascript proxy to our service. If we save and open this file with Visual Studio we will see what it means:

jsproxy

As you can see, this file contains a JSON definition having the same methods that our service contract IMeetingsService, and in the first line we have a namespace registration, the same namespace that we defined in our ServiceContract. So, let’s back to our .aspx page and invoke the service.

To do this, we just have to create an instance of this proxy, in this case ajaxfriendly.services.IMeetingsService, and use its methods, and this task is especially easy using Visual Studio 2008, because we have javascript intellisense & debugging…

jsintellisense

To call any method we have to provide the service parameters and also, because this will run asynchronous, we have to provide one handler to succeededCallback event, and another to failedCallbackEvent. Finally we will have something like this…

js

In the succeededCallback event handler we just display the data. If we run and debug, we can see that in the “result” parameter we’ve our DataContract retrieved by our service in JSON.

An that’s all, the next is play with JavaScript, JQuery (recommended), to manage this data.

You can download the Code Here.

Regards!

The first time that I saw ASP.NET MVC, I was at a Microsoft Tech-night, the speaker was my admired co-worker, Edgardo Rossetto, and I felt in love with the framework. It brought me many memories about my ASP 3.0 developer time.

ASP.NET MVC is not a replace for ASP.NET Web Forms model, is just another choice, and I really like, because I’m a patterns lover and, as you can imagine, ASP.NET MVC is based on the famous MVC Pattern, but also is great because enable easy Test-Driven Development, and every single action is easy mapped to a REST-friendly URL.

So, given that, I want to share with you a little home-made project, my own ASP.NET MVC Grid View.

Before you feel so excited, it do not support paging and sorting (yet), but you can easily add these features in your controller. Right now, it supports simply "Data Source" (any IEnumarable object), extensible "Column Definitions" and CSS Styles.

 

How to use it?

This grid View is basically composed by a Web Control, and a set of "model" classes.

mvcgrid 

The data (DataSource, ColumnDefinitions, CSS Styles, etc…) is given to the WebControl as ViewData. Let’s see that…

Mock Data (Just a method that returns a list of users):

mvcgrid4 

Controller example code (DataSource & Column Definitions at Controller):

mvcgrid1

View example code:

mvcgrid2

The result:

mvcgrid3

How does it work?

The method in change of render the value of each field is place in GridColumnDefinition base class. As you can imagine, it’s based on reflection, using the value of PropertyName to find the value to render.

This is the magic method:

mvcgrid5

Here we’ve something cool; this method is also based on Template Method Pattern, to allow formatting the value before render, so you can write your own implementation of the FormatValue method.

I’ve written three as example…

 

image

This is the GridImageColumn implementation of FormatValue, to render an HTML image with the value…

mvcgrid7

Perhaps an "Action" column definition can be implemented giving as value the Id; it’s free to your imagination!

You can download the source code here.

The next Saturday 4th-Oct, the Microsoft CodeCamp will take place, once again.

This time is really special for me mainly because of two reasons.

The first one is that, this year, the event will be located at the UAI. This university is a place I’m really fond of, because it’s where I had one of my first work opportunities in the software industry.

A couple years ago I worked at the Center of High Studies in Information Technology (CAETI) of this University, where I was able to increase my passion for technology in the fields of research and development, working on topics such as robotics, electronics, and software development, but basically learning a lot and meeting people ready to teach and learn.

On the other hand, as you can see in the post made by Mr. Alberto Ortega, a handful of my admired work mates at Southworks (another place where I can keep up with my passion for technologies) will be in charge of some presentations, so I’ll be there, as an spectator, to support them.

If you didn’t register yet, don’t miss the chance, I promise you won’t be disappointed: http://www.microsoft.com/Argentina/CodeCamp/

Hope to see you there!

I want to share with you something I found very useful. In this post I’ll show how to use the WCF Serializer to serialize and deserialize objects into XML files. I’ve learn that from my coworker Edgardo Rossetto.

I’ve wrote in the previous post about WCF, to send an receive messages WCF needs to serialize and deserialize objects, to do this in the assembly System.Runtime.Serialization there is a class called DataContractSerializer

public sealed class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer
    Member of System.Runtime.Serialization

Summary:
Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited.

So, let’s see an example…

The first step is tag our model classes with DataContract and DataMember attributes.

using System.Collections.ObjectModel;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
    private Collection<Address> address;

    [DataMember]
    public int Id { get; set; }

    [DataMember(IsRequired=false)]
    public string Name { get; set; }

    [DataMember]
    public Collection<Address> Address
    {
        get
        {
            if (this.address == null)
            {
                this.address = new Collection<Address>();
            }

            return this.address;
        }
        set
        {
            this.address = value;
        }
    }
}


[DataContract]
public class Address
{



    [DataMember]
    public string Street { get; set; }



    [DataMember]
    public int Number { get; set; }
}

Notice, we want to serialize and deserialize the Person class, but it has a one-to-many relationship with Address class, so both classes should be tagged as DataContracts and the members we want to serialize should be tagged with DataMember attribute, a little detail to denote is that the property Name of Person class is defined as not required, this means that we don’t need to have a value for this property.

After we have all our classes tagged we need to create a helper class to work with DataContractSerializer. Usually this class is defined with generic methods, because in that way we can use the same class to serialize and deserialize any kind of objects.

using System;
using System.Runtime.Serialization;
using System.Xml;

public class ModelSerializer
{
    public virtual TModel Deserialize<TModel>(string path)
    {
        XmlReader reader = XmlReader.Create(path);

        DataContractSerializer serializer = new DataContractSerializer(typeof(TModel));
        TModel result = (TModel)serializer.ReadObject(reader);

        return result;
    }

    public virtual void Serialize<TModel>(TModel model, string path)
    {
        XmlWriter writer = XmlWriter.Create(path);

        DataContractSerializer serializer = new DataContractSerializer(typeof(TModel));
        serializer.WriteObject(writer, model);

        writer.Flush();
    }
}

This class has two generic methods, Serialize and Deserialize, as you can see both methods uses the DataContractSerializer giving as parameter the generic type TModel.

The implementation is very simple, you only need an XmlReader or an XmlWritter, to provide infrastructure to write or read the XML file, and that’s all. Now we can serialize, into an XML file, any instance of any class tagged as DataContract and deserialize it from an XML file.

This is an example of using, in an Console Application we create an instance of Person class, set some data and we serialize using out ModelSerializer.

class Program
{
    static void Main(string[] args)
    {
        var person = new Person()
        {
            Id = 1,
            Name = "Franz Xaver Sussmayr",
        };

        person.Address.Add(new Address()
        {
            Street = "Schwanenstadt",
            Number = 1766
        });

        person.Address.Add(new Address()
        {
            Street = "Vienna",
            Number = 1803
        });

        var serializer = new ModelSerializer();

        serializer.Serialize<Person>(person, "C:/person.xml");
    }
}

And the result is an person.xml file with this content:

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://schemas.datacontract.org/2004/07/WcfSerialization">



  <Id>1</Id>
  <Name>Franz Xaver Sussmayr</Name>

  <Address>

    <Address>

      <Number>1766</Number>

      <Street>
Schwanenstadt
</Street>

    </Address>


    <Address>
      <Number>1803</Number>
      <Street>Vienna</Street>
    </Address>
  </Address>

</Person>

To deserialize this file is even more easy…

class Program
{
    static void Main(string[] args)
    {
        var serializer = new ModelSerializer();

        var person = serializer.Deserialize<Person>("C:/person.xml");
    }
}

quickwatch

One of the things I really like about working at Southworks is that you have access to an incredible library where you can learn a lot, this is part of the Southworks’ culture

This weekend I started reading Justin Smith’s book “Inside Windows Communication Foundation”.

I’ve finished the first part of the book, although I’ve worked in service-oriented systems, I’ve learned new things about service-orientation and WCF.

Let’s start…

WCF is the Microsoft’s API for creating service-oriented applications.

 

One of the things I really like about WCF, between others, is a “conceptual” feature: WCF works as a “bridge” between object-oriented world and service-oriented world. It means I can work in lovely my object-oriented world (having a very little considerations) and turn my application into service-oriented in a very easy way.

Service Orientation

In a nutshell, service orientation is an architectural style in witch distributed applications components are loosely coupled through contracts.

Service-oriented applications describe the messages they interact with through contracts. These contracts must be expressed in a language and format easily understood by other applications, thereby reducing the number of dependencies on component implementation.

I think is very clear, our system, distributed, connected by messages described by contracts, this made possible our components be loosely coupled. And lastly, I’d like to add that Service Orientation just like Object Orientation is a paradigm that transcends vendors and technology boundaries.

An example…

I like the definitions, but I’m a developer, so let’s take the definition to code.

 

The Contract

As you can read in the service orientation definition the start point of our service-oriented application should be the contract.

The contract must define the messages in a language and format easily understood by other applications, as you can imagine XML is the natural choice.

Imagine a “to-do lists” service, and this being our task message definition contract:

<Task>
    <
TaskId>xs:integer</TaskId
>
    <
Text>xs:string</Text
>
    <
IsCompleted>xs:boolean</IsCompleted
>
</
Task>

Sender and receiver must agree on what kind of messages they’re going to use, this is an example using SOAP messages.

<s:Envelope xmlns:s=http://www.w3.org/2003/05/soap-envelope
            xmlns:wsa=http://schemas.xmlsoap.org/ws/2004/08/addressing
>
  <
s:Header
>
    <
wsa:MessageID>1</wsa:MessageID
>
    <
wsa:Action s:mustUnderstand=1>urn:submitTask</wsa:Action
>
    <
wsa:ReplyTo
>
      <
wsa:Address
>
       
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
      </wsa:Address
>
    </
wsa:ReplyTo
>
    <
wsa:To s:mustUnderstand=1>http://localhost:32677/Order</wsa:To
>
  </
s:Header
>
  <
s:Body
>
    <
Task
>
      <
TaskId>27</TaskId
>
      <
Text>Clean my room</Text
>
      <
IsCompleted>1</IsCompleted
>
    </
Task
>
  </
s:Body
>
</
s:Envelope>

As you can see the example also uses WS-Addressing to indicate the target of the message.

(I am not going to explain WS-Addressing, because my lack of time, if you hadn’t worked with webservices and WS-Addressing before you can read more about WS-Addressing in wikipedia.)

After we have our Task message contract defined, the next step is to define the endpoint that will receive the message, to do this we use WSDL.

Thanks god, or thanks to the WCF Team, WCF provides a way to express a contract in C# (or our favorite CLR compatible language).

A contract expressed in C# can be turned into XSD-based and WSDL-based contracts on demand.

If we choose to express our contracts in C#, we usually use Interfaces.

 

namespace SOApplication.Contracts
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;

    [ServiceContract(Namespace = "http://services.taskmanager.com/TaskService")]
    public interface ITaskService
    {
        [OperationContract(Action="urn:SubmitTask")]
        void SubmitTask(Message task);
    }
}

 


As you can see, this is a normal C# interface. The attributes ServiceContract and OperationContract identifies the interface and the method as a Contracts, this contracts will be turned into an WSDL-based contract on demand.

Notice the type of task, the SubmitTask method parameter type is System.ServiceModel.Channels.Message this parameter represents any message that can be sent to a service.

This contract now can be compiled into an assembly and distributed.

I think is very interesting…

In an Visual Studio Command Prompt, use sqlmetal tool to generate an C# wrapper file that will contain all the code you need to interact with your database, let’s supose PicturesDB. Notice I’ve added “/sprocs”, this means I also need the stored procedures.

    \>sqlmetal /server:.\SQLEXPRESS /database:PeopleDB /sprocs /code:db.cs 

     

Next step is to complie this file, to do this use the CS compiler. This compiles the db.cs file into an assembly called db.dll, accessible by PowerShell.

    \>csc /target:libary db.cs

 

Now we have to load the assembly and use the generated class PeopleDB just like we do in C#. For this example we going to use an stored procedure called GetPeople.

    [Reflection.Assembly]::LoadFile(’C:\db.dll’)
    $conn = “server=.\SQLEXPRESS;database=PicturesDB;Trusted_Connection=true”
    $db = new-object dbMovies($conn)
    $result = $db.GetPeople()
    $result | format-list

pssp

 

I think this can be useful for deployment scripts or data base tests.

This is a quickly sample of sending emails with SmtpClient class, in this example i’m using Gmail’s smtp server.

 

MailMessage mail = new MailMessage()
{
    From = new MailAddress(“user@gmail.com”, “[Name to Show]“),

       Subject = “[Subject]“,
    IsBodyHtml = false,
    Body =
“[Body]”
};

//To MailAddress
mail.To.Add(new MailAddress(“somebody@someplace.com”));

SmtpClient smtp = new SmtpClient(“smtp.gmail.com”, 587);
smtp.Credentials = new NetworkCredential(“[User]“, “[Passwd]“);

//Gmail smtp needs SSL
smtp.EnableSsl = true;

try
{
    smtp.Send(mail);
}
catch (Exception ex)
{
  
//manage your exception…
}

 

Don’t forget add the usings:

using System.Net;
using System.Net.Mail;

 

Thanks!,

Lean.

The next PowerShell code is an example to call an Stored Procedure from Windows PowerShell…

Write-Host “————————————————————”
Write-Host “DataScript Started…OK”
Write-Host “————————————————————”

$connectionString = “Server=localhost;DataBase=PictureDB;Integrated Security=SSPI”

$conn = new-Object System.Data.SqlClient.SqlConnection($connectionString)
$conn.Open()

Write-Host “Connection Opened…”
Write-Host “”

[int] $rowCount = 0

$cmd = new-Object System.Data.SqlClient.SqlCommand(”InsertPicture”, $conn)
$cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’

$cmd.Parameters.Clear()

$cmd.Parameters.Add(”@PictureId”,
[System.Guid]::NewGuid().ToString()) | out-null

$cmd.Parameters.Add(”@Text”, “ISO Party”) | out-null
$cmd.Parameters.Add(”@SubmittedOn”, [System.DateTime]::Now) | out-null

$cmd.Parameters.Add(”@Image”,
[System.IO.File]::ReadAllBytes(”pictures/party001.jpg”)) | out-null

Write-Host “Inserting picture…”

$rowCount = $cmd.ExecuteNonQuery()

$cmd.Dispose()

Write-Host $rowCount “Rows acfected!”

$conn.Close()
$conn.Dispose()

Write-Host “”
Write-Host “Connection Closed.”