Advertisements

Archive

Archive for the ‘ASP.Net’ Category

How to create always visible div using Ajax/ Always visible div in ASP.Net using Ajax

September 22, 2012 1 comment

                                  DOWNLOAD SOURCE CODE FOR ALWAYS VISIBLE DIV

Create very simple always visible div using ajax in ASP.Net

Here we are demonstrating how to create a very simple always visible div using Ajax in ASP.Net/C#. Some of the WebPages we may need to show some information always visible to user even they are scrolling down and up.   In this situation we can achieved it by different method. In our previous post we already posted how to create a always visible div using CSS. Here we are going to implement the always visible div using Ajax in ASP.Net/C#.

Register Ajax Control Toolkit

In order to implement always visible div using Ajax, we need to download and refer ajax control toolkit to our project. First of all download ajaxtoolkit dll from here and 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 AlwaysVisibleControlExtender in AJAX Controls?

Always vissible Control Extender in Ajax control tool kit is using to implement always vissible div or any controls in ASP.Net/C#.

After registering the ajax control tool kit we can implement alwaysvisibleextender as below mentioned code.

<ajax:alwaysvisiblecontrolextender id="ace" runat="server" targetcontrolid="pnlTimer"
 verticalside="Top" verticaloffset="10" horizontalside="Right" horizontaloffset="10"
 scrolleffectduration=".1" />

We are having some properties in the alwaysvisiblecontrolextender and we can adjust the postion and controls for always visible extender. Below are the main properties of alwaysvissibleextender in ajax.

TargetControlID – ID of control for this extender to always make visible

HorizontalOffset – Distance to the HorizontalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.

HorizontalSide – Horizontal edge of the browser (either Left, Center, or Right) used to anchor the target control. The default is Left.

VerticalOffset – Distance to the VerticalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.

VerticalSide – Vertical edge of the browser (either Top, Middle, or Bottom) used to anchor the target control. The default is Top.

ScrollEffectDuration – Length in seconds of the scrolling effect to last when the target control is repositioned. The default is .1 second.

 ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="AjaxControls.aspx.cs" 
Inherits="ExperimentLab.AjaxControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <ajax:ToolkitScriptManager ID="Scriptmanager1" runat="server">
 </ajax:ToolkitScriptManager>
 <div>
<ajax:AlwaysVisibleControlExtender id="ace" runat="server" 
targetcontrolid="pnlTimer"
 verticalside="Top" verticaloffset="10" horizontalside="Right" 
horizontaloffset="10"
 scrolleffectduration=".1" />
<div runat="server" id="pnlTimer" style="border: 2px solid green; 
height: 100px;
 width: 200px; text-align: center; padding-top: 50px; 
font-weight: bold;">
 This div is always visible to user
</div>
 <br />
 <br />
 Scroll down .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Scroll down
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Scroll down
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Still 'Always visible div' is available ...!
 </div>
 </form>
</body>
</html>

------

                                                        DOWNLOAD SOURCE CODE FOR ALWAYS VISIBLE DIV


			
Advertisements

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

How to maintain scrollposition after post back?

January 6, 2012 Leave a comment

How to maintain scroll position in ASP.Net Pages

When web pages are posted back to the server, by default user is returned to the top of the page. On a large web page, you might have a requirement to scroll down the user automatically to the last position on the page.

MaintainScrollPositionOnPostBack page property can be used to achieve this  in one of the following ways.

  1. Application level:To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.<pages maintainScrollPositionOnPostBack=”true”>
  2. Page Level:for a particular page, open the aspx and set the property<%@ Page MaintainScrollPositionOnPostback=”true” …
  3. Code level: to set the property programmaticallyPage.MaintainScrollPositionOnPostBack = true;
%d bloggers like this: