Navigation

Sunday 13 November 2016

Retrieving/Uploading image using ASP.NET Web API.

A. Create the Window Application


STEP 1: In Visual Studio, create a new Windows application and design the form like this.


      This Windows application is created for updating employee profile pic.
It get and save employee image, though Api.





STEP 2: Install the Web API Client Libraries


Use NuGet Package Manager to install the Web API Client Libraries package.

Tools=> NuGet Package Manager=>Manage NuGet Package Manager Solution..

STEP 3: Search and install following package.


Install-Package Microsoft. Asp Net. WebApi. Client

STEP 4: Paste the following code.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using Newtonsoft.Json;


namespace Image
{
    public partial class Form1 : Form
    {    

        public Form1()
        {
            InitializeComponent();
        }      

        private void button1_Click(object sender, EventArgs e)
        {

            HttpClient client = new HttpClient();
     
            client.BaseAddress = new Uri("http://xyz.com/ImageWebApi/");
           // client.BaseAddress = new Uri(" http://localhost:55106/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = new HttpResponseMessage();
            byte[] mybytearray = null;
            response = client.GetAsync("api/employee?EmployeeNo=" + textBox1.Text).Result;
            if (response.IsSuccessStatusCode)
            {
                mybytearray = response.Content.ReadAsAsync<byte[]>().Result;//Here is the problem

                if (mybytearray.Count() > 0)
                {
                    Image img1 = byteArrayToImage(mybytearray);
                    pictureBox1.Image = img1;
                }
            }
        }


        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            using (MemoryStream mStream = new MemoryStream(byteArrayIn))
            {
                return Image.FromStream(mStream);
            }
        }

