Monthly Archives: April 2014

C#

Read and write files with stream in C#

fsutil
Very basic example how to read and write files. The util class is as following:

using System.IO;
using System.Text;

namespace Project.Dao
{
    public class FileSystemUtils
    {
        public static string ReadFile(string filePath, Encoding encoding)
        {
            using (var reader = new StreamReader(filePath, encoding))
            {
                return reader.ReadToEnd();
            }
        }

        public static void WriteFile(string filePath, string content, Encoding encoding)
        {
            using (var writer = new StreamWriter(filePath, false, encoding))
            {
                writer.Write(content);
            }
        }
    }
}

KISS paradigm enjoys.

C#

WebClient with automatic decompression in C#

trafcompr
To reduce traffic loading it is often used compression.

You may read scientific investigation about it on
web.mit.edu – Data Compression Techniques for Urban Traffic Data
and more technic on
research.vtu.ac.in – Gateway Traffic Compression.

When you use WebClient in your WebAPI (or etc.) application, downloaded file be in “confused” format. To solve the issue improve web client like this:

using System;
using System.Net;

namespace App
{
    public class WebClientSpecial : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest req = base.GetWebRequest(address);
            if (req is HttpWebRequest)
            {
                (req as HttpWebRequest).AutomaticDecompression = 
                  DecompressionMethods.Deflate | DecompressionMethods.GZip;
            }
            return req;
        }
    }
}

The DecompressionMethods in HttpWebRequest can be seen on
http://msdn.microsoft.com/en-us/library/system.net.decompressionmethods%28v=vs.110%29.aspx

C#

Wrap WebAPI RESTful service with Self Host in C#

selfhost
1. Create “Console Application”.
2. Change “.Net Framework Client Profile” to “.Net Framework”!
3. Open “Package Manager Console” and run:

Install-Package Microsoft.AspNet.WebApi.SelfHost -Version 4.0.30506

Version can be removed if you’re using .Net >= 5
4. Add your Models and Controllers to the project.
5. Add code to Main method:

class Program {
  public static void Main(string[] args) {
    var config = new HttpSelfHostConfiguration("http://localhost:8080");

    config.Routes.MapHttpRoute(
        "API Default", "api/{controller}/{id}", 
        new { id = RouteParameter.Optional });

    using (var server = new HttpSelfHostServer(config))
    {
        server.OpenAsync().Wait();
        Console.WriteLine("Press  to quit.");
        Console.ReadLine();
    }
  }
}

6. Run application!

More info,
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api,
http://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/

C#

Return statement in using block in C#

using
You may use such very lazy C# statement as using (proof)
But beginner programmers often repeat mistake like this: for example you want to download data from the internet using stream but return web-headers:

public static WebHeaderCollection Download(string url, string filePath)
{
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead(url))
        {
            using (var file = File.Create(filePath))
            {
                stream.CopyTo(file);
                return client.ResponseHeaders;
            }
        }
    }
}

Be aware of such case. The right (recommended) way is as this:

public static WebHeaderCollection Download(string url, string filePath)
{
    WebHeaderCollection result = null;
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead(url))
        {
            using (var file = File.Create(filePath))
            {
                stream.CopyTo(file);
            }
        }
        result = client.ResponseHeaders;
    }
    return result;
}

As you see, return statement is moved down after the using statement closing.

See also, http://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block

Using PrimeFaces SelectOneButton in JSF with ajax

selonebut
You are probably deal with SelectOneButton in PrimeFaces.
And as you can note, it actually doesn’t work correctly (in my case up to 3.4.2 version)!
So, to survive use next:

<h:form id="myForm">
    <p:selectOneButton value="#{MyBean.var}">
        <p:ajax event="change" update="@form" />
        <f:selectItem itemLabel="lable One" itemValue="1" />
        <f:selectItem itemLabel="lable Two" itemValue="2" />
        <f:selectItem itemLabel="lable Three" itemValue="3" />
    </p:selectOneButton>
</h:form>

And here you can see the hack:

<p:ajax event="change" update="@form" />

Now it works perfect!

And one more check: the CSS style for active button presents?

.ui-buttonset .ui-state-active {background-color: red;}