Monday, November 21, 2016

Upload Image though Web API, C# MVC

Introduction

Here I will explain how to post image via http or save save image throw web api


1)MVC Application

Home Controller: create Home controller in your MVC project and add two action Methods Index and . Index and UploadImage. 

        
using ImageUpload.Models;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace ImageUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public async Task< ActionResult> UploadImage(HttpPostedFileBase file)
        {
            MemoryStream target = new MemoryStream();
            file.InputStream.CopyTo(target);
            byte[] data = target.ToArray();
         
            //Assign Model
            ImageModel obj = new Models.ImageModel();
            obj.ImageName = file.FileName;
            obj.Base64ImageString= Convert.ToBase64String(data);
            
            using (var client = new HttpClient())
            {
                HttpResponseMessage resMsg =await client.PostAsJsonAsync("http://localhost:51071/api/ImageApi", obj);
                if (resMsg.IsSuccessStatusCode)
                {
                    ViewBag.Msg = "Image Uploaded.";
                    return View();
                }
            }
            ViewBag.Msg = "fail to upload Image.";
            return View("Index");
        }
    }

}

Model:

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

namespace ImageUpload.Models
{
    public class ImageModel
    {
        public string Base64ImageString { get; set; }
        public string ImageName { get; set; }
    }

}

Index View:

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h2> @ViewBag.Msg</h2>
    <table class="table-bordered" width="500px">
        <tr height="20px" bgcolor="grey">
            <td colspan="4"></td>
        </tr>
        <tr>
            <td width="20px" bgcolor="grey"></td>
            <td>Image</td>
            <td>
                <input type="file" name="file" />
                <input type="submit" />
            </td>
            <td width="20px" bgcolor="grey"></td>
        </tr>
        <tr height="20px" bgcolor="grey">
            <td colspan="4"></td>
        </tr>
    </table>

}

UploadImageView:

@{
    ViewBag.Title = "UploadImage";
}

<h2>@ViewBag.Msg</h2>


----------------------------x--------------x----------------x-------------------------------
Web API

Controller:

using ImageUpload.Models;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace ImageUpload.Controllers
{
    public class ImageApiController : ApiController
    {
        [Route("api/ImageApi")]
        [HttpPost]
        public HttpResponseMessage AddImageViaWebAPI(ImageModel Obj)
        {
            var filePath = HttpContext.Current.Server.MapPath("~/Images/" + Obj.ImageName);
            byte[] bytes = Convert.FromBase64String(Obj.Base64ImageString);
            Image image;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                image = Image.FromStream(ms);
                image.Save(filePath);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}


Simple Voting Application in ASP .Net

Introduction

Here I will explain how to make basic voting app in ASP.Net C#.
I will use cookies to identify unique user . (Note: User can vote again by clearing cookies.).

Reference: unknown.



















Store Vote

I am using a text file to store user votes . You have to just crate a text file  @"C/temp/Result.txt" .

Home.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Voting</title>
</head>
<body>
    <form id="form1" runat="server">
        <br />
        <div>
            <table>
                <tr>
                    <td colspan="3"><b>Is currency demonetization good or bad?</b></td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                            <asp:ListItem Value="Yes">Yes</asp:ListItem>
                            <asp:ListItem Value="No">No</asp:ListItem>
                            <asp:ListItem Value="NoIdea">No Comment</asp:ListItem>
                        </asp:RadioButtonList>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                    <td>
                        <asp:Button ID="btnVote" runat="server" OnClick="btnVote_Click" Text="Vote" />
                        <asp:Button ID="btnView" runat="server" Text="View Result" OnClick="btnView_Click" />
                    </td>
                </tr>
                <tr>
                    <td>Result:
                    </td>
                    <td width="10px"></td>
                    <td>
                        <label>
                            <asp:Label ID="lblMsg1" runat="server" Text="Label" Font-Bold="True"></asp:Label><br />
                            <asp:Label ID="lblMsg2" runat="server" Text="Label" Font-Bold="True"></asp:Label><br />
                            <asp:Label ID="lblMsg3" runat="server" Text="Label" Font-Bold="True"></asp:Label><br />
                            <asp:Label ID="lblMsg4" runat="server" Text="Label" Font-Bold="True"></asp:Label>
                        </label>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>

</html>

Home.aspx.cs (Code Behind)

using System;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMsg1.Visible = false;
        lblMsg2.Visible = false;
        lblMsg3.Visible = false;
        lblMsg4.Visible = false;
    }

    protected void btnVote_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["State"] == null)
        {
            foreach (ListItem item in RadioButtonList1.Items)
            {

                if (item.Selected == true)
                {
                    FileStream fs1 = new FileStream("C:\\temp\\Result.txt", FileMode.Append, FileAccess.Write);//Physical file path
                    StreamWriter sw1 = new StreamWriter(fs1);
                    sw1.WriteLine(item.Value);
                    sw1.Flush();
                    sw1.Close();
                    sw1.Close();
                    HttpCookie HC = new HttpCookie("State");
                    HC.Values["State"] = "Set";
                    HC.Expires = DateTime.Now.AddDays(2); //Added cookies Expires time
                    Response.Cookies.Add(HC);
                    lblMsg4.Visible = true;
                    lblMsg4.ForeColor = Color.Green;
                    lblMsg4.Text = "You Have voted Sucessfully";
                }
            }
        }
        else
        {
            lblMsg4.Visible = true;
            lblMsg4.ForeColor = Color.Red;
            lblMsg4.Text = "You are already Voted";

        }
    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        int yes = 0;
        int no = 0;
        int noIdea = 0;
        FileStream fs2 = new FileStream("C:\\temp\\Result.txt", FileMode.Open, FileAccess.Read);
        StreamReader sr2 = new StreamReader(fs2);

        sr2.BaseStream.Seek(0, SeekOrigin.Begin);
        string str = sr2.ReadLine();
        while (str != null)
        {

            if (str == "Yes")
            {
                yes = yes + 1;

            }
            if (str == "No")
            {
                no = no + 1;

            }
            if (str == "NoIdea")
            {
                noIdea = noIdea + 1;

            }
            str = sr2.ReadLine();

        }
        sr2.Close();
        fs2.Close();
        float a = (float)yes / (yes + no+noIdea) * 100;
        float b = (float)no / (yes + no + noIdea) * 100;
        float c = (float)noIdea / (yes + no + noIdea) * 100;
        int aresult = (int)a;
        int bresult = (int)b;
        int cresult =100 - (aresult+bresult);
        lblMsg1.Visible = true;
        lblMsg1.ForeColor = Color.Brown;
        lblMsg1.Text = "Yes :" + "   " + "  " + Convert.ToString(aresult) + " " + "%";
        lblMsg2.Visible = true;
        lblMsg2.ForeColor = Color.Brown;
        lblMsg2.Text = "No :" + "   " + "  " + Convert.ToString(bresult) + " " + "%";
        lblMsg3.Visible = true;
        lblMsg3.ForeColor = Color.Brown;
        lblMsg3.Text = "No Comment :" + "   " + "  " + Convert.ToString(cresult) + " " + "%";

    }

}

If  you will  do vote again then ..

View Result

Import Excel and Map Excel Column with SQL Table Column Using ASP .Net

Introduction

Here I will explain how to Import Excel in ASP.NET with C# and allow user to map Excel column with SQL table column before save excel data.

Database

I have made use of following table schema



Sql Connection String


 <connectionStrings>
    
    <add name="CommectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|ExcelDatabase.mdf;Integrated Security=True;"   providerName="System.Data.SqlClient" />
  </connectionStrings>


Model

public class ImportModel
{
public string SqlColName { get; set; }
public List<string> ListExcelCols{ get; set; }
}

Home.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Import.aspx.cs" Inherits="ExcelImporting.Import" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload runat="server" ID="filecontrol" />
            <asp:Button runat="server" ID="btnUpload" OnClick="btnUpload_Click" Text="Upload" />
            <hr />
            <table border="1">
                <thead>
                    <tr>
                        <td>Parent Column</td>
                        <td width="10px"></td>
                        <td>Excel Column</td>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <td colspan="3"></td>
                    </tr>
                </tfoot>
                <tbody>
                    <asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Repeater1_ItemDataBound1">
                        <ItemTemplate>
                        <tr>
                            <td><asp:Label runat="server" ID="lblSqlColName" Text='<%#Eval("SqlColName") %>'></asp:Label></td>
                            <td></td>
                            <td>
                                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                            </td>
                        </tr>
                    </ItemTemplate>
                    </asp:Repeater>
                    <tr>
                        <td></td>
                        <td></td>
                        <td>
                            <asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"/>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </form>
