Advertisements

Archive

Archive for the ‘DotNet’ Category

How to implement BalloonPopupExtender in ASP.Net/C# OR Ballon Popup Extender Sample in ASP.Net/C#

September 25, 2012 1 comment

                     DOWNLOAD SOURCE CODE FOR BALLOON POPUP EXTENDER EXAMPLE

How to display good POPUP Window in ASP.Net using Ajax?

Most of the ASP.Net application requires showing some POPUP window to user for showing some messages or information. Also in order to create a ToolTips in ASP.Net/C# web application it’s very difficult to achieve for good looking ToolTip. In the newest Ajax Control Toolkit includes an awesome good looking and more functional popup extender called Balloon POPUP Extender. It’s a very light weight and having good look and feel popup, also we can apply custom styles for POPUP. Balloon POPUP Extender can use as ToolTips in ASP.Net application.

Download and Register New AjaxControl Toolkit

For implementing Balloon POPUP Extender in ASP.Net/C# application, we need to download newest Ajax Control Toolkit and register to the Project references. You can download new Ajax Control Toolkit from this link. Right click the ‘References’ under the ASP.Net project from Visual Studio and browse the dll and press OK.

In the ASPX page we need to register this ajax toolkit dll like below mentioned code.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

How to implement Balloon POPUP Extender in ASP.Net/C# Application?

After adding and register the Ajax Control Toolkit as mentioned above, we can start to implement the Balloon POPUP Extender. We can implement Balloon POPUP Extender while clicking/on mouse over/on focus of any server controls in ASP.Net. Below mentioned is the codes for implementing the same.

<ajax:BalloonPopupExtender ID="PopupControlExtender2" runat="server" 
TargetControlID="txtUserName"
 BalloonPopupControlID="pnlBalloon" Position="BottomRight" 
BalloonStyle="Cloud"
 BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="true"
 DisplayOnFocus="false" DisplayOnClick="true" />

Balloon Popup Extender Sample

Balloon Popup Extender Sample

Balloon Popup Extender Sample


There are some properties are available for Balloon POPUP Extender control and we can adjust the size,color,style and controls of POPUP using these properties. Below are the main properties of Balloon POPUP Extender

TargetControlID – The ID of the control to attach to.

BalloonPopupControlID – The ID of the control to display.

Position – Optional setting specifying where the popup should be positioned relative to the target control. (TopRight, TopLeft, BottomRight, BottomLeft, Auto) Default value is Auto.

OffsetX/OffsetY – The number of pixels to offset the Popup from its default position, as specified by Position. Default value is 0.

BalloonStyle – Optional setting specifying the theme of balloon popup. (Cloud, Rectangle, Custom). Default value is Rectangle.

BalloonSize – Optional setting specifying the size of balloon popup. (Small, Medium and Large). Default value is Small.

CustomCssUrl – This is required if user choose BalloonStyle to Custom. This specifies the url of custom css which will display custom theme.

CustomClassName – This is required if user choose BalloonStyle to Custom. This specifies the name of the css class for the custom theme.

UseShadow – Optional setting specifying whether to display shadow of balloon popup or not.

ScrollBars – Optional setting specifying whether to display scrollbar if contents are overflowing. This property contains 5 options – None, Horizontal, Vertical, Both and Auto. Default value is Auto.

DisplayOnMouseOver – Optional setting specifying whether to display balloon popup on the client onMouseOver event. Default value is false.

DisplayOnFocus – Optional setting specifying whether to display balloon popup on the client onFocus event. Default value is false.

DisplayOnClick – Optional setting specifying whether to display balloon popup on the client onClick event. Default value is true.

Animations – Generic animations for the PopupControlExtender.

                     OnShow – The OnShow animation will be played each time the popup is displayed. The popup will be positioned correctly               but hidden. The animation can use <HideAction Visible=”true” /> to display the popup along with any other visual effects.

                     OnHide – The OnHide animation will be played each time the popup is hidden.


A very simple example for Balloon POPUP Extender in ASP.Net/C# using Ajax

Here we are demonstrating a very simple for implementing Ajax Balloon POPUP Extender  with full downloadable source code.

