Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, May 14, 2009

Lambda Expression

Good article that explains lambda expressions:

http://www.developingfor.net/c-30/upgrade-your-c-skills-part-3-lambda-expressions.html

C# extention methods

Very nice feature.
According to definition: "Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type"

Example:

namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

And use it:
string s = "Hello Extension Methods";
int i = s.WordCount();

Note the following:
  1. Extensions should be defined in a static class
  2. Extensions should be defined in a static methods
  3. First parameter should be "this {class} {var}"

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);

}