Total Pageviews
Thursday, 30 August 2018
Saturday, 27 February 2016
Datalist and bootstrap modal in asp.net
Pre requests - Use bootstrap CDN links
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
Objective- Add comment from bootstrap modal pop up
Write html outside datalist code
where datalist id- post_datalist
Bootstrap Modal code (we are using a asp hidden field control in modal)
------------------------------
<div class="modal fade" id="add_comment" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="H2">Comment</h4>
</div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div class="modal-body" style="height: 150px;">
<div class="form-group">
<div class="col-xs-12">
<asp:TextBox ID="comment_txt" runat="server" TextMode="MultiLine" Style="width: 100%; min-height: 90px;"></asp:TextBox>
<asp:HiddenField ID="post_id" runat="server" />
</div>
</div>
</div>
<div class="modal-footer">
<asp:Label ID="Label2" Visible="false" runat="server"></asp:Label>
<asp:Button ID="post_comment" runat="server" Text="Post comment" CssClass="btn btn-info" OnClick="post_comment_Click" />
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="post_datalist" EventName="ItemCommand" />
<asp:AsyncPostBackTrigger ControlID="post_comment" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
Now in code behind inside post_datalist_ItemCommand --
//add_comment
if ((e.CommandName == "comment") && (e.CommandArgument != null))
{
int id = Convert.ToInt32(e.CommandArgument);
string code = Convert.ToString(id);
post_id.Value = code;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("$('#add_comment').modal('show');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "CommentModalScript", sb.ToString(), false);
}
Now when the modal opens you can write the comment and click button- here is the button click function
protected void post_comment_Click(object sender, EventArgs e)
{
string postid = post_id.Value;
Int32 post_id_value = Convert.ToInt32(postid);
comment_save(post_id_value); // here you can call function to save the data
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type='text/javascript'>");
sb.Append("$('#add_comment').modal('hide');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "CommentModalScript", sb.ToString(), false);
BindParentDataList();// bind data /refresh
}
Friends pending request,confirm request & friends list table in MSSQL
Create Two tables
User(id, Username)
Friends(friend_one ,friend_two,status)
Here status 0, 1 and 2 values references to Pending Friend Request, Confirm Friend Request and You.
Add friend
INSERT INTO friends
(friend_one,friend_two)
VALUES
(@user_id,@friend_id);
(friend_one,friend_two)
VALUES
(@user_id,@friend_id);
Confirm friend
UPDATE friends
SET status="1"
WHERE
(friend_one=@user_id OR friend_two=@user_id)
AND
(friend_one=@friend_id OR friend_two=@friend_id);
SET status="1"
WHERE
(friend_one=@user_id OR friend_two=@user_id)
AND
(friend_one=@friend_id OR friend_two=@friend_id);
Checking friend
SELECT 'friend_one','friend_two','status' FROM friends
WHERE
(friend_one=@user_id OR friend_two=@user_id)
AND
(friend_one=@user_id OR friend_two=@user_id)
WHERE
(friend_one=@user_id OR friend_two=@user_id)
AND
(friend_one=@user_id OR friend_two=@user_id)
List friends
LEFT JOIN Friends F
ON U.id = F.friend_two
WHERE F.friend_one = 1 and status=1
UNION
SELECT * FROM user U
LEFT JOIN friends F
ON U.id = F.friend_one
WHERE F.friend_two = 1 and status=1
Monday, 25 January 2016
Bootstrap confirm dialog in asp.net server control
Objective : We use here a html control and server control to activate a confirmation dialog(Bootstrap modal)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('a[data-confirm]').click(function (ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal fade" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header" style="background: orange; color: white;"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body" style="background: white;"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmOK').attr('href', href);
$('#dataConfirmModal').modal({ show: true });
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<a href="delete.cfm" data-confirm="Are you sure you want to delete?">Delete</a>
<asp:LinkButton ID="LinkButton1" runat="server" data-confirm="Are you sure you want to delete?" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('a[data-confirm]').click(function (ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal fade" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header" style="background: orange; color: white;"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body" style="background: white;"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmOK').attr('href', href);
$('#dataConfirmModal').modal({ show: true });
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<a href="delete.cfm" data-confirm="Are you sure you want to delete?">Delete</a>
<asp:LinkButton ID="LinkButton1" runat="server" data-confirm="Are you sure you want to delete?" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
Code Behind
-----------------
protected void LinkButton1_Click(object sender, EventArgs e)
{
Response.Write("ok");
}
Friday, 22 January 2016
Submit form data without files in dropzone on button click
Objective:
------------
Form data and image file submitted at button click or Form data is submitted without image file on button click.
Dropzone:
-------------
https://rawgit.com/enyo/dropzone/master/dist/dropzone.js
Prerequisites:
---------------
Dropzone Js file corrections(Check out my post below for corrections )
http://aspdotnetcake.blogspot.in/2016/01/dropzone-js-corrections.html
Scripts:
--------------
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="http://localhost:1202/code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="Jquery/bootstrap.min.js"></script>
<link href="Jquery/bootstrap.min.css" rel="stylesheet" />
<script src="js/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css" />
Script code:
------------------
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
autoDiscover: false,
addRemoveLinks: true,
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 20,
url: "db_save.ashx",
addRemoveLinks: true,
maxFiles: 5,
maxFilesize: 5,
dictDefaultMessage: "Drag or click to add photos",
// The setting up of the dropzone
init: function () {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function (e, formData) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
else
{
alert("hi"); //Testing it with alert
myDropzone.uploadFiles([]);
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function (file, xhr, formData) {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
formData.append('title', $("input[name=title]").val());
formData.append('desc', $("textarea[name=description]").val());
});
this.on("successmultiple", function (files, response) {
alert(response);
});
this.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
HTMLin aspx
-------------------
<form id="my-awesome-dropzone" class="dropzone">
<div>
<input type="text" name="title" placeholder="Title" />
<textarea name="description" aria-valuetext="" style="cursor: pointer; width: 100%;" placeholder="Description" ></textarea></br>
<button id="submit-all" type="submit" class="button3" style="cursor: pointer">Post</button>
</div>
<div>
<div class="dropzone-previews" style="border: 1px dashed blue;"></div>
</div>
<%--<input id="username" type="text" name="username" value="akash" style="display: none;" />--%>
<input id="username" type="text" name="username" value="<% =ServerValue %>" style="display: none;" />
</form>
db_save.ashx
------------------------
string constring = ConfigurationManager.ConnectionStrings["xxxxx_mdf"].ConnectionString;
//HttpFileCollection files = context.Request.Files;
string user = string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xxxx= string.Empty;
string xxx= string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xx= string.Empty;
string xxxx= string.Empty;
int photos_count = 0;
user = context.Request["username"];
post_desc = context.Request["desc"];
string title = context.Request["title"];
string dirFullPath = HttpContext.Current.Server.MapPath("~/pictures/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
string id = string.Empty;
id = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
context.Response.Write(status);
if (!string.IsNullOrEmpty(fileName))
{
context.Response.Write(status);
fileExtension = Path.GetExtension(fileName);
Guid g = Guid.NewGuid();
str_image = g + numFiles.ToString() + fileExtension;
string image_path = HttpContext.Current.Server.MapPath("~/pictures/") + str_image;
file.SaveAs(image_path);
Stream streamfile = file.InputStream;
//context.Response.Write(pathToSave_100);
//Start of post data
post_title = context.Request["title"];
post_title = post_title.Substring(0, post_title.IndexOf(','));
event_photo_path = "pictures/" + str_image;
event_photoname = file.FileName;
event_photoid = "xxx" + DateTime.Now.ToString();
event_photo_ext = fileExtension;
photo_hide_code = "0";
photo_username = "";
event_timestamp = DateTime.Now.ToString();
int event_like_count = 0;
photos_count = photos_count + 1;
//DB for photos
if (event_photoname != "")
{
try
{
{
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("insert into db_save values (@xxxx,@xxxxx,@xxxx,@xxxx)", con))
{
cmd.Parameters.AddWithValue("@xxx", );
cmd.Parameters.AddWithValue("@xxx", );
cmd.Parameters.AddWithValue("@xxx", );
cmd.Parameters.AddWithValue("@xxx", );
con.Open();
cmd.ExecuteNonQuery();
con.Close();
status = "ok";
context.Response.Write(status);
return;
}
}
}
}
catch (Exception ex)
{
context.Response.Write(ex);
}
finally
{
}//try catch complete
}//if event_photoname-->complete
}//if filename exists -->complete
}//For each complete
// If no image write code here below
Dropzone Js corrections
Please correct the Dropzone js file
Updated by below redline
------------------------------------------
for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) {
// formData.append(this._getParamName(i), files[i], files[i].name);
if (typeof files[i] != "undefined") {
formData.append(this._getParamName(i), files[i], files[i].name);
} else {
formData.append(this._getParamName(i), files[i], "");
}
}
and this redline
-------------------------------
xhr.onload = (function(_this) {
return function(e) {
var _ref;
if (files[0] && files[0].status === Dropzone.CANCELED) {
return;
}
if (xhr.readyState !== 4) {
return;
}
Updated by below redline
------------------------------------------
for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) {
// formData.append(this._getParamName(i), files[i], files[i].name);
if (typeof files[i] != "undefined") {
formData.append(this._getParamName(i), files[i], files[i].name);
} else {
formData.append(this._getParamName(i), files[i], "");
}
}
and this redline
-------------------------------
xhr.onload = (function(_this) {
return function(e) {
var _ref;
if (files[0] && files[0].status === Dropzone.CANCELED) {
return;
}
if (xhr.readyState !== 4) {
return;
}
Tuesday, 6 October 2015
Dropzone with multiple files in asp.net(upload)
Scripts
--------
<script>
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
autoDiscover: false,
addRemoveLinks: true,
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 20,
url: "fileupload.ashx",
addRemoveLinks: true,
maxFiles: 5,
maxFilesize: 5,
dictDefaultMessage: "Drag or click to add photos",
// The setting up of the dropzone
init: function () {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function (file, xhr, formData) {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
formData.append('title', $("input[name=title]").val());
});
this.on("successmultiple", function (files, response) {
alert(response);
});
this.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
fileupload.aspx
------------------
--------
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="http://localhost:1202/code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="Jquery/bootstrap.min.js"></script>
<link href="Jquery/bootstrap.min.css" rel="stylesheet" />
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css" />
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
autoDiscover: false,
addRemoveLinks: true,
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 20,
url: "fileupload.ashx",
addRemoveLinks: true,
maxFiles: 5,
maxFilesize: 5,
dictDefaultMessage: "Drag or click to add photos",
// The setting up of the dropzone
init: function () {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function (file, xhr, formData) {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
formData.append('title', $("input[name=title]").val());
});
this.on("successmultiple", function (files, response) {
alert(response);
});
this.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
fileupload.aspx
------------------
<form id="my-awesome-dropzone" class="dropzone">
<div>
<input type="text" name="title" placeholder="Title" />
<button id="submit-all" type="submit" class="button3" style="cursor: pointer">Post</button>
</div>
<div>
<div class="dropzone-previews" style="border: 1px dashed blue;"></div>
</div>
</form>
fileupload.ashx
---------------------
<%@ WebHandler Language="C#" Class="fileupload" %>
using System;
using System.Web;
using System.IO;
public class agoodthing : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
string title = context.Request["title"];
string photo_name = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
HttpPostedFile file = files[i];
//string fileExtension = file.ContentType;
string photo_box_id = photo_name ;
string fname = context.Server.MapPath("~/dump/" +photo_box_id+ file.FileName);
file.SaveAs(fname);
//context.Response.Write( title );
}
}
public bool IsReusable {
get {
return false;
}
}
}
Monday, 5 October 2015
How to use dropzone and cropper in asp.net
Include scripts (inside head tag and get bootstrap links from getbootstrap.com)
--------------------
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="http://localhost:1202/code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="Jquery/bootstrap.min.js"></script>
<link href="Jquery/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.rawgit.com/fengyuanchen/cropper/v0.11.1/dist/cropper.min.css" rel="stylesheet">
<script src="https://cdn.rawgit.com/fengyuanchen/cropper/v0.11.1/dist/cropper.min.js"></script>
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css" />
//Script for dropzone
-------------------------
<script>$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
$("#dZUpload").dropzone({
url: "profile_pic.ashx",
addRemoveLinks: true,
maxFiles: 1,
maxFilesize: 5,
//previewsContainer: "#previews",
dictDefaultMessage: "Drag or click to add profile image",
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log('Successfully uploaded :' + imgName);
var imgName = response;
d = new Date();
$("#imgcrop").attr("src", "");
$(".photo_to_crop1").attr("src", "dump_images/" + imgName + "?" + d.getTime());
$("#img_name").attr("value", imgName);
intialize();
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
sending: function (file, xhr, formData) {
formData.append('name', $("input[name=name]").val());
},
complete: function (response) {
}
});
});
</script>
//Script for cropper
-----------------------
<script>
function intialize() {
var imageURL = $(".photo_to_crop1").attr("src");
var imageBox = $('.photo_to_crop');
var options = {
aspectRatio: 1,
movable: true,
zoomable: true,
responsive: true,
center: true,
scalable: true,
crop: getcroparea
};
if (imageURL != null) {
console.log("It's not empty, building dedault box!");
var DefaultCropBoxOptionObj = {
height: 25,
width: 25
};
console.log(DefaultCropBoxOptionObj);
imageBox.cropper(options);
imageBox.cropper('setData', DefaultCropBoxOptionObj);
imageBox.cropper('replace', imageURL);
}
}
function getcroparea(c) {
$('#hdnx').val(parseInt(c.x));
$('#hdny').val(parseInt(c.y));
$('#hdnw').val(parseInt(c.width));
$('#hdnh').val(parseInt(c.height));
$('#hdnr').val(parseInt(c.rotate));
$('#hdnsx').val(parseInt(c.scaleX));
$('#hdnsy').val(parseInt(c.scaleY));
};
</script>
cropper.aspx
-------------------
<form id="form1" runat="server">
<div id="dZUpload" class="dropzone">
<div class="dz-default dz-message">
<p style="font-family: 'Open Sans'">Drop a photo here or click to add profile photo</p>
</div>
</div>
<div>
<input id="username" type="text" name="name" value="<% =ServerValue %>" style="display: none;" />
<img id="img1" alt="sample image" src="" class="photo_to_crop1" style="display: none;" />
<div style="padding-bottom: 5px; padding-top: 5px; width: 300px">
<img id="imgcropped" runat="server" visible="false" class="img-responsive" />
<h5>
<asp:Label ID="my_ad_err_lbl" runat="server" Text=""></asp:Label></h5>
</div>
<div class="container cropcontainer">
<img id="imgcrop" alt="sample image" src="" class="photo_to_crop" />
<input type="text" style="display: none" id="img_name" name="img_name" value="user.png" />
</div>
<input type="hidden" id="hdnx" runat="server" />
<input type="hidden" id="hdny" runat="server" />
<input type="hidden" id="hdnw" runat="server" />
<input type="hidden" id="hdnh" runat="server" />
<input type="hidden" id="hdnr" runat="server" />
<input type="hidden" id="hdnsx" runat="server" />
<input type="hidden" id="hdnsy" runat="server" />
<asp:Button ID="btncrop" runat="server" OnClick="btncrop_Click" Text="Crop and Save" CssClass="button3" OnClientClick="reload()" />
<asp:Button ID="save_original" runat="server" OnClick="btnsave_original_Click" Text="Save original" CssClass="button3" OnClientClick="reload()" Style="display: none;" />
<asp:Button ID="pic_delete" runat="server" OnClick="btndelete_Click" Text="Delete Photo" OnClientClick="deletepic()" CssClass="button3" />
</div>
</form>
Code behind
----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Image = System.Drawing.Image;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
public partial class cropper : System.Web.UI.Page
{
string con = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
public string ServerValue = String.Empty;
public string photo_loc = String.Empty;
public string db_photo_name = String.Empty;
public string db_photo_loc = String.Empty;
public string db_photo_ext = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["userdata"] != null)
{
HttpCookie login = Request.Cookies["userdata"];
string user = login["username"];
ServerValue = user;
//load_profile_pic();
}
}
protected void btncrop_Click(object sender, EventArgs e)
{
try
{
//string photo_path = imgcrop.Src;
string photo_name = Request.Form["img_name"];
string fname = photo_name;
string fpath = Path.Combine(Server.MapPath("~/dump_images"), fname);
Image oimg = Image.FromFile(fpath);
Rectangle cropcords = new Rectangle(
Convert.ToInt32(hdnx.Value),
Convert.ToInt32(hdny.Value),
Convert.ToInt32(hdnw.Value),
Convert.ToInt32(hdnh.Value)
);
string cfname, cfpath;
Bitmap bitMap = new Bitmap(cropcords.Width, cropcords.Height, oimg.PixelFormat);
Graphics grph = Graphics.FromImage(bitMap);
grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel);
cfname = "crop_" + fname;
cfpath = Path.Combine(Server.MapPath("~/profile_images"), cfname);
bitMap.Save(cfpath);
imgcropped.Visible = true;
imgcropped.Src = "~/profile_images/" + cfname;
db_photo_loc = "profile_images/" + cfname;
db_photo_name = cfname;
string id = db_photo_name;
//UPDATE THE IMAGE IN DB
try
{
SqlConnection conn = new SqlConnection(con);
SqlCommand sqlcomm = new SqlCommand(" write your query for update", conn);
conn.Open();
sqlcomm.ExecuteNonQuery();
conn.Close();
my_ad_err_lbl.Text = "Profile photo cropped and saved.";
if (my_ad_err_lbl.Text == "Done")
{
}
}
catch (Exception ex)
{
my_ad_err_lbl.Text = ex.Message;
}
finally
{
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void btndelete_Click(object sender, EventArgs e)
{
delete_photo();
}
public void delete_photo()
{
//DELETE THE IMAGE BEFORE UPDATE
try
{
SqlConnection conn = new SqlConnection(con);
conn.Open();
SqlCommand cmd = new SqlCommand(" write your query to delete '", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string imageurl = dr["profile_img_loc"].ToString();
string imageFilePath = HttpContext.Current.Server.MapPath("~/" + imageurl);
System.IO.File.Delete(imageFilePath);
}
}
catch (Exception ex)
{
my_ad_err_lbl.Text = ex.Message;
}
finally
{
}
}
protected void btnsave_original_Click(object sender, EventArgs e)
{
string id = db_photo_name;
//UPDATE THE IMAGE IN DB
try
{
}
catch (Exception ex)
{
}
finally
{
}
}
}
profile_pic.ashx
---------------------
<%@ WebHandler Language="C#" Class="profile_pic" %>
using System;
using System.Web;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public class profile_pic : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string con = ConfigurationManager.ConnectionStrings["prayermeeting_mdf"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(con);
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("~/profile_images/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
if (fileExtension == ".jpeg" || fileExtension == ".JPEG" || fileExtension == ".png" || fileExtension == ".PNG" || fileExtension == ".jpg" || fileExtension == ".JPG")
{
string user = context.Request["name"];
//context.Response.Write("your username: " + user + fileExtension);
string profile_pic_id = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
str_image = profile_pic_id + user + fileExtension;
string id=profile_pic_id + user;
string pathToSave = HttpContext.Current.Server.MapPath("~/dump_images/") + str_image;
//context.Response.Write(str_image);
string loc = "dump_images/" + str_image;
//DELETE THE IMAGE BEFORE UPDATE
//SAVE THE IMAGE
file.SaveAs(pathToSave);
// UPDATE THE IMAGE IN DB
}
}
}
context.Response.Write(str_image);
}
public bool IsReusable {
get {
return false;
}
}
Saturday, 26 September 2015
Autocomplete for a input text box with update panel
SCRIPT
----------
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<script>
$(document).keypress(function (event) {
if (event.keyCode == 13) {
$("#<%= pm_search_btn.ClientID%>").click();
}
});
</script>
$(document).keypress(function (event) {
if (event.keyCode == 13) {
$("#<%= pm_search_btn.ClientID%>").click();
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
SearchText_m();
});
//On UpdatePanel Refresh.
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
SearchText_m();
}
});
};
function SearchText_m() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "meetings.aspx/GetAutoCompleteData",
data: "{'search_txt':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
HTML (meetings.aspx)
--------
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<input type="text" id="txtSearch" placeholder="Search..." class="autosuggest" name="pm_search_txt" />
<span style="display:none">
<asp:Button ID="pm_search_btn" runat="server" Text="Button" OnClick="pm_search_btn_Click" />
</span>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
---------------
using System.Web.Services;
public static List<string> GetAutoCompleteData(string search_txt)
{
List<string> result = new List<string>();
string conn = ConfigurationManager.ConnectionStrings["meeting_mdf"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand(" select top 10 ministry from (select DISTINCT ministry from customer_ad ) as tb1 where ministry LIKE '%'+@SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", search_txt);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["ministry "].ToString());
}
return result;
}
}
}
Now you can get data
protected void pm_search_btn_Click(object sender, EventArgs e)
{
}
Subscribe to:
Posts (Atom)