        public class Param
        {
            public byte[] EmpPic { get; set; }
            public int EmpId { get; set; }
        }
        private void btnSavePic_Click(object sender, EventArgs e)
        {
            int employeeNo = 0;

            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                employeeNo = Convert.ToInt32(textBox1.Text);
            }
            if (employeeNo > 0)
            {
                HttpClient client = new HttpClient();

                client.BaseAddress = new Uri(" http://localhost:55106/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = new HttpResponseMessage();

                Stream myStream = null;
                OpenFileDialog openFileDialog1 = new OpenFileDialog();

               // PalaceServices.PalaceServiceClient obj = new PalaceServices.PalaceServiceClient();



                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF| All files (*.*)|*.*";
                openFileDialog1.FilterIndex = 2;
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if ((myStream = openFileDialog1.OpenFile()) != null)
                        {
                            using (myStream)
                            {
                                // Insert code to read the stream here.
                                byte[] buffer = new byte[16 * 1024];
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    int read;
                                    while ((read = myStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        ms.Write(buffer, 0, read);
                                    }

                                    Param prm = new Param();
                                    prm.EmpPic = ms.ToArray();
                                    prm.EmpId = employeeNo;

                                    response = client.PostAsJsonAsync("api/employee", prm).Result;
                                    //response = client.GetAsync("api/employee?ms=" + jsonstring).Result;

                                    if (response.IsSuccessStatusCode)
                                    {
                                        //obj.SaveEmployeeImage(ms, 905);
                                        Image img1 = byteArrayToImage(ms.ToArray());
                                        pictureBox1.Image = img1;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("EmployeeNo is Required");
            }
        }
    }
}
--------------------------------End Of Window Application -------------------------------------------------
Note: your Windows application completed here. Now Create WebApi through which you send image in byte[

B. Create new project in MVC and name it 'ImageWebApi'. Following is the detail of the project. 




STEP 2: Employee Controller C# code, copy and page to your controller.

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

using System.Xml;
using System.IO;
using System.Text;
using System.Data;

using Logic.DataLayer;
using System.Data.SqlClient;

using System.Drawing;
using System.Web;

namespace ImageWebApi.Controllers
{
    public class EmployeeController : ApiController
    {
     

        string Path = @"D:\Projects\Dev\ImageWebApi\EmpPic\";
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpPost]
        public byte[] GetEmployeeImage(string EmployeeNo)
        {
            MemoryStream ms = new MemoryStream();
            SQL obj = new SQL();
            DataSet ds = new DataSet();
            try
            {
                obj.AddParameter("@EmployeeNo", DbType.String, ParameterDirection.Input, 0, EmployeeNo);
                ds = obj.ExecuteDataSet("p_GetEmployeeimage");
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    string path = Path + Convert.ToString(ds.Tables[0].Rows[0]["PicturePath"]);
                    if (File.Exists(path))
                    {
                        Image imageIn = Image.FromFile(path);
                        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    else
                    {
                        Path = @"D:\Projects\Dev\ImageWebApi\Images\no_image.png";
                        Image imageIn = Image.FromFile(Path);
                        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }                  
                }
                else
                {
                    string Path = @"D:\Projects\Dev\ImageWebApi\Images\no_image.png";
                    Image imageIn = Image.FromFile(Path);
                    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                }
            }
            catch (Exception s)
            { throw (s); }

            return ms.ToArray();
        }
        private void SaveFileOnDisk(MemoryStream ms, string EmployeeNo)
        {
            try
            {
                SQL obj = new SQL();
                obj.AddParameter("@EmployeeNo", DbType.String, ParameterDirection.Input, 0, EmployeeNo);
                DataTable dt = obj.ExecuteDataSet("p_getEmployeeID").Tables[0];

                if (dt.Rows.Count > 0)
                {
                    int Employeeid = Convert.ToInt32(dt.Rows[0]["EmployeeID"]);
                    using (var original = Image.FromStream(ms))
                    {
                        original.Save(Path + "\\" + Employeeid + ".jpg");
                    }
                    UpEmployeeImage(Employeeid);
                }
            }
            catch (Exception ex)
            {
                //lblMsg.Text = "Please try again later.";
            }
        }

        private int UpEmployeeImage(int EmployeeID)
        {

            SQL obj = new SQL();
            int temp;
            try
            {
                obj.AddParameter("@EmployeeID", DbType.Int32, ParameterDirection.Input, 0, EmployeeID);
                temp = obj.ExecuteNonQuery("[p_UpEmployeeimage]");
            }
            catch (Exception s)
            { throw (s); }

            return temp;
        }

        public class Param
        {
            public byte[] EmpPic { get; set; }
            public int EmpId { get; set; }
        }
        [HttpPost]
        public bool SaveEmployeeImage(Param ms)
        {
            SQL obj = new SQL();
            DataSet ds = new DataSet();
            try
            {
                MemoryStream ms1 = new MemoryStream(ms.EmpPic);
                SaveFileOnDisk(ms1, ms.EmpId.ToString());

            }
            catch (Exception s)
            { throw (s); }

            return true;
        }
    }
}

--------------------------End of Employee Controller Class----------------------------------------


STEP 3: This class is used to connect SQL Server so, you can create your own class or directly write connection in employee controller only. This is your choice. For help I put code of SQL class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;
using System.Configuration;
using System.ComponentModel;
using System.Reflection;
using Logic.DataLayer;
namespace Logic.DataLayer
{
    public class SQL : IDisposable
    {

        SqlCommand cmd = null;
        SqlConnection sqlCon = null;
        string sqlSTR = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;

        public SQL()
        {
            InitialzeConnection();
        }
        private void InitialzeConnection()
        {

            if (sqlCon == null)
                sqlCon = new SqlConnection(sqlSTR);

            if (sqlCon.State != ConnectionState.Closed)
                sqlCon.Close();
            sqlCon.Open();
            cmd = new SqlCommand();
            cmd.Connection = sqlCon;

        }
        public void Dispose()
        {
            sqlCon.Dispose();
            cmd.Dispose();
        }
        public void AddParameter(string pName, DbType type, ParameterDirection direction, int size, object value)
        {
            DbParameter p = new SqlParameter();
            p.DbType = type;
            p.ParameterName = pName;
            p.Direction = direction;
            p.Size = size;
            p.Value = value;
            cmd.Parameters.Add(p);
        }
        public DataSet ExecuteDataSet(string pName)
        {
            SetCMDName(pName);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            OutputParameters();
            Dispose();
            return ds;
        }
        DbParameter[] param = null;

        public DbParameter[] OutParams
        {
            get { return param; }
        }
        private DbParameter[] OutputParameters()
        {
            param = new DbParameter[cmd.Parameters.Count];
            int i = 0;
            foreach (DbParameter dp in cmd.Parameters)
            {
                if (dp.Direction == ParameterDirection.Output)
                {
                    param[i] = dp;
                } i++;
            }
            return param;
        }
        private void SetCMDName(string pName)
        {
            cmd.CommandText = pName;
            cmd.CommandType = CommandType.StoredProcedure;
        }      

    }
}
-----------------------------------------End SQL Class---------------------------------------------


No comments:

Post a Comment