</body>
</html>


Home.aspx.cs

using ExcelImporting.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace ExcelImporting
{
    public partial class Import : System.Web.UI.Page
    {

        OleDbDataAdapter oleda;
        OleDbCommand cmd;
       static DataSet dsExcel;
        DataSet ds;
        OleDbConnection excelConnection;
        SqlDataAdapter sqlda;
        SqlCommand sqlcmd;
        SqlConnection sqlconnection;

        String _StrConnection = ConfigurationManager.ConnectionStrings["CommectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            // Excel import
            oleda = new OleDbDataAdapter();
            dsExcel = new DataSet();
            cmd = new OleDbCommand();
            string tmp = DateTime.Now.ToString("MMM-ddd-d-HH-mm-ss-yyyy") + "_" + filecontrol.PostedFile.FileName;
            string path = System.IO.Path.GetFullPath(Server.MapPath(Convert.ToString("~/ExcelFiles/") + tmp));
            filecontrol.SaveAs(Server.MapPath(Convert.ToString("~/ExcelFiles/") + tmp));
            string excelConnectionString = (Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=") + path) + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
            excelConnection = new OleDbConnection(excelConnectionString);
            cmd.CommandText = "Select * from [Sheet1$]";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = excelConnection;
            excelConnection.Open();

            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill(dsExcel, "dataExcel");

            List<string> list = new List<string>();
            ExcelDataset = dsExcel;
            list = BindExcelCols(dsExcel.Tables["dataExcel"]);
            //Sql Table column fetch
            if (list.Count > 0)
            {
                getSqlTableColumns(list);
            }
        }
        private void getSqlTableColumns(List<string> excelCols)
        {
            
            ds = new DataSet();
            sqlcmd = new SqlCommand();
            sqlconnection = new SqlConnection(_StrConnection);
            sqlcmd.CommandText = "Select * from TableToImportExcel";
            sqlcmd.CommandType = CommandType.Text;
            sqlcmd.Connection = sqlconnection;
            sqlconnection.Open();
            sqlda = new SqlDataAdapter(sqlcmd);
            sqlda.Fill(ds, "TableToImportExcel");

            var Importlist = BindSqlCols(ds.Tables["TableToImportExcel"], excelCols);

            Repeater1.DataSource = Importlist;
            Repeater1.DataBind();
        }


        private List<string> BindExcelCols(DataTable table)
        {
            List<string> list = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                list.Add(column.ColumnName);
            }
            return list;
        }
        private List<ImportModel> BindSqlCols(DataTable table, List<string> excelCols)
        {
            List<ImportModel> list = new List<ImportModel>();
            foreach (DataColumn column in table.Columns)
            {
                list.Add(new Models.ImportModel { ListExcelCols = excelCols, SqlColName = column.ColumnName });
            }
            return list;
        }

        protected void Repeater1_ItemDataBound1(object sender, RepeaterItemEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==ListItemType.AlternatingItem)
            {
                var Value = (ImportModel)e.Item.DataItem;
                DropDownList List = new DropDownList();
                List = (DropDownList)e.Item.FindControl("DropDownList1");
                List.DataSource = Value.ListExcelCols;
                List.DataBind();
            }
        }
        public static DataSet ExcelDataset {
            get { return dsExcel; }
            set { dsExcel= value ; }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SqlBulkCopy sqlBulk = new SqlBulkCopy(_StrConnection);
            sqlBulk.BatchSize = 150;
            sqlBulk.BulkCopyTimeout = 600;

            //Give your Destination table name
            sqlBulk.DestinationTableName = "dbo.TableToImportExcel";
            sqlBulk.ColumnMappings.Clear();
            foreach (RepeaterItem item in Repeater1.Items)//lblSqlColName
            {
                string key = ((Label)item.FindControl("lblSqlColName")).Text;
                string value = ((DropDownList)item.FindControl("DropDownList1")).SelectedItem.Text;
                sqlBulk.ColumnMappings.Add(value, key);
            }
            dsExcel = ExcelDataset;
            sqlBulk.WriteToServer(dsExcel.Tables[0]);
        }
    }
}