Uploading and cropping an Image using MVC and Jquery

To upload a file using jquery We require Jquery.bpopup.min.js and jquery.jcorp.min.js.

Home Controller.CS

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLogicLayer;
using ModelClasses;

namespace KnockOutJS.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[“DefaultConnection”].ToString();
public ActionResult Department()
{
return View();
}
public ActionResult DepartmentList()
{
BL_Department objBD = new BL_Department();
MC_Department objMCD = new MC_Department();
objMCD.DepartmentID = 0;
List<MC_Department> lstDepartment = objBD.ShowRole(connectionString);
return Json(lstDepartment, JsonRequestBehavior.AllowGet);
}
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult UploadFile()
{
var path = “”;
var returnPath = “”;
for (int i = 0; i < Request.Files.Count; i++)
{

var file = Request.Files[i];
var fileName = DateTime.Now.Ticks + “_” + Path.GetFileName(file.FileName);
path = Path.Combine(Server.MapPath(“~/Junk/OriginalImages/”), fileName);
file.SaveAs(path);
}
returnPath=CreateThumbnail(300, 400, path);
return Json(returnPath, JsonRequestBehavior.AllowGet);
}
public string CreateThumbnail(int maxWidth, int maxHeight, string path)
{

var image = System.Drawing.Image.FromFile(path);
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics thumbGraph = Graphics.FromImage(newImage);

thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
//thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight);
image.Dispose();
string fileRelativePath = “../Junk/ResizedImage/” + maxWidth + Path.GetFileName(path);
newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
return fileRelativePath;
}
[HttpGet]
public ActionResult CropImage(string path, string x, string y, string w, string h)
{
try
{

byte[] CropImage = Crop(Server.MapPath(path), Convert.ToInt32(w), Convert.ToInt32(h), Convert.ToInt32(x), Convert.ToInt32(y));
using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
{
ms.Write(CropImage, 0, CropImage.Length);
using (Image CroppedImage = Image.FromStream(ms, true))
{
path = path.Replace(“ResizedImage”, “CroppedImages”);
CroppedImage.Save(Server.MapPath(path), CroppedImage.RawFormat);
}
}
}
catch (Exception e)
{
string error = e.Message;
}
return Json(path, JsonRequestBehavior.AllowGet);
}

static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (Image OriginalImage = Image.FromFile(Img))
{
using (Bitmap bmp = new Bitmap(Width, Height))
{
bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
using (Graphics Graphic = Graphics.FromImage(bmp))
{
Graphic.SmoothingMode = SmoothingMode.AntiAlias;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height, GraphicsUnit.Pixel);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, OriginalImage.RawFormat);
return ms.GetBuffer();
}
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
}
}


@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Upload Example</title>
<link href=”~/Content/jcrop_main.css” rel=”stylesheet” />
<link href=”~/Content/jquery.Jcrop.css” rel=”stylesheet” />
</head>
<body style=”background-color: black;”>
<div id=”dvPopup” style=”background-color: white; height: 400px; width: 500px; left: 20%; top: 20%;”>
<div style=”margin-left: 50px; margin-top: 50px;”>
<input type=”file” id=”FileUpload” />
<input type=”hidden” id=”hdnfServerPath” value=”~/Junk/ResizedImage/” />
<br />
<img src=”~/Content/Images/378.GIF” id=”loader” style=”display: none;” />