ASPX Page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BaloonPopup._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
TagPrefix="ajax" %>
<asp:Content ID="HeaderContent" runat="server" 
ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" 
ContentPlaceHolderID="MainContent">
<h2>
Welcome to Baloon Popup Extender Sample
</h2>
<p>
For Website/WebApplication creation <a href="http://www.tuvian.com" 
title="aps.net">www.tuvian.com</a>.
</p>
<div>
<ajax:ToolkitScriptManager ID="Scriptmanager1" runat="server">
</ajax:ToolkitScriptManager>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Cloud Style Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="PopupControlExtender2" runat="server" 
TargetControlID="txtUserName"
BalloonPopupControlID="pnlBalloon" Position="BottomRight" BalloonStyle="Cloud"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" DisplayOnMouseOver="true"
DisplayOnFocus="false" DisplayOnClick="true" />
UserName :
<asp:TextBox runat="server" ID="txtUserName" />
<asp:Panel runat="server" ID="pnlBalloon">
This is the Cloud Style Ballon Popup</asp:Panel>
</div>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Rectangular Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="Balloonpopupextender1" runat="server" 
TargetControlID="lblShow"
BalloonPopupControlID="pnlRectangularBallon" Position="TopRight" 
BalloonStyle="Rectangle"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="false"
DisplayOnFocus="false" DisplayOnClick="true" />
<asp:Label runat="server" ID="lblShow" 
Text="Click Here to Show the Rectangular Balloon Popup" />
<asp:Panel runat="server" ID="pnlRectangularBallon">
This is the rectangular ballon popup</asp:Panel>
</div>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Custom Style Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="Balloonpopupextender2" runat="server" 
TargetControlID="txtCustomBallonPopup"
BalloonPopupControlID="pnlCustomBallon" Position="BottomRight" 
BalloonStyle="Custom"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="true"
CustomCssUrl="Styles/BalloonPopupOvalStyle.css" 
CustomClassName="oval" DisplayOnFocus="false"
DisplayOnClick="true" />
<asp:TextBox runat="server" ID="txtCustomBallonPopup" />
<asp:Panel runat="server" ID="pnlCustomBallon">
This is the Custom Style ballon popup</asp:Panel>
</div>
</div>
</asp:Content>
--------------

                  DOWNLOAD SOURCE CODE FOR BALLOON POPUP EXTENDER EXAMPLE
Advertisements

How to Create a Data Table Dynamically with sample data and Bind to Grid/Create datatable with sample data.

September 7, 2012 4 comments

How to create a datatable with sample data

We are going to demonstrate how to create a sample datatable dynamically in ASP.Net. Here we are creating a ASPx page with a grid view. In the page load of the ASPx page will call a bind method which creating a datatable dynamically and bind the datatable with datagrid. In BindGridviewData function create data for an employee and binding employee data to the employee grid.

ASPxPage

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicCreateDataTable.aspx.cs"
    Inherits="ExperimentLab.DynamicCreateDataTable" %> 
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gdEmployee" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
BindGridviewData();
}
//Creating datatable dynamically and bind data to a grid
protected void BindGridviewData()
{
DataTable dt = new DataTable();
//Create datatable Columns dynamically 
dt.Columns.Add("EmployeeID", typeof(Int32));
dt.Columns.Add("EmployeeName", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("City", typeof(string));
//Create data table row dynamically add
DataRow dtrow = dt.NewRow(); // Create New Row 
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 1; //Bind Data to Columns
dtrow["EmployeeName"] = "Ramraj";
dtrow["Department"] = "Admin";
dtrow["City"] = "Calicut";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 2; //Bind Data to Columns
dtrow["EmployeeName"] = "Malhothra";
dtrow["Department"] = "HR";
dtrow["City"] = "Mumbai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 3; //Bind Data to Columns
dtrow["EmployeeName"] = "Sinan Hafis";
dtrow["Department"] = "Admin";
dtrow["City"] = "Delhi";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 4; //Bind Data to Columns
dtrow["EmployeeName"] = "Wazim Jafar";
dtrow["Department"] = "Finance";
dtrow["City"] = "Goa";
dt.Rows.Add(dtrow);
gdEmployee.DataSource = dt;
gdEmployee.DataBind();
}

RESULT 

Dynamic datatable in ASP.Net

Dynamic datatable in ASP.Net

How to Create and use Table-Valued Parameter in C# and T-SQL/ How to pass table to stored procedures in SQL

July 17, 2012 Leave a comment

What is Table – Valued Parameter in SQL Server 2008?

Table-valued parameters provide an easy way to marshal multiple rows of data from a client application to SQL Server without requiring multiple round trips or special server-side logic for processing the data. You can use table-valued parameters to encapsulate rows of data in a client application and send the data to the server in a single parameterized command. The incoming data rows are stored in a table variable that can then be operated on by using Transact-SQL.

What we are going to do with Table – Valued Parameter?

We are going to demonstrate a very simple example for using Table – Valued parameter. In this sample project we will insert bulk amount of data into the table by passing a bulk data using datatable in C# to SQL stored procedure.

Create a Table for insert data using Table – Valued Parameter 

Here we are having a table named Officer and having three fields ID,Name and Salary. We are going to fill the table with bulk data.

CREATE TABLE Officer(
ID INT PRIMARY KEY IDENTITY(1,1),
NAME VARCHAR(50),
SALARY DECIMAL(18, 0))

Stored Procedure for insert data by accepting Table Valued Parameter

Now we are going to create a Stored Procedure that accepting a table type as parameter and insert values in this type into the table.

CREATE PROCEDURE InsertOfficerDetails
(
@OfficerData OfficerDetails readonly
)
AS 
INSERT INTO Officer (Name, Salary)
SELECT Name, Salary
FROM @OfficerData;

C# code to call Stored Procedure to insert data in to the table using Table – Valued Parameter

We are creating a simple ASPX page with a single button. When we click this button we are calling above stored procedure by creating and passing some amount of sample data to the stored procedure as Table – Valued Parameter.

ASPX Page 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CallSP.aspx.cs" 
Inherits="ExperimentLab.CallSP" %>
<!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 id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Button ID="btnCallSP" runat="server" Text="Call SP" 
 OnClick="btnCallSP_Click" />
 </div>
 </form>
</body>
</html>

Code Behind

protected void btnCallSP_Click(object sender, EventArgs e)
 {
 try
 {
 DataTable dt = new DataTable();
 DataColumn dtCol = new DataColumn();
 dtCol.ColumnName = "ID";
 dt.Columns.Add(dtCol);
dtCol = new DataColumn();
 dtCol.ColumnName = "Name";
 dt.Columns.Add(dtCol);
dtCol = new DataColumn();
 dtCol.ColumnName = "Salary";
 dt.Columns.Add(dtCol);
for (int i = 0; i < 10; i++)
 {
 DataRow dr = dt.NewRow();
 dr["Name"] = "Name " + i;
 dr["Salary"] = 1000 + i;
 dr["ID"] = i;
 dt.Rows.Add(dr);
 }
 
 string connStr = ConfigurationManager.
 AppSettings["LocalSqlServer"].ToString();
 SqlConnection con = new SqlConnection(connStr);
using (var conn = new SqlConnection(connStr))
 using (var cmd = conn.CreateCommand())
 {
 cmd.Connection = con;
 con.Open();
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.CommandText = "dbo.InsertOfficerDetails";
 SqlParameter param = cmd.Parameters.AddWithValue("@OfficerData", dt);
 cmd.ExecuteNonQuery();
 }
 }
 catch (Exception a)
 {
 Response.Write(a.Message);
 }
 }

Web.Config

<appSettings>
 <add key="LocalSqlServer" 
value="Database=testDB;Server=Servername\SQLEXPRESS;User Id=userid;Password=password"/>
</appSettings>

Hence we discussed about how to create and use Table valued parameters, how to create a store procedure with table type as parameter, how to pass table to stored procedure in C#/Asp.Net,  how to insert multiple rows of data to a table with table valued parameter in SQL, how to insert bulk data to SQL table using Table Valued Parameter in SQL Server 2008 etc..

 

How to create asynchronous file up loader using ajax in ASP.Net


Ajax files uploader in ASP.Net/C# to upload files to Server as asynchronous 

In most of the web applications, there might be have an option to upload files to server. If we are using ASP.Net file uplaoder option to upload files, will have postback after every server request. It may be very disturbance to the user. In order to avoid postback while uploading files into server in ASP.Net/C#, we can implement AJAX mechanism.

Include AjaxControlToolkit reference to the Project

First of all we need to refer ajax tool kit to our project. In order to do this, right click the project and add reference and select the folder that included the ajaxtoolkit file. Once we added, in the aspx page below line will be displayed

<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>

After that we can incuded ajax  uploader into the ASPX page like this.

<ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete"OnClientUploadError="uploadError" 
CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern"UploadingBackColor="#CCFFFF" 
ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" />

There are some special kind if events are available in the control like onUploadComplete, OnClineUploadError ..

OnClientUploadError – This property is used to execute the client side JavaScript function if file uploading failed.

OnClientUploadStarted – This property is used to execute the client side JavaScript function whenver file uploading start.

OnClientUploadComplete – This property is used to execute the client side JavaScript function after file successfully uploaded.

CompleteBackColor – This property is used to set fileupload control background after file upload complete its default value ‘Lime’.

ErrorBackColor – This property is used to set fileupload control background if file upload failed its default value ‘Red’.

UploadingBackColor – This property is the id of the control which is seen during upload file.

UploaderStyle – This property is used to set fileupload control appearance style either Modern orTraditional. By default its value “Traditional”.

ThrobberID – ID of control that is shown while the file is uploading.

 

ASPX PAGE

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title>Untitled Page</title> 
<script type="text/javascript"> 
// This function will execute after file uploaded successfully 
function uploadComplete() { 
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File Uploaded Successfully"; 
} 
// This function will execute if file upload fails 
function uploadError() { 
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File upload Failed."; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<ajax:ToolkitScriptManager ID="scriptManager1" runat="server"/> 
<div> 
<ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete"OnClientUploadError="uploadError"
 CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern"UploadingBackColor="#CCFFFF"
 ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" /><br />
 <asp:Image ID="imgLoad" runat="server" ImageUrl="loading.gif" />
 <br />
 <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
 </div>
 </form>
 </body>
 </html>

CODE BEHIND

using System;
using System.Web.UI;
using AjaxControlToolkit;

protected void fileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(fileUpload1.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/") + filename);
}

 

How to crop image using ASP.Net/C# OR Cropping image in C# before upload

May 22, 2012 40 comments

DOWNLOAD SOURCE CODE FOR CROP IMAGE IN ASP.NET

Crop images before upload to the server in C#/ASP.Net

In our previous post we demonstrate how we can re size image using C# or Create thumbnail image using ASP.Net. Here we are demonstrating how we can crop images using ASP.Net application using Jquery and C#. In some applications we need to upload images and we need only some portion of the images to get clear picture on the photo. In this case we need to give an option to users to crop image before they are uploading the image.

Include Jquery file/CSS files to the application. 

First of all we need to include following jquery/CSS files to the application.

1.       jquery.min.js     –    You can download from here

2.       jquery.Jcrop.js   –    You can download from here

3.       jquery.Jcrop.css   –    You can download from here 

Simple steps to crop image using ASP.Net,C#,Jquery

In this application we are having a browse option for selecting an image. Once we selected a image it will display int the screen.

Crop image using ASP.net C#

Select an image to crop using ASP.Net C# Jquery

In the next step we will have the option to select an area to crop the image. Once we selected an area we can click crop button on the screen.

Crop image using ASP.Net C#

Select image area to crop

Then the selected area will be cropped and displayed in the screen.

Crop image using ASP.Net C#

Cropped area of the image

ASPX Page for crop images using Jquery 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CropImage.aspx.cs" 
Inherits="ExperimentLab.CropImage" %>
<!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 id="Head1" runat="server">
 <title>Crop Image</title>
 <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" 
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>
 <script type="text/javascript">
 jQuery(document).ready(function () {
 jQuery('#imgCrop').Jcrop({
 onSelect: storeCoords
 });
 });
function storeCoords(c) {
 jQuery('#X').val(c.x);
 jQuery('#Y').val(c.y);
 jQuery('#W').val(c.w);
 jQuery('#H').val(c.h);
 };
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Panel ID="pnlUpload" runat="server">
 <asp:FileUpload ID="Upload" runat="server" />
 <br />
 <asp:Button ID="btnUpload" runat="server" 
 OnClick="btnUpload_Click" Text="Upload" />
 <asp:Label ID="lblError" runat="server" Visible="false" />
 </asp:Panel>
 <asp:Panel ID="pnlCrop" runat="server" Visible="false">
 <asp:Image ID="imgCrop" runat="server" />
 <br />
 <asp:HiddenField ID="X" runat="server" />
 <asp:HiddenField ID="Y" runat="server" />
 <asp:HiddenField ID="W" runat="server" />
 <asp:HiddenField ID="H" runat="server" />
 <asp:Button ID="btnCrop" runat="server" Text="Crop" 
 OnClick="btnCrop_Click" />
 </asp:Panel>
 <asp:Panel ID="pnlCropped" runat="server" Visible="false">
 <asp:Image ID="imgCropped" runat="server" />
 </asp:Panel>
 </div>
 </form>
</body>
</html>

Code Behind of the ASPX page for Crop image using ASP.Net/C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Drawing2D;
namespace ExperimentLab
{
public partial class CropImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
protected void btnUpload_Click(object sender, EventArgs e)
{
Boolean FileOK = false;
Boolean FileSaved = false; 
if (Upload.HasFile)
{
Session["WorkingImage"] = Upload.FileName;
String FileExtension =
Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
 FileOK = true;
}
}
}
if (FileOK)
{
try
{
Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
FileSaved = true;
}
catch (Exception ex)
{
lblError.Text = "File could not be uploaded." + ex.Message.ToString();
lblError.Visible = true;
FileSaved = false;
}
}
else
{
lblError.Text = "Cannot accept files of this type.";
lblError.Visible = true;
}
if (FileSaved)
{
pnlUpload.Visible = false;
pnlCrop.Visible = true;
imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
}
}
protected void btnCrop_Click(object sender, EventArgs e)
{
string ImageName = Session["WorkingImage"].ToString();
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
byte[] CropImage = Crop(path + ImageName, w, h, x, y);
using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
{
ms.Write(CropImage, 0, CropImage.Length);
using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
{
string SaveTo = path + "crop" + ImageName;
CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
pnlCrop.Visible = false;
pnlCropped.Visible = true;
imgCropped.ImageUrl = "images/crop" + ImageName;
}
}
}
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (SD.Image OriginalImage = SD.Image.FromFile(Img))
{
using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
{
 bmp.SetResolution(OriginalImage.HorizontalResolution, 
 OriginalImage.VerticalResolution);
 using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
 {
 Graphic.SmoothingMode = SmoothingMode.AntiAlias;
 Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
 Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
 Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height),
 X, Y, Width, Height, SD.GraphicsUnit.Pixel);
 MemoryStream ms = new MemoryStream();
 bmp.Save(ms, OriginalImage.RawFormat);
 return ms.GetBuffer();
 }
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
}
}


DOWNLOAD SOURCE CODE FOR CROP IMAGE IN ASP.NET

Disable right click on a web page in asp.net/C# using Jquery/Javascript

March 20, 2012 2 comments

How to disable right click functionality from the asp.net web page

In some of the web page has the requirement to protect source code from the users. Users can right click the page and take the source code. In order protect right click functionality on the web page we can implement javascript functionality to prevent user’s right click on the web page. So user not able to access features available on the right click menus.

By implementing javascript method we can identify the right click event from the user by checking the button code and prevent if the user clicks right click. Below mentioned web page prevented to click right click by the user. When the user trying to right click it will return warning message to user and return the action.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisableRightClick.aspx.cs"
 Inherits="ExperimentLab.DisableRightClick" %>
<!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 id="Head1" runat="server">
 <title>Sample to Disable Right Click of Page</title>
 <script language="JavaScript" type="text/javascript">
 //Message to display whenever right click on website
 var message = "Sorry, Right Click have been disabled.";
 function click(e) {
 if (document.all) {
 if (event.button == 2 || event.button == 3) {
 alert(message);
 return false;
 }
 }
else {
 if (e.button == 2 || e.button == 3) {
 e.preventDefault();
 e.stopPropagation();
 alert(message);
 return false;
 }
 }
 }
