Archive | July 2013

Subversion Post-Commit Hooks

I came across this and I find it in order to share with my readers.

The “Hello World!” of Subversion post-commit hooks is the use of SVNnotify to send e-mails out to a project team every time a new revision is committed to the repository.

This is easier than it sounds:

Make sure svnnotify is installed on your system. I’ll leave that as an exercise for the reader.

Navigate to your repository’s hooks directory. This is almost always a directory cleverly named “hooks” right inside the top level of your repository:

cd /Users/mwest/svn/my_repository/hooks/

Create a new file called post-commit, and make it executable by the www user.


touch ./post-commit

chmod 755 ./post-commit

Open up the file you just created, and add the following bit of code:


#!/bin/sh

REPOS="$1"

REV="$2"

/usr/local/bin/svnnotify \

--repos-path "$REPOS" \

--revision "$REV" \

--subject-cx \

--with-diff \

--handler HTML::ColorDiff \

--to \

--from

It’s all pretty straightforward, so let’s take it line by line:

The first line is the so-called shebang that tells the system that the file is a shell script that ought be executed.

Next, we set two variables based on the information that Subversion passes into the script when it’s called. The post-commit hook gets two bits of data: the path to the repository, and the new revision number that the commit created.

Finally, we call svnnotify to actually generate and send a nicely formatted e-mail using the repository path and revision number that we gathered earlier. Make sure to put your e-mail address (or list’s address) in the last two lines!

Do some work, and commit it. Go check your email

Happy coding 🙂

Advertisements

Implementing RESTiful WCF service

This post will give some simple insight on how to implement a RESTiful service with WCF.

REST stands for Representational State Transfer. Its an architectural style that focusses on accessing resources through a universal interface URI. An architectural style of software is something that describes the features that can be used to build a software. And REST is actually one way to implement client server architecture style and infact it builds on client-server archicture style. So a service that uses rest architectural style is usually reffered as RESTiful service or endpoint

Rest constraints are based on underlying principles that govern the web  which includes:

  1. User agents interacts with resources and resources are anything that can be named and represented. Each resource can be addressed via unique URI
  2. The interaction with resouces is accomplished using uniform interface http stardand verbs.  There is also declaration of the resource’s media type via http content-type header
  3. Resources are descriptive
  4. Resources contains links to other resources. (HATEOAS)

Even though WCF geared towards RPC (Remote Process Call) using SOAP, there is the capability to expose and consume REST services. The REST programming is around two attributes WebInvokeAttribute and WebGetAttribute and URI template mechanism that enable us to declare the URI and method verb.

WebHttpBinding binding and WebHttpBehavior provides the correct networking stack for using REST with WCF. The hosting infrastructure used to host RESTiful service are WebServiceHost and WebServiceHostFactory which extends ServiceHost and ServiceHostFactory respectively.

The WebGetAttribute tells the dispatcher that the method should only respond to HTTP GET request while WebInvokeAttribute which is mapped to HTTP POST by default, can be set to support any other HTTP VERB e.g PUT,DELETE

UriTemplate is used to enable customization of the URI for each method and verb combination.

So lets dive into some code to see this in action. The sample we are using is not a stardand just used to pass the concept of how to implement a RESTiful WCF service. Our data contract looks like

[DataContract]
public class Person
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public int Age { get; set; }
}

And here is the contract declaration, and to note here is the usage of the WebGet and WebInvoke attributes. I would like to point out that if you look at the UriTemplate for GetPerson and DeletePerson looks the same, but they have the different HTTP VERB.

[ServiceContract(Namespace = "https://piusnjoka.wordpress.com/v1/2013/07/20")]
public interface IPerson
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "save")]
void AddPerson(Person person);

[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "update")]
void UpdatePerson(Person person);

[OperationContract]
[WebInvoke(Method = "DELETE", UriTemplate = "person/{id}")]
void DeletePerson(string id);

[OperationContract]
[WebGet(UriTemplate = "persons")]
List<Person> GetAllPerson();

[OperationContract]
[WebGet(UriTemplate = "person/{id}")]
Person GetPerson(string id);
}

This is our service implementation, which is a singleton service.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PersonService : IPerson
{
private static List<Person> persons = new List<Person>();

public void AddPerson(Person person)
{
persons.Add(person);
}

public void UpdatePerson(Person person)
{
//TODO: Implement bette update here
DeletePerson(person.Id.ToString());
persons.Add(person);
//do some update here
}

public void DeletePerson(string id)
{
persons.RemoveAll(x => x.Id == int.Parse(id));
}

public List<Person> GetAllPerson()
{
return persons;
}

public Person GetPerson(string id)
{
return persons.FirstOrDefault(x => x.Id == int.Parse(id));
}
}

And remember we said that we use WebHttpBinding to support REST and there in our app.config in host project you will find this

<system.serviceModel>
<services>
<service name="WCFRestSample.Service.PersonService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8082"/>
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="WCFRestSample.Service.IPerson"></endpoint>
</service>
</services>
</system.serviceModel>

For simplicity, we will use a self hosting in a console application. Of importance to note here is the “WebServiceHost” which we are using to host our service. If in case it find that there is no endpoint configured in the service description it creates one at the service base address i.e for http/https. The WebServiceHost also add WebHttpBehavior to endpoint that do not have the behavior configured.

WebServiceHost host = new WebServiceHost(typeof(PersonService));
try
{

host.Open();
Console.WriteLine("Host Running");
Console.ReadKey();
host.Close();
}
catch (Exception)
{
host.Abort();
}
}

Thats it we have our service ready for hosting. Any client can call the RESTiful service and in our case we are going to use a simple console application which looks as below. And of importance to note is the “WebChannelFactory<IPerson>”. This adds WebHttpBehavior to endpoints if it does not already exist.

WebChannelFactory<IPerson> factory = new WebChannelFactory<IPerson>(new Uri("http://localhost:8082"));
var channel = factory.CreateChannel();

//Add three persons
Console.WriteLine("***Adding three initial persons**");
channel.AddPerson(new Person { Age = 12, Email = "testone@gmail.com", Id = 0, Name = "test user one" });
channel.AddPerson(new Person { Age = 12, Email = "testtwo@gmail.com", Id = 1, Name = "test user two" });
channel.AddPerson(new Person { Age = 12, Email = "testthree@gmail.com", Id = 2, Name = "test user three" });

Console.WriteLine("There {0} persons", channel.GetAllPerson().Count());
//Delete one
Console.WriteLine("Deleting person with id on 0");
channel.DeletePerson("0");
Console.WriteLine("There {0} persons", channel.GetAllPerson().Count());
Console.Read();

Console.WriteLine("Updating person with Id of 1");
var toUpdate = channel.GetPerson("1");
channel.UpdatePerson(toUpdate);
Console.WriteLine("Update done");

//Display to account
Console.WriteLine(channel.GetAllPerson().Count());

Console.ReadKey();

To finish lets look at some of the advantages which come with REST.

Caching:  When RESTful endpoints are asked for data using HTTP, the HTTP verb used is GET. Resources returned in response to a GET request can be cached in many different ways. Conditional GET, which is a way that a client can check with the service if his version of the data is still the current version, is an optional implementation detail a RESTful endpoint can implement that can further improve speed and scalability.
Scale-Out: REST encourages each resource to contain all of the states necessary to process a particular request. RESTful services are much easier to scale out when they fulfill this constraint and can be stateless.
Side Effects: RESTful services should have no side effects when you ask for a resource using GET (unfortunately, this constraint is easier to break than some of the other REST constraints).
Idempotent :The other two main HTTP verbs typically used as part of the uniform interface are PUT and DELETE. PUT is most often used when a user agent wants to modify a resource, and DELETE is self-descriptive. The important bit (and what the word idempotent describes) is that you can use these two verbs on a particular resource more than once, and the effect will be the same as the first time you used them—or at least there won’t be any further effect. This is reassuring when building reliable distributed systems in which errors, network failures, or latency might cause code to execute multiple times.
Interoperability: Many people tout SOAP as being the most interoperable way to implement client-server programs. But some languages and environments still don’t have SOAP toolkits. And some that do have toolkits are based on older standards that can’t always communicate with toolkits that implement newer standards. REST only requires an HTTP library to be available for most operations (an XML library, of course, is often useful as well), and it is certainly more interoperable than any RCP technology (including SOAP).
Simplicity: This advantage is more subjective than the others and can mean different things to different people. To me, the simplicity of using REST relates to URIs representing resources and the uniform interface.

Hope you enjoyed. Happy coding 🙂

Wpf WebBrowser control and silverlight IE security issue

Its long since I worked with WPF and silverlight :(. But for the last one week I have been playing around with both of them. The case scenario that I was trying to implement was a simple intercommunication between wpf and silverlight. The requirement was very simple, as I need to build a WPF user control that wraps a simple silverlight control which is hosted in WebBrowser control with a two way communication between the WPF client and the silverlight implementation via javascript.

I will briefly describe the implementation details so as to know how I got to the problem.

First, I created a silverlight application which was supposed to  have a edit box and a button. On the html page hosting the silverlight, I added javascript  functions that were supposed to set and get the text value of the textbox on the silverlight. Also I added a handler that will be handle  silverlight button click event

And just for testing my javascript, I added some two buttons on the html file and which worked which worked great.

Then, I created a WPF user control, which utilized WebBrowser control to host the silverlight xap file. And just to do it the hard way, I dynamically wrote the html for the WebBrowser control including the javascript functions and the silverlight button handler just like I did on the html page.

And to consume my user control, I created a simple WPF client, which had three controls on its main page and handler to be used when the silverlight button is clicked.

-My custom control

-Button to set the edit box on silverlight

-Button to get the value of the silverlight edit box.

And upto here everything worked fine. For more details on how to set up all this go to here

Having done all this, I expected that my when I run my WPF client, I will see my silverlight control, but oops, I got this screen 😦

silverlight

This is a security alert informing that the content contain some ActiveX components. WebBrowser  will display a warning everytime you load the component. This took me to a thorough research on the web and found various articles pointing out that the solution was to add the mark of the web. Unfortunately, this did not work out  for me.

After researching and consulting, I ended up to this function  “CoInternetSetFeatureEnabled” which you can find more details here. And here was my quick implementation which I added to the user control which is basically some simple pinvoke. By looking at the function, you will note that it takes three parameters,

Feature entry: This is a value from  InternetFeatureList enumeration showing which feature to enable or disable. And so I added this enumeration:

internal enum INTERNETFEATURELIST
{
FEATURE_OBJECT_CACHING = 0,
FEATURE_ZONE_ELEVATION = 1,
FEATURE_MIME_HANDLING = 2,
FEATURE_MIME_SNIFFING = 3,
FEATURE_WINDOW_RESTRICTIONS = 4,
FEATURE_WEBOC_POPUPMANAGEMENT = 5,
FEATURE_BEHAVIORS = 6,
FEATURE_DISABLE_MK_PROTOCOL = 7,
FEATURE_LOCALMACHINE_LOCKDOWN = 8,
FEATURE_SECURITYBAND = 9,
FEATURE_RESTRICT_ACTIVEXINSTALL = 10,
FEATURE_VALIDATE_NAVIGATE_URL = 11,
FEATURE_RESTRICT_FILEDOWNLOAD = 12,
FEATURE_ADDON_MANAGEMENT = 13,
FEATURE_PROTOCOL_LOCKDOWN = 14,
FEATURE_HTTP_USERNAME_PASSWORD_DISABLE = 15,
FEATURE_SAFE_BINDTOOBJECT = 16,
FEATURE_UNC_SAVEDFILECHECK = 17,
FEATURE_GET_URL_DOM_FILEPATH_UNENCODED = 18,
FEATURE_ENTRY_COUNT = 19,
};

dwFlags: This specifies at what level do you want to put the feature control value. To my case I wanted it on the current process And so I declared the following constants

internal const uint SET_FEATURE_ON_THREAD = 0x00000001;
internal const uint SET_FEATURE_ON_PROCESS = 0x00000002;
internal const uint SET_FEATURE_IN_REGISTRY = 0x00000004;
internal const uint SET_FEATURE_ON_THREAD_LOCALMACHINE = 0x00000008;
internal const uint SET_FEATURE_ON_THREAD_INTRANET = 0x00000010;
internal const uint SET_FEATURE_ON_THREAD_TRUSTED = 0x00000020;
internal const uint SET_FEATURE_ON_THREAD_INTERNET = 0x00000040;
internal const uint SET_FEATURE_ON_THREAD_RESTRICTED = 0x00000080;

fEnable: And this is simply to indicate the feature should be enable or not. And so I did not want enable, since I wanted it for the current process, and the value was false.

With that in place I declared the function as below,

[DllImport("urlmon.dll")]
[return: MarshalAs(UnmanagedType.Error)]
internal static extern int CoInternetSetFeatureEnabled(uint FeatureEntry, [MarshalAs(UnmanagedType.U4)] uint dwFlags, bool fEnable);

In my ctor I called the function as below, passing the three arguements as per my scenario.

CoInternetSetFeatureEnabled((uint)INTERNETFEATURELIST.FEATURE_LOCALMACHINE_LOCKDOWN, SET_FEATURE_ON_PROCESS, false);

Hope this helps someone who might have the same case!

The best way to know you were here is to leave a comment, suggestions for topics you would like covered or even corrections.

Happy coding and see you here for another great post!

Oh Wait,please take a second to like our facebook page here. Thanks!!   🙂

%d bloggers like this: