a developer's notes – a semi-technical web development BLOG

December 19, 2014

Web API 2 – Sample HttpClient and Sample WebClient call

Filed under: C# — Duy Nguyen @ 11:29 am
Tags: , , , ,

Here is a sample request using the old WebClient.

//GET
using (var client = new WebClient())
{
	try
	{
		client.BaseAddress = "http://localhost/endpoint";
		// HTTP GET
		client.UseDefaultCredentials = true;
		jsonResponse = client.DownloadString(endpoint);
	}
	catch (WebException ex)
	{
		// Http Error
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
			var statusCode = (int)wrsp.StatusCode;
			var msg = wrsp.StatusDescription;
			throw new HttpException(statusCode, msg);
		}
		else
		{
			throw new HttpException(500, ex.Message);
		}
	}
}

//Post
public string PostRequest(string endpoint, NameValueCollection requestParams)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/x-www-form-urlencoded");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadValues(uri, "POST", requestParams);
			jsonResponse = Encoding.ASCII.GetString(response);
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}

// Post Json
public string PostRequestJson(string endpoint, string json)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/json");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadString(uri, "POST", json);
			jsonResponse = response;
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}


Here is a sample request using the new HttpClient.


HttpClientHandler handler = new HttpClientHandler()
{
	PreAuthenticate = true,
	UseDefaultCredentials = true
};


string reasonPhrase = "";
using (var client = new HttpClient(handler))
{
	client.BaseAddress = new Uri("http://localhost/endpoint");
	client.DefaultRequestHeaders.Accept.Clear();
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	
	// GET
	var response = client.GetAsync(endpoint).Result;
	// Post
	// var response = client.PostAsJsonAsync("http://localhost/endpoint", obj).Result;
	
	if (response.IsSuccessStatusCode)
	{
		var result = response.Content.ReadAsStringAsync().Result;
		return result;
	}
	else
	{
		reasonPhrase = response.ReasonPhrase;
		if (reasonPhrase.ToUpper() == "UNAUTHORIZED")
		{
			throw new KeyNotFoundException("Not authorized");
		}
		var apps = response.Content.ReadAsAsync<ResponseHeader>().Result;
		if (apps.ReturnCode.ToUpper() == "NOTFOUND" )
		{		
			throw new KeyNotFoundException(apps.Result);
		}
		else
		{
			throw new SystemException(apps.Result);
		}
	}
}

September 13, 2013

Google Maps API V3 with ASP.NET MVC 4 Example

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 1:06 pm
Tags: , , , , , , , , , , , ,

Here is the most basic example to get you started with Google Maps API V3. Create a basic template MVC 4 project and create a Home controller with this method:

    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }

Create a new view called Index.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@section Scripts {
    <script type="text/javascript"  src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
}

@section Styles { @*Styles needed for Google Maps to appear*@
    html { height: 100% }
    body { height: 100%; margin: 0px; padding: 0px }
}

<h2>Hello, Google Maps</h2>

<div style="width: 100%; height: 100%">
    <div id="map_canvas" style="width:100%; height:100%; margin-left: 100px"></div>
</div>

<script type="text/javascript">

    function initialize() {

        var canvas = $("#map_canvas");

        var latitude = 30.3296604;
        var longitude = -97.8743174;

        var latlng = new google.maps.LatLng(latitude, longitude);
        var options = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(canvas[0], options);

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(latitude, longitude),
            map: map
        });
    }

    $(function () { //Same as $(document).ready()
        initialize();
    });
       
</script>

Now run the application and you should see the map.

googleMapsExample

September 2, 2011

A Sample AJAX Script

Filed under: Javascript / JQuery — Duy Nguyen @ 2:51 am
Tags: , , , ,

Here is a sample AJax application. This was taken from “Ajax for Dummies”.

Here a user clicks on the “Display Message” button and it retrieves text from a text file and changes the text on the web page.

The application:


Here is the code:

<script language = “javascript”>

//Create the XMLHttpRequest object
var XMLHttpRequestObject = false;
 
if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) { //For Internet Explorer only
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
}
 
//a function that takes a path for the datasource location and the div's ID to put the retrieved data into
function getData(dataSource, divID){
    if(XMLHttpRequestObject) {

        //find the div to put the data into
        var obj = document.getElementById(divID);

        //open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]])
        XMLHttpRequestObject.open(“GET”, dataSource); 

        //Set up the anonymous function to call when ready. The actual request isn't until later
        XMLHttpRequestObject.onreadystatechange = function() 
        {   
            //readState[ 0:uninitialize, 1:loading, 2:loaded, 3:interactive, 4:complete ]
            //status 200 = OK
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                //data retrieved sucessfully so put the retrieved data into the div
                obj.innerHTML = XMLHttpRequestObject.responseText;
            }
        }
       
        //request server for data. And the anonymous function will handle the response back from the server
        XMLHttpRequestObject.send(null); //null is only used for GETs
    }
}

</script>
 
<body>
 
<H1>Fetching data with Ajax</H1>
    <form>
        <input type = 'button' value = 'Display Message' onclick = 'getData(‘http://localhost/ch01/data.txt’,‘targetDiv’)'>
    </form>
 
    <div id='targetDiv'>
        <p>The fetched data will go here.</p>
    </div>
 
</body>

The text file data.txt, contains:

This text was fetched using Ajax.

I hope this was simple enough. The interesting thing about this is that the function to handle the response is setup before the actual request call. Enjoy!

Create a free website or blog at WordPress.com.