Developing Windows Store App Part 2: REST Service implementation


Today’s blog post will discass how to implement REST service by using ASP.NET Web API. To expose data to our Windows Store app, we need to implement some kind of REST or Soap service. For this sample we are going to create Rest service, which will expose basic data operation to our Windows 8 Store client.

1. Open you previous EFModel solution in Visual Studio 2012.

2. Right click at the solution and choose Add New Project

3. Select ASP.NET MVC 4 Web Application, Enter the name of the project.

4. Click OK button.

5. On the next Dialog select Web API, and click OK button.

6. Initial skeleton for RESTService is created.

7. Add Reference of EFModel project.

Now we are going to implement Controller.

8. Right Click on RestService project ->Add New Controller.

9. Enter CExplorer name, and click OK.

Implementation of the controller shows the next listing:

 public class CExplorerController : ApiController
    {
        // GET CExplorer
        [HttpGet]
        public List Place()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    var lst = ctx.Places.ToList();
                    return lst;
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        // GET CExplorer/5
        [HttpGet]
        public Place Place(int id)
        {
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    return ctx.Places.Where(x => x.PlaceID == id).FirstOrDefault();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        // GET CExplorer/5
        [HttpGet]
        public IEnumerable Search(string queryText)
        {
            try
            {
                //queryText = queryText;
                using (CExplorerContext ctx = new CExplorerContext())
                {

                    var lst11 = ctx.Dishes.Where(x => x.Name.ToLower().Contains(queryText.ToLower())).Select(x => x.DishID).ToList();
                    var lst22 = ctx.Towns.Where(x => x.Name.ToLower().Contains(queryText.ToLower())).Select(x => x.TownID).ToList();

                    var lst = ctx.Places.ToList();

                    var ll = from p in ctx.Places
                             where
                             lst11.Contains(p.DishID) ||
                             lst22.Contains(p.TownID) ||
                             p.Name.ToLower().Contains(queryText.ToLower()) ||
                             p.Slogan.ToLower().Contains(queryText.ToLower())

                             select p;

                    var rr = ll.ToList();
                    return rr;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        // POST CExplorer
        [HttpPost]
        public void Place([FromBody]Place plc)
        {
            try
            {
                if (plc == null)
                    return;
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    if (plc.PlaceID == -1)
                    {
                        ctx.Places.Add(plc);
                        ctx.SaveChanges();
                    }
                    else
                    {
                        var p = ctx.Places.Where(x => x.PlaceID == plc.PlaceID).FirstOrDefault();
                        if (p == null)
                            return;

                        p.Name = plc.Name;
                        p.Slogan = plc.Slogan;
                        p.Description = plc.Description;
                        p.DishID = plc.DishID;
                        p.TownID = plc.TownID;
                        p.Image = plc.Image;
                        ctx.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        // GET Town
        [HttpGet]
        public List Town()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    return ctx.Towns.ToList();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        // GET Dish
        [HttpGet]
        public List Dish()
        {
            /// return new string[] { "value1", "value2" };
            ///
            try
            {
                using (CExplorerContext ctx = new CExplorerContext())
                {
                    // var ss= ctx.Dishes.ToString();
                    return ctx.Dishes.ToList();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
    }

10. Resolve using statement, that you can compile project.

11. Modify App_Start/WebApiConfig.cs file like the following listing:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "{controller}/Place/{id}",
                defaults: new { action = "Place", id = RouteParameter.Optional }
             );

            config.Routes.MapHttpRoute(
                name: "DefaultApi1",
                routeTemplate: "{controller}/Town",
               defaults: new { action = "Town" }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi2",
                routeTemplate: "{controller}/Dish",
                defaults: new { action = "Dish" }
            );

            config.Routes.MapHttpRoute(
                 name: "DefaultApi3",
                 routeTemplate: "{controller}/Search/{queryText}",
                defaults: new { action = "Search", queryText = RouteParameter.Optional }
             );
        }
    }

Defining connection string. For propery connection string definition you need to provide valid SQL login. You can achive this by creating new Login at SQL Server database, similar like picture below.

12. Add connection string to WebConfig file similar like the following.

<connectionStrings>
  <add name="cexplorer_db" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=cevap_db;Persist Security Info=True;User ID=testuser;Password=123;"/>
  </connectionStrings>

13. Set RestService as Startup project, and hit F5.

14. When IE appear, enter the following url adress: http://localhost:4636/cexplorer/place, to get all Places from the db.

Note: This is exactly what we inserted in Place Table, while we run EFTest console app from the previos blog post.

Now we have all instrastructure to start developing Windows Store app Ćevap Explorer. Source code for this blog can be found here.

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 23/09/2012, in .NET, C#, CodeProject, Metro style App, Windows 8 and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s