Monday 26 May 2014

Create a sample web api with self Hosting

In this article we are going to see how to create a sample web api and self host it for this first create a Console Application , then using Nuget package manager install the following one
  • Microsoft.AspNet.WebApi.SelfHost
Then Start to build the application, in our example we can take the Employees as sample.


Api Controller:
******************
    public class Employee
    {
        public string Name { setget; }

        public int Age { setget; }
       
    }

    public class EmployeeController:ApiController
    {
        private static readonly IEmployeeRepository emp = new EmployeeRepository();

        public IEnumerable<Employee> Get()
        {
            return emp.GetAllEmployee();
        }

        public Employee Get(string name)
        {
            return emp.GetAllEmployee().Where(x => x.Name == name).FirstOrDefault();
        }

        [ActionName("PostEmployee1")]
        [HttpPost]
        public int Emp(string name,int age)
        {
            emp.GetAllEmployee().Add(new Employee() {Name=name ,Age=age});
            return emp.GetAllEmployee().Count;
        }

        [ActionName("PostEmployee2")]
        [HttpPost]
        public int PostEmployee([FromBody]Employee empl)
        {
            emp.GetAllEmployee().Add(new Employee() { Name = empl.Name, Age = empl.Age });
            return emp.GetAllEmployee().Count;
        }

    }


Repository:

    interface IEmployeeRepository
    {
        List<Employee> GetAllEmployee();
    } 

    public class EmployeeRepository:IEmployeeRepository
    {
        List<Employee> employees = new List<Employee>() { new Employee()                                       {Name="Ram",Age=34},new Employee(){Name="Kumar",Age=30}};
        public List<Employee> GetAllEmployee()
        {
            return employees;
        }
    }


Assembly Resolver:
******************
    public class EmpAssemblyResolver:IAssembliesResolver
    {
        private string path;

        public EmpAssemblyResolver(string assempath)
        {
            this.path = assempath;
        }

        public ICollection<System.Reflection.Assembly> GetAssemblies()
        {
            List<Assembly> assemblies= new List<Assembly>();
            assemblies.Add(Assembly.LoadFrom(path));
            return assemblies;
        }
    }


Hosting :

 
Uri _baseaddress = new Uri("http://localhost:8070/");
            var assemloc = Assembly.GetExecutingAssembly().Location;
            string assempath = assemloc.Substring(0, assemloc.LastIndexOf("\\")) + @"\WebApiSamples.exe";
           
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseaddress);
            config.Services.Replace(typeof(IAssembliesResolver), new EmpAssemblyResolver(assempath));
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });

            using (HttpSelfHostServer hostserver = new HttpSelfHostServer(config))
            {
                Console.WriteLine("Waiting ....");
                hostserver.OpenAsync().Wait();

                GetEmployees();
                PostEmployeeinUrl();
                Console.WriteLine();
                Console.Read();
            }
           


Main Program:


    class Program
    {
        static void Main(string[] args)
        {
           
            Uri _baseaddress = new Uri("http://localhost:8070/");
            var assemloc = Assembly.GetExecutingAssembly().Location;
            string assempath = assemloc.Substring(0, assemloc.LastIndexOf("\\")) + @"\WebApiSamples.exe";
           
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseaddress);
            config.Services.Replace(typeof(IAssembliesResolver), new EmpAssemblyResolver(assempath));
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}",                       defaults: new { id = RouteParameter.Optional });

            using (HttpSelfHostServer hostserver = new HttpSelfHostServer(config))
            {
                Console.WriteLine("Waiting ....");
                hostserver.OpenAsync().Wait();

                GetEmployees();
                PostEmployeeinUrl();
                Console.WriteLine();
                Console.Read();
            }
           



        }

        private static async void GetEmployees()
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage res = await client.GetAsync(new                                                              Uri("http://localhost:8070/api/Employee/Get"));
                res.EnsureSuccessStatusCode();
                string successmess = await res.Content.ReadAsStringAsync();
                var empl = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Employee>>(successmess);

                Console.WriteLine("Employee Count "+ empl.Count);
                foreach (Employee e in empl)
                {
                    Console.WriteLine("Name "+e.Name+", Age : "+e.Age);
                }

            }
            catch (Exception ex)
            {

            }
        }

        private static async void PostEmployeeinUrl()
        {
            try
            {

                Console.WriteLine("");
                HttpClient client = new HttpClient();
                var postdat = new List<KeyValuePair<string, string>>();
                postdat.Add(new KeyValuePair<string, string>("name", "sur"));
                postdat.Add(new KeyValuePair<string, string>("age", "23"));
                HttpContent content = new FormUrlEncodedContent(postdat);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage res = await client.PostAsync(new     
                    Uri("http://localhost:8070/api/Employee/PostEmployee1"),content);
                res.EnsureSuccessStatusCode();
                var count = res.Content.ReadAsStringAsync();
                Console.WriteLine();
                Console.WriteLine("Adding a new employee");
                Console.WriteLine("Added succesfully ,EmployeeCount " + count.Result);
            }
            catch (Exception ex)
            {

            }
        }

        private static async void PostEmployee()
        {
            try
            {
               
                Console.WriteLine("");
                HttpClient client = new HttpClient();               
                MediaTypeFormatter formatter =  new JsonMediaTypeFormatter();
                HttpContent content = new ObjectContent<Employee>(new Employee()
                            {Name="r",Age=24},formatter,"application/json");
                HttpResponseMessage res = await client.PostAsync(new 
                           Uri("http://localhost:8070/api/Employee/PostEmployee2"), content);
                res.EnsureSuccessStatusCode();
                var count = res.Content.ReadAsStringAsync();
                Console.WriteLine();
                Console.WriteLine("Adding a new employee");
                Console.WriteLine("Added succesfully ,EmployeeCount "+count.Result);
            }
            catch (Exception ex)
            {

            }
        }

    }