<div id=”ImageCropperDiv”>
<div>
<img id=”imageEditor” src=”” style=”max-height: 400px; max-width: 300px;” />
</div>
<input type=”button” id=”btnCrop” value=”Crop” onclick=”CropImage();” />
<input type=”hidden” runat=”server” id=”X” />
<input type=”hidden” runat=”server” id=”Y” />
<input type=”hidden” runat=”server” id=”W” />
<input type=”hidden” runat=”server” id=”H” />
</div>
<img src=”” id=”croppedImage” style=”display: none;” />
</div>
</div>
<script src=”~/Scripts/jquery-1.7.1.intellisense.js”></script>
<script src=”~/Scripts/jquery-1.7.1.js”></script>
<script src=”~/Scripts/jquery-1.7.1.min.js”></script>
<script src=”~/Scripts/jquery.bpopup.min.js”></script>
<script src=”~/Scripts/jquery.Jcrop.min.js”></script>
<script>
$(document).ready(function () {
$(“#dvPopup”).bPopup();
$(“#FileUpload”).change(function (event) {
$(“#loader”).slideToggle();
$(“#croppedImage”).css(“display”, “none”);
$(“#ImageCropperDiv”).css(“display”, “block”);
var fileName = $(“#hdnfServerPath”).val();
var formData = new FormData();
var totalFiles = document.getElementById(“FileUpload”).files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById(“FileUpload”).files[i];
file.name = file.name + $.now();
fileName = fileName + file.name;
formData.append(“FileUpload”, file);
}
$.ajax({
type: “POST”,
url: ‘/Home/UploadFile’,
data: formData,
dataType: ‘json’,
contentType: false,
processData: false,
success: function (data) {
$(“#loader”).slideToggle();
$(“#imageEditor”).attr(“src”, data);
jQuery(“#imageEditor”).Jcrop({
onSelect: storeCoords
});
},
error: function (error) {
alert(“errror”);
$(“#loader”).slideToggle();
}
});
});
});
function storeCoords(c) {
$(‘#X’).val(c.x);
$(‘#Y’).val(c.y);
$(‘#W’).val(c.w);
$(‘#H’).val(c.h);
};
function CropImage() {
try {
var px = $(‘#X’).val();
var py = $(‘#Y’).val();
var pw = $(‘#W’).val();
var ph = $(‘#H’).val();
var pFileName = $(“#imageEditor”).attr(“src”);
$.ajax({
type: “GET”,
url: “/Home/CropImage”,
data: {
x: px,
y: py,
w: pw,
h: ph,
path: pFileName
},
dataType: ‘json’,
contentType: false,
success: function (data) {
$(“#croppedImage”).removeAttr(“src”);
$(“#croppedImage”).attr(“src”, data);
$(“#croppedImage”).css(“display”, “block”);
$(“#ImageCropperDiv”).css(“display”, “none”);
},
error: function (msg) {
alert(msg);
}
});

} catch (e) {
alert(e);
}
}
</script>
</body>
</html>


Jquery.Jcorp.css

/* Fixes issue here http://code.google.com/p/jcrop/issues/detail?id=1 */
.jcrop-holder { text-align: left; }

.jcrop-vline, .jcrop-hline
{
font-size: 0;
position: absolute;
background: white url(‘Jcrop.gif’) top left repeat;
}
.jcrop-vline { height: 100%; width: 1px !important; }
.jcrop-hline { width: 100%; height: 1px !important; }
.jcrop-handle {
font-size: 1px;
width: 7px !important;
height: 7px !important;
border: 1px #eee solid;
background-color: #333;
*width: 9px;
*height: 9px;
}

.jcrop-tracker { width: 100%; height: 100%; }

.custom .jcrop-vline,
.custom .jcrop-hline
{
background: yellow;
}
.custom .jcrop-handle
{
border-color: black;
background-color: #C7BB00;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}


Jcorp.main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.jcrop_example{background:#FFF;width:865px;font-size:80%;border:1px #000 solid;margin:3.5em 10% 2em;padding:1em 2em 2em}
.jcrop_example p{font-size:90%}
.accordion h3{margin:0}
.accordion form{border:1px solid;background:#E6E6E6;border-color:#C3C3C3 #8B8B8B #8B8B8B #C3C3C3;margin:.5em 0;padding:.5em}
.accordion form label{margin-right:1em;font-weight:700;color:#900;font-size:10px}

.jcrop_custom .jcrop-vline,.jcrop_custom .jcrop-hline{background:#FF0}
.jcrop_custom .jcrop-handle{background-color:#FF4B4B;-moz-border-radius:5px;-webkit-border-radius:5px;border-color:#FFF}

Amit Shishodia
amit.shishodia.007@gmail.com
shishodia.011@gmail.com
Contact No:9910164912

jqueryCorp



Jquery -Ajax File Upload in MVC

Upload.CSHTML

<html>
<head>
<title>Upload Example</title>
<script src=”~/Scripts/jquery-1.7.1.intellisense.js”></script>
<script src=”~/Scripts/jquery-1.7.1.js”></script>
<script src=”~/Scripts/jquery-1.7.1.min.js”></script>
<script src=”~/Scripts/jquery.bpopup.min.js”></script>
<script>
$(document).ready(function () {
$(“#dvPopup”).bPopup();

$(“#FileUpload”).change(function () {

var formData = new FormData();
var totalFiles = document.getElementById(“FileUpload”).files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById(“FileUpload”).files[i];

formData.append(“FileUpload”, file);
}
$.ajax({
type: “POST”,
url: ‘/Home/UploadFile’,
data: formData,
dataType: ‘json’,
contentType: false,
processData: false,
success: function (response) {
alert(‘succes!!’);

},
error: function (error) {
alert(“errror”);

}
});
});
});

</script>
</head>
<body style=”background-color: black;”>
<div id=”dvPopup” style=”background-color: white; height: 200px; width: 300px; left: 20%; top: 20%;”>
<div style=”margin-left:50px; margin-top:50px;”>
<input type=”file” id=”FileUpload” />

</div>
</div>
</body>
</html>


HomeController,CS

public ActionResult Upload()
{
return View();
}
[HttpPost]
public void UploadFile()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];

var fileName = Path.GetFileName(file.FileName);

var path = Path.Combine(Server.MapPath(“~/Junk/”), fileName);
file.SaveAs(path);
}

}


Multi Heirarchy Handling in mvc and database

public class MenuItem
{
public int MenuID
{
get;
set;
}
public int ParentMenu
{
get;
set;
}
public string Menu
{
get;
set;
}

}

public ActionResult getMenu()
{
DBConnect dbc = new DBConnect();
DataTable dt = dbc.GetData();
List<MenuItem> data = dt.AsEnumerable().Select(x => new MenuItem
{
MenuID = (Int32)(x[“MenuID”] ?? 0),
ParentMenu = (Int32)(x[“ParentMenu”] ?? “”),
Menu = (string)(x[“Menu”] ?? “”),

}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}

<body>
<div id=”mainDV”>
<ul id=”mainUL”></ul>
</div>
</body>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$.getJSON(“/Home/getMenu”, function (data) {

try{
for(var i=0;i<data.length;i++)
{
var elem = document.createElement(“li”);
elem.setAttribute(“id”, data[i].MenuID);
$(elem).text(data[i].Menu);
var mainulElem = document.createElement(“ul”);
mainulElem.setAttribute(“id”, “ul_” + data[i].MenuID);
$(elem).append(mainulElem);
if (data[i].ParentMenu == “0”) {
$(“#mainUL”).append(elem);
} else {
$(“#ul_” + data[i].ParentMenu).append(elem);
}
}

} catch (e) {
alert(e);
}
});
});
</script>

Drop All User Defined objects from databse

 

Using given below query you can easy create

/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
    SELECT @SQL = ‘DROP PROCEDURE [dbo].[‘ + RTRIM(@name) +’]’
    EXEC (@SQL)
    PRINT ‘Dropped Procedure: ‘ + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = ‘DROP VIEW [dbo].[‘ + RTRIM(@name) +’]’
    EXEC (@SQL)
    PRINT ‘Dropped View: ‘ + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = ‘DROP FUNCTION [dbo].[‘ + RTRIM(@name) +’]’
    EXEC (@SQL)
    PRINT ‘Dropped Function: ‘ + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = ‘ALTER TABLE [dbo].[‘ + RTRIM(@name) +’] DROP CONSTRAINT ‘ + RTRIM(@constraint)
        EXEC (@SQL)
        PRINT ‘Dropped FK Constraint: ‘ + @constraint + ‘ on ‘ + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = ‘ALTER TABLE [dbo].[‘ + RTRIM(@name) +’] DROP CONSTRAINT ‘ + RTRIM(@constraint)
        EXEC (@SQL)
        PRINT ‘Dropped PK Constraint: ‘ + @constraint + ‘ on ‘ + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = ‘DROP TABLE [dbo].[‘ + RTRIM(@name) +’]’
    EXEC (@SQL)
    PRINT ‘Dropped Table: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

Getting Table Names in Which contains a particular column(name)

For example I am looking for partyid column

DECLARE @SQL VARCHAR(MAX)

CREATETABLE #TMP

(Clmn VARCHAR(500),

   CNT INT)

SELECT @SQL=COALESCE(@SQL,”)+CAST(‘INSERT INTO #TMP Select ”’+ TABLE_SCHEMA +’.’+ TABLE_NAME +’.’+ COLUMN_NAME +”’ AS Clmn, count(*) CNT FROM ‘

+ TABLE_SCHEMA +’.[‘+ TABLE_NAME +

‘] WHERE [‘+ COLUMN_NAME +’] is not NULL ;’ASVARCHAR(MAX))

FROMINFORMATION_SCHEMA.COLUMNS

JOINsysobjects B

ONINFORMATION_SCHEMA.COLUMNS.TABLE_NAME = B.NAME

WHERE COLUMN_NAME =’PartyID’AND xtype =’U’

AND DATA_TYPE NOTIN(‘datetime’)

PRINT @SQL

EXEC(@SQL)

SELECT*FROM #TMP WHERE CNT > 0

DROPTABLE #TMP

Image

Assigning Rank to duplicate records as 1.1,1.2,1.3

This query is for identifying duplicate records uniquely,I am using row number and rank so that i can number duplicate records as 1.1,1.2,1.3,2.1,2.2,2.3.The query is as follows.

SETANSI_NULLSON

GO

SETQUOTED_IDENTIFIERON

GO

SETANSI_PADDINGON

GO

CREATETABLE [dbo].[#Table1](

     [id] [int] NULL,

     [Name] [varchar](50)NULL

)ON [PRIMARY]

GO

SETANSI_PADDINGOFF

GO

INSERT [dbo].[#Table1]([id], [Name])VALUES (1,N’Amit’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (2,N’Amit’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (3,N’Puja’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (4,N’Rahul’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (5,N’Puja’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (6,N’Ashish’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (7,N’Rahul’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (8,N’Amit’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (9,N’Ashish’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (10,N’Rahul’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (11,N’amit’)

INSERT [dbo].[#Table1]([id], [Name])VALUES (12,N’Puja’)

 

createtable #temp(name varchar(15),sno varchar(10))

insertinto #temp

SELECTdistinct name,ROW_NUMBER()OVER (ORDERBY name)AS sno FROM #Table1 groupby name orderby name

 

SELECT id,name,(select sno from #temp where #temp.name=#Table1.name)+’.’+cast(RANK()OVER (PARTITIONBY name ORDERBY id ASC)asvarchar(10))AS [rank]

FROM #Table1 orderby name  

 

droptable #temp 

droptable #Table1

Image