Computer Magic Logo
C# client

Monday, March 14, 2016

Published by Aristotelis Pitaridis

Usually in a web application we retrieve the data using client side code but there are times that we want to retrieve the data at the server using C# code. This method is also useful when we want to retrieve the data from a desktop application.

In order to make the same example using C# code we will have to define a new model which is going to be the object that the Update action will return.

namespace ComputerMagic.Models
{
    public class UpdateResultModel
    {
        public int ID { get; set; }
        public bool ProductExistsInDatabase { get; set; }
    }
}

Now we paste the following code in a new page.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@using ComputerMagic.Models
@{
    Layout = null;


    string responseString;

    // Get
    using (var client = new WebClient())
    {
        responseString = client.DownloadString("http://localhost:54599//umbraco/api/ProductsApi/GetAllProducts");
    }

    List<Product> MyProducts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(responseString);

    // Get
    using (var client = new WebClient())
    {
        responseString = client.DownloadString("http://localhost:54599//umbraco/api/ProductsApi/GetProductById/2");
    }

    Product MyProduct = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(responseString);

    // Post
    using (var client = new WebClient())
    {
        var values = new System.Collections.Specialized.NameValueCollection();
        values["ID"] = "3";
        values["Name"] = "Product 4";
        values["Price"] = "42";

        var response = client.UploadValues("http://localhost:54599/umbraco/api/ProductsApi/Update", values);

        responseString = System.Text.Encoding.Default.GetString(response);
    }
    UpdateResultModel UpdateResult = Newtonsoft.Json.JsonConvert.DeserializeObject<UpdateResultModel>(responseString);
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@Umbraco.Field("title")</title>
    <meta name="description" content="@Umbraco.Field("description")">
    <meta name="keywords" content="@Umbraco.Field("keywords")">
</head>
<body>
    <h2>All Products</h2>
    <div>
        @foreach (var item in MyProducts)
        {
            <p>@item.Name : € @item.Price</p>
        }
    </div>

    <h2>One Product</h2>
    <div>
        @MyProduct.Name : € @MyProduct.Price
    </div>

    <h2>Update Product</h2>
    <div>
        ID returned : @UpdateResult.ID<br />
        Product Exists : @UpdateResult.ProductExistsInDatabase
    </div>
</body>
</html>