Output:



When invoke from advance rest client 
url :
http://localhost:8070/api/Employee/PostEmployee1?name=rajesh&age=30

output:
3

From this article you can learn how to create the sample web Api and self host it.

Create a Custom Panel (StackVanishing Panel) in Xaml (WPF)

In this article we are going to see how to create a Stack Vanishing Panel, Stack Vanishing Panel is ordering the elements in the Stack order and keep on decrease the visibility of elements like seeing an object from a long view.The Required output for us is looks like the following one.




So to do that Panel, we need some reducing factor that is called ZFactor and we make the child objects as constant starting height.

Custom Panel :
***********
  class StackVanishingPanel:Panel
    {
        private Size _arrangesize = new Size();

        public double ItemHeight
        {
            get { return (double)GetValue(ItemHeightProperty); }
            set { SetValue(ItemHeightProperty, value); }
        }
       
        public static readonly DependencyProperty ItemHeightProperty =
            DependencyProperty.Register("ItemHeight", typeof(double), typeof(StackVanishingPanel), new 
                                                        FrameworkPropertyMetadata(50.0D,               
                                                        FrameworkPropertyMetadataOptions.AffectsMeasure
                                                        |FrameworkPropertyMetadataOptions.AffectsArrange));


        public double ZFactor
        {
            get { return (double)GetValue(ZFactorProperty); }
            set { SetValue(ZFactorProperty, value); }
        }
       
        public static readonly DependencyProperty ZFactorProperty =
            DependencyProperty.Register("ZFactor", typeof(double), typeof(StackVanishingPanel), new 
                                         FrameworkPropertyMetadata(0.5D,
                                         FrameworkPropertyMetadataOptions.AffectsArrange));

        protected override Size MeasureOverride(Size availableSize)
        {

            if (availableSize.Width == double.PositiveInfinity && availableSize.Height ==                                                                                     double.PositiveInfinity)
                return Size.Empty;

            for (int i = 0; i < InternalChildren.Count; i++)
            {
                InternalChildren[i].Measure(new Size(availableSize.Width, ItemHeight));
            }

            return new Size(availableSize.Width, ItemHeight * InternalChildren.Count);
        }


        protected override Size ArrangeOverride(Size finalSize)
        {
            _arrangesize = finalSize;
            int currentindex = 0;
            for (int i = 0; i <InternalChildren.Count; i++,currentindex++)
            {
                Rect _newrect = GetRect(currentindex);
                InternalChildren[i].Arrange(_newrect);
            }

            return base.ArrangeOverride(finalSize);
        }

        private Rect GetRect(int index)
        {
            double _zfactor = Math.Pow(ZFactor, index);
            Size itemsize = new Size(_arrangesize.Width * _zfactor, ItemHeight * _zfactor);

            double left = (_arrangesize.Width - itemsize.Width) * 0.5;
            double top = _arrangesize.Height;

            for (int i = 0; i <= index; i++)
            {
                top -= Math.Pow(ZFactor, i) * ItemHeight;
            }

            Rect newrect = new Rect(itemsize);
            newrect.Location = new Point(left, top);
            return newrect;
        }
              

    }

Xaml:
*****


       <local:StackVanishingPanel ItemHeight="50" ZFactor="0.88">
            <Button Background="Orange" Foreground="white"> 1</Button>
            <Button Background="Gray" Foreground="white"> 2</Button>
            <Button Background="SteelBlue" Foreground="white"> 3</Button>
            <Button Background="Red" Foreground="white"> 4</Button>
            <Button Background="Magenta" Foreground="white"> 5</Button>
            <Button Background="Navy" Foreground="white"> 6</Button>
            <Button Background="Black" Foreground="white"> 7</Button>           
        </local:StackVanishingPanel>






From this article you can learn how to create a Stack Vanishing Panel.