Monday, April 27, 2009

WCF Rest Client

In my humble opinion the easiest way to create REST client in .NET is using "WCF REST Starter Kit Preview"

Step 1
Add references to:

  • Microsoft.Http.dll
  • Microsoft.Http.Extention.dll
These dlls could be found in installation directory of WCF REST Starter Kit (C:\Program Files (x86)\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies\... in my case)

Step 2

using Microsoft.Http;


Step 3
Create HTTP client

HttpClient http = new HttpClient(baseUrl);

You can also add authentication (basic)

http.TransportSettings.Credentials = new NetworkCredential(userName, password);


Step 4 (Get)
Get resource

// Optional. Add query parameters
HttpQueryString query = new HttpQueryString();
query.Add("f", "xml");
// Add relative uri of a resource
Uri uri = new Uri("resource_name", UriKind.Relative);
// Get Resource
HttpResponseMessage resp = http.Get(uri,query);


Step 4 (Post/Put/Delete/)
HttpClient has support of Post/Put/Delete methods

Read password C# console

Method to read password from console:



using System.Collections;
...
public static string ReadPassword() {

Stack pass = new Stack();

for (ConsoleKeyInfo consKeyInfo = Console.ReadKey(true);
consKeyInfo.Key != ConsoleKey.Enter; consKeyInfo = Console.ReadKey(true))
{
if (consKeyInfo.Key == ConsoleKey.Backspace)
{
try
{
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write(" ");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
pass.Pop();
}
catch (InvalidOperationException)
{
Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
}
}
else {
Console.Write("*");
pass.Push(consKeyInfo.KeyChar.ToString());
}
}
string[] password = (string[])pass.ToArray();
Array.Reverse(password);
return string.Join(string.Empty, password);

}

Wednesday, April 1, 2009

Resources and Spring

Spring provides an easy way to store resources. For instance you need to use an xslt transformation file in your class.

1. Add resource member in your class
 
public class A {
...
private org.springframework.core.io.Resource myResource;
public void setMyResource(org.springframework.core.io.Resource myResource) {
this.myResource = myResource;
}
...
// You Code
// Now you can get the file/stream from the resource:
// myResource.getFile();
// myResource.getInputStream();
...
}


2. Define the resource in spring configuration

<bean id="myBean" class="A">
<property name="myResource">
<value type="org.springframework.core.io.Resource">{path}</value>
</property>
</bean>



The {path} could be:
- /WEB-INF/...
- classpath:/...
- file:/c:/...