Thursday, 5 June 2014

Calling a MVC Web Api from Advance Rest Client Chrome

In this article we are going to see how to call a MVC web api from the Rest client, For do this first we have to create a MVC Web API with following HTTP methods GET, POST, PUT, DELETE

In the Following code we are taking a 4 GET methods
1 with returning a Complex object ,
1 which takes id as input and return the corresponding Student. along with url because id is mention in route config.
1 which takes name as input, values are submitted in query string.
1 which takes name , id as input, so one value is mapped in url, another one in Query string.

     // GET api/Student
        public IEnumerable<Student> Get()
        {
            AddData();
            return _students;
        }

        //GET api/student?name=rajesh
        public Student Get(string name)
        {
            AddData();
            return _students.Where(x => x.Name == name).FirstOrDefault();
        }

        // GET api/Student/1
        public Student Get(int id)
        {
            AddData();
            return _students.Where(x => x.Id == id).FirstOrDefault();
        }

        // GET api/student/1?name=rajesh
        public Student Get(int id,string name)
        {
            AddData();
            return _students.Where(x => x.Id == id && x.Name==name).FirstOrDefault();
        }

        private void AddData()
        {
            Department dep = new Department() { Id = 1, Name = "computer" };
            List<Marks> marks = new List<Marks>() { new Marks() { Mark = 85, 
           SubectName = "Computer" }, new Marks() { Mark = 78, SubectName = "Electronic" } };
            _students.Add(new Student() { Age = 12, Id = 1, Depart = dep, Name = "rajesh",              Rank = 1, Subjects = new string[] { "Computer", "Electronic" }, 
           SubMarks = marks });

        }




1 POST method which intakes the Complex object

        // POST api/Student
        public void Post([FromBody]List<Student> students)
        {
            _students.AddRange(students);           
        }


1 DELETE method

        // PUT api/Student/1
        public void Put(int id, [FromBody]Student value)
        {
            AddData();
            Student stud = _students.Where(x => x.Id == id).FirstOrDefault();
            stud = value;
        }

1 PUT Method with Authorization passing in header

        // DELETE api/Student/1
        public void Delete(int id)
        {
            string auth = Request.Headers.Authorization.Scheme;
            AddData();
            Student std = _students.Where(x => x.Id == id).FirstOrDefault();
            if(std!=null)
            _students.Remove(std);

        }


Full code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace mvcSAMPLE.Controllers
{
    public class Department
    {
        public string Name {set;get;}

        public int Id {set;get;}

    }

    public class Marks
    {
        public string SubectName {set;get;}

        public int Mark {set;get;}

    }

    public class Student
    {
        public int Id { set; get; }

        public string Name { set; get; }

        public int Age { set; get; }

        public string[] Subjects { set; get; }

        public Department Depart { set; get; }

        public List<Marks> SubMarks { set; get; }

        public int Rank { set; get; }

    }

    public class StudentController : ApiController
    {
        List<Student> _students = new List<Student>();

        // GET api/Student
        public IEnumerable<Student> Get()
        {
            AddData();
            return _students;
        }

        //GET api/student?name=rajesh
        public Student Get(string name)
        {
            AddData();
            return _students.Where(x => x.Name == name).FirstOrDefault();
        }

        // GET api/Student/1
        public Student Get(int id)
        {
            AddData();
            return _students.Where(x => x.Id == id).FirstOrDefault();
        }

        // GET api/student/1?name=rajesh
        public Student Get(int id,string name)
        {
            AddData();
            return _students.Where(x => x.Id == id && x.Name==name).FirstOrDefault();
        }

        private void AddData()
        {
            Department dep = new Department() { Id = 1, Name = "computer" };
            List<Marks> marks = new List<Marks>() { new Marks() { Mark = 85, SubectName = "Computer" }, new Marks() { Mark = 78, SubectName = "Electronic" } };
            _students.Add(new Student() { Age = 12, Id = 1, Depart = dep, Name = "rajesh", Rank = 1, Subjects = new string[] { "Computer", "Electronic" }, SubMarks = marks });

        }

        // POST api/Student
        public void Post([FromBody]List<Student> students)
        {
            _students.AddRange(students);           
        }

        // PUT api/Student/1
        public void Put(int id, [FromBody]Student value)
        {
            AddData();
            Student stud = _students.Where(x => x.Id == id).FirstOrDefault();
            stud = value;
        }

        // DELETE api/Student/1
        public void Delete(int id)
        {
            string auth = Request.Headers.Authorization.Scheme;
            AddData();
            Student std = _students.Where(x => x.Id == id).FirstOrDefault();
            if(std!=null)
            _students.Remove(std);
        }
    }

}


Route config:

       config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );



Chrome:
Now install the advance rest client in chrome.

In the Rest client three things are important
1. Url passing for request along with methods selected.
2. Passing the header information and Body information
3. Content Type selection

In our sample Content-Type is application/json , we will use the Body section on the POST method.

For the various Get Methods:

Default Get Method
url : http://localhost:53986/api/Student

Get with parameter 
paramter id:
url : http://localhost:53986/api/Student/1


parameter name:
url : http://localhost:53986/api/Student?name=rajesh






paramter id, name:
url : http://localhost:53986/api/Student/1?name=rajesh







For all the three queries we have the same output

Output:





POST Method 
url : http://localhost:53986/api/Student


FromBody we can only able to pass one parameter







In this post content we have to pass a complex object which is a list,now we are going to see how to pass a complex object for rest client.

For object we have to use {}
For array or List we have to use []
then next thing we have to place the property name as key in the left side with in double quotes and value in the right side of colon , string are mention in double quotes values , integer are as it is.


For example :
*************
Array or list of string to pass as a input to API then. ["Rajesh","suresh"]. 

If an object is need to be pass then  { "Name":"Rajesh","Age":10}

if an property is an array of another object then
"submarks" : [ {"Mark":80,"subject":"Computer"},{"Mark":97,"subject":"Electronic"} ]



POST content :

[
 {
   "Id"            :   1,
   "Name"      :   "Rajesh",
   "Age"         :   12,
   "Subjects"   :   ["Computer","Electronics"],
  "Depart"      :   {
"Name":"Computer Science",
"Id"  :1
                       },
  "SubMarks"  :   [
{ "SubectName":"Computer", "Mark":95 },
                          { "SubectName":"Electronics","Mark":84}
                       ],
  "Rank"          :  13
 },
{
   "Id"              :   2,
   "Name"        :   "Suresh",
   "Age"           :   8,
   "Subjects"    :   ["Computer","Electronics"],
   "Depart"       :  {
                              "Name":"Computer Science",
"Id":1
                       },
   "SubMarks"  :  [
{"SubectName":"Computer","Mark":100},
{"SubectName":"Electronics","Mark":100}
                       ],
   "Rank"  :  1
  }

]



Output:



















DELETE method
url : http://localhost:53986/api/Student/1








PUT Method 

url : http://localhost:53986/api/Student/1


From this article you can learn how to call the MVC web api from the rest client.


Tuesday, 3 June 2014

Customize the Scrollbar in WPF (XAML)

In this article we are going to see how to create a customize scrollbar in WPF, for that first we have to understand about the Scrollbar, scrollbar is made up with a Track, Two RepeatButtons, and a Thumb.
now we are going to create a Style for each one.

Thumb: For thumb we have to make border with curve
Repeat Buttons: Make the Visible as Transparent
Track : Make a gradient path

Resource:


<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   

    <LinearGradientBrush x:Key="thumbbrush" StartPoint="0,0" EndPoint="1,0">
        <GradientStopCollection>
            <GradientStop Color="#c1dbe8" Offset="0" />
            <GradientStop Color="#FF2A56CB" Offset="0.6" />
            <GradientStop Color="#066caa" Offset="1" />
        </GradientStopCollection>
    </LinearGradientBrush>
   
    <LinearGradientBrush x:Key="trackbrush" StartPoint="0,0" EndPoint="1,0">
        <GradientStopCollection>
            <GradientStop Color="#bcbcbc" Offset="0"/>
            <GradientStop Color="#eeeeee" Offset="0.75"/>
            <GradientStop Color="#eeeeee" Offset="1" />
        </GradientStopCollection>
    </LinearGradientBrush>
   

    <ControlTemplate x:Key="repeattemplate" TargetType="{x:Type RepeatButton}">       
            <Rectangle Fill="Transparent" />      
    </ControlTemplate>
   

    <ControlTemplate x:Key="thumbtemplate" TargetType="{x:Type Thumb}">       
            <Border Background="{TemplateBinding Background}" CornerRadius="10,10,10,10"                          Padding="1" />                   
    </ControlTemplate>
   

    <ControlTemplate x:Key="verticalscrollbar" TargetType="{x:Type ScrollBar}">
        <Grid>
            <Border CornerRadius="10,10,10,10" Background="{StaticResource trackbrush}"                          BorderBrush="#999999"
                    BorderThickness="1" Padding="1">
                <Track x:Name="PART_Track" IsDirectionReversed="True">
                    <Track.DecreaseRepeatButton>
                        <RepeatButton Template="{StaticResource repeattemplate}"                                                    Command="ScrollBar.PageUpCommand" />
                    </Track.DecreaseRepeatButton>
                    <Track.Thumb>
                        <Thumb Template="{StaticResource thumbtemplate}" 
                               Background="{TemplateBinding Background}"
                               BorderThickness="1" 
                               BorderBrush="{TemplateBinding BorderBrush}" />
                    </Track.Thumb>
                    <Track.IncreaseRepeatButton>
                        <RepeatButton Template="{StaticResource repeattemplate}"                                             Command="ScrollBar.PageDownCommand" />
                    </Track.IncreaseRepeatButton>
                </Track>
            </Border>
        </Grid>
    </ControlTemplate>

   
    <Style x:Key="scrollstyle" TargetType="ScrollBar">
        <Setter Property="MinWidth" Value="20" />
        <Setter Property="Background" Value="{StaticResource thumbbrush}"/>
        <Setter Property="BorderBrush" Value="#999999" />
        <Setter Property="Template" Value="{StaticResource verticalscrollbar}" />
    </Style>
   


</ResourceDictionary>

Xaml:

    <Grid Height="319" VerticalAlignment="Bottom">
        <Grid.RowDefinitions>
            <RowDefinition Height="19" />
            <RowDefinition />
            <RowDefinition Height="40" />
        </Grid.RowDefinitions>
       
        <ScrollBar Grid.Row="1" Style="{StaticResource scrollstyle}" Maximum="100"                               ViewportSize="36" >
        </ScrollBar>

    </Grid>


Output:



From this article you will learn how to create a customize Scrollbar.