if (document.all) {
 document.onmousedown = click;
 }
else {
 document.onclick = click;
 }
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 In this page right click not allowed.
 </div>
 </form>
</body>
</html>

Disable copy paste on textbox in the ASP.Net/C# using javascript/Jquery

March 15, 2012 2 comments

Very simple method to disable copy paste in the textbox without any extra script

To achieve some requirements like disable copy paste functionalities in the textbox in aspx page, commonly we need to write some additional javascript functionalities in the aspx page. We can achieve this features using very simple methods.

First Method to disable Ctrl Key and right click on textbox

This method is very simple method and here we don’t need to include any javascript methods or files. We are having oncopy and onpaste event for the textboxes and can call return false for this both event.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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 id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>First Method To disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox2" runat="server" oncopy="return false" oncut="return false"
 onpaste="return false"></asp:TextBox>
 </div>
 </form>
</body>
</html>

Second method to prevent copy paste feature in the aspx texbox

In this option, we are calling a javascript function on any key press. This function checks whether user press ctrl key or right click using e.keyCode and e.button variable. If the user press ctrl key or right click, from the javascript function call return false

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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 id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
 <script language="javascript" type="text/javascript">
//Function to disable Cntrl key/right click
function DisableControlKey(e) {
// Message to display
var message = "Cntrl key/ Right Click Option disabled";
// Condition to check mouse right click / Ctrl key press
if (e.keyCode == 17 || e.button == 2) {
alert(message);
return false;
}
}
</script>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>Second Method to Disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox3" runat="server" onKeyDown="return DisableControlKey(event)"
 onMouseDown="return DisableControlKey(event)"></asp:TextBox>
 </div>
 </form>
</body>
</html>


%d bloggers like this: