Difference between <% %>, <%= %>, <%# %>?

Whenever we are going to write code inside the <% %> then that piece of code will treated as server side code generally vbscript.

When we are accessing any server side variable into the HTML (in .aspx) side then we use <%= %>.

When we are using any binding control like repeater, gridview… etc then to bind the particular column with the database value then we are using <%# %> when the Autogenerate column of the binding controls are FALSE

For Example:

Text='<%#Eval("FirstName") %>' this tag put inside the Text property of the control inside the datagrid like (textbox, label etc....)

...S.VinothkumaR.

Image Resizing by WPF: Using System.Windows.Media.Imaging;

Here is the example of getting resized image by using Imaging namespace in DotNet 3.0.

Same three reference need to add for resizing the image also. PresentationCore, WindowsBase and PresentationFramework.


private void ResizeImage(string SourceImagePath, string ImageType, string TargetImagePath, int decodePixelWidth, int decodePixelHeight)

{

newWidth = 0;

newHeight = 0;

getResizableHeightWidth(SourceImagePath, decodePixelWidth, decodePixelHeight);

byte[] imageBytes = LoadImageData(SourceImagePath);

ImageSource imageSource = CreateResizedImage(imageBytes, newWidth, newHeight);

imageBytes = GetEncodedImageData(imageSource, ImageType);

SaveImageData(imageBytes, TargetImagePath);

}

LoadImageData, GetEncodedImageData and SaveImageData methods are given in last post. Here the CreateResizedImage method is given in below.


//Method for getting resized image by given image data byte array with width and height.

ImageSource CreateResizedImage(byte[] imageData, int width, int height)

{

BitmapImage bmpImage = new BitmapImage();

bmpImage.BeginInit();

if (width > 0)

{

bmpImage.DecodePixelWidth = width;

}

if (height > 0)

{

bmpImage.DecodePixelHeight = height;

}

bmpImage.StreamSource = new MemoryStream(imageData);

bmpImage.CreateOptions = BitmapCreateOptions.None;

bmpImage.CacheOption = BitmapCacheOption.OnLoad;

bmpImage.EndInit();

Rect rect = new Rect(0, 0, width, height);

DrawingVisual drawingVisual = new DrawingVisual();

using (DrawingContext drawingContext = drawingVisual.RenderOpen())

{

drawingContext.DrawImage(bmpImage, rect);

}

RenderTargetBitmap resizedImage = new RenderTargetBitmap(

(int)rect.Width, (int)rect.Height, // Resized dimensions

96, 96, // Default DPI values

PixelFormats.Default); // Default pixel format

resizedImage.Render(drawingVisual);

return resizedImage;

}


//Method for getting resizable height and width by given height and width.

private void getResizableHeightWidth(string ImagePath, int maxWidth, int maxHeight)

{

System.Drawing.Image image = new Bitmap(ImagePath);

int width = image.Width;

int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));

double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

newWidth=0;

newHeight=0;

if (widthFactor > heightFactor)

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);

}

else

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);

}

if (newHeight == 0)

{

newHeight = 1;

}

if (newWidth == 0)

{

newWidth = 1;

}

}



That’s it.


...S.VinothkumaR.

Image Cropping by WPF: Using System.Windows.Media.Imaging;

Introducing System.Windows.Media.Imaging namespace provides types that are used to encode and decode bitmap images.


Here I am going to explain a sample application which is used to cropping images. Imaging namespace is in under Windows Presentation Foundation will do the image manipulation in simple manner.


First of all, we need to add the following reference in our project.

- PresentationCore

- PresentationFramework

- WindowsBase


Then use the following namespace,


using System.Windows.Media;

using System.Windows.Media.Imaging;


The method for creating crop images with passing appropriate parameters as follows,


//Method for Creating Crop Image

private void CreateCropImage(int x, int y, int width, int height, string SourceImagePath, string TargetImagePath, string ImageType)

{

byte[] imgBytest = LoadImageData(SourceImagePath);

System.Drawing.Image img=new Bitmap(SourceImagePath);

CroppedBitmap cb = new CroppedBitmap((BitmapSource)CreateImage(imgBytest,img.Width,img.Height), new Int32Rect(x, y, width, height));

ImageSource imageSource = cb;

byte[] imageBytes = GetEncodedImageData(imageSource, ImageType);

SaveImageData(imageBytes, TargetImagePath);

}


//Method for getting image bytes from image's source path by using FileStream.

private static byte[] LoadImageData(string filePath)

{

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

byte[] imageBytes = br.ReadBytes((int)fs.Length);

br.Close();

fs.Close();

return imageBytes;

}

//Method for getting cropped image.

private static ImageSource CreateImage(byte[] imageData, int decodePixelWidth, int decodePixelHeight)

{

if (imageData == null) return null;

BitmapImage result = new BitmapImage();

result.BeginInit();

if (decodePixelWidth > 0)

{

result.DecodePixelWidth = decodePixelWidth;

}

if (decodePixelHeight > 0)

{

result.DecodePixelHeight = decodePixelHeight;

}

result.StreamSource = new MemoryStream(imageData);

result.CreateOptions = BitmapCreateOptions.None;

result.CacheOption = BitmapCacheOption.OnLoad;

result.EndInit();

return result;

}


//Method for getting encoded image data for the cropped image.

internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)

{

byte[] returnData = null;

BitmapEncoder encoder = null;

switch (preferredFormat.ToLower())

{

case ".jpg":

case ".jpeg":

encoder = new JpegBitmapEncoder();

break;

case ".bmp":

encoder = new BmpBitmapEncoder();

break;

case ".png":

encoder = new PngBitmapEncoder();

break;

case ".tif":

case ".tiff":

encoder = new TiffBitmapEncoder();

break;

case ".gif":

encoder = new GifBitmapEncoder();

break;

case ".wmp":

encoder = new WmpBitmapEncoder();

break;

}

if (image is BitmapSource)

{

MemoryStream stream = new MemoryStream();

encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));

encoder.Save(stream);

stream.Seek(0, SeekOrigin.Begin);

returnData = new byte[stream.Length];

BinaryReader br = new BinaryReader(stream);

br.Read(returnData, 0, (int)stream.Length);

br.Close();

stream.Close();

}

return returnData;

}

//Method for saving the image data as image in to spec

private static void SaveImageData(byte[] imageData, string filePath)

{

FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

BinaryWriter bw = new BinaryWriter(fs);

bw.Write(imageData);

bw.Close();

fs.Close();

}


That's it...


...S.VinothkumaR.

Windows Presentation Foundation.

I think all of you getting pretty confusion why need to explain about WPF cause of lot explanation available in more pages. Actually I am going to post some Image manipulation functionalism in upcoming posts. So here is the introduction to WPF.

The Windows Presentation Foundation is a Graphical subsystem in .Net Framework 3.0 which uses a markup language, known as XAML for rich user interface development. WPF formerly code named Avalon. WCF – Indigo, CardSpace – InfoCard, WF – WorkFlow. WPF is included with Windows Vista, Windows Server 2008, Windows XP Service Pack 2 or later and Windows Server 2003.


It provides a clear separation between the user interface and the business logic. A WPF application can be deployed on the desktop or hosted in a web browser. So we can create a wide range of both standalone and browser-hosted applications.


It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.


Some examples are Yahoo! Messenger and the New York Times Reader, as well as the Contoso Healthcare Sample Application. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library.


I hope this will make you some ideas in WPF. Let we stop the introduction of WPF from here.


...S.VinothkumaR.


Image Resize using C#.

Use the following method to resize an image.

public Image ResizeImage(Image image, int maxWidth, int maxHeight)
{
if (image == null)
{
return image;
}
int width = image.Width;
int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));
double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

if (widthFactor <>
{
// Skip resize
return image;
}
else
{
int newWidth;
int newHeight;
if (widthFactor > heightFactor)
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);
}
else
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);
}
if (newHeight == 0)
{
newHeight = 1;
}
if (newWidth == 0)
{
newWidth = 1;
}
Bitmap bitmap = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
bitmap.SetResolution(96, 96);

Graphics graphics = Graphics.FromImage(bitmap);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
image.Dispose();
return bitmap;
}
}


...S.VinothkumaR.

Bytes to GB MB Conversion using C#

Hi all,

Just copy the following method to getting file size with GB or MB formatted.

private string GetFileSize(long Bytes)
{
if (Bytes >= 1073741824)
{
Decimal size = Decimal.Divide(Bytes, 1073741824);
return String.Format("{0:##.##} GB", size);
}
else if (Bytes >= 1048576)
{ Decimal size = Decimal.Divide(Bytes, 1048576);
return String.Format("{0:##.##} MB", size);
}
else if (Bytes >= 1024)
{ Decimal size = Decimal.Divide(Bytes, 1024);
return String.Format("{0:##.##} KB", size);
}
else if (Bytes > 0 & Bytes <>
{ Decimal size = Bytes;
return String.Format("{0:##.##} Bytes", size);
}
else
{
return "0 Bytes";
}
}

...S.VinothkumaR.

Cropping Image

Use the following code to crop an image by C#.

public Image CropImage(Image img, int cropLeft, int cropTop, int cropWidth, int cropHeight)
{
Bitmap bmp = new Bitmap(img);
Rectangle rect = new Rectangle(cropLeft, cropTop, cropWidth, cropHeight);
Bitmap croppedBmp = bmp.Clone(rect, bmp.PixelFormat);
return croppedBmp;
}


....S.VinothkumaR.

Cropping an Image with best quality using C#

Hi all,

Here is the sample code for getting cropped image with the best quality. Try it out.


public Image CropImage(Image img, int left, int top, int width, int height)
{

try

{

Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);

bmp.SetResolution(80, 60);

Graphics graphics = Graphics.FromImage(bmp);

graphics.SmoothingMode = SmoothingMode.AntiAlias;

graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

graphics.DrawImage(img, new Rectangle(0, 0, width, height), left, top, width, height, GraphicsUnit.Pixel);

img.Dispose();

bmp.Dispose();

graphics.Dispose();

return bmp;
}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

return null;

}
}


that's it....

...S.VinothkumaR.

Query for getting number of employee by department wise.

Hi all,

Here I am having the following two tables.

Table : Department

Id Name

--- ----

1 IT

2 Maths

3 Science


Table: Employee

Id Name DeptId

--- ---- ------

1 aaa 2

2 vvv 2

3 eee 2

4 www 1

5 yyy 2

6 ppp 3

7 ooo 1

8 rrr 3

9 uuu 1

10 iii 3



Now, I need to get the number of employee in each department. How to do?

Here is the query for that.

select dept.Name as DepartmentName,count(*) as NoOfEmp from Department dept

INNER JOIN Employee emp on emp.DeptId=dept.Id group by dept.Name


By running this query, we can get the values like as follows.


DepartmentName NoOfEmp

-------------- -------

IT 3

Maths 4

Science 3


That's it...



...S.VinothkumaR.

Getting the GridViewRow from checkbox checked event.


Get the GridView Row when a checkbox clicked from a GridView.

Here I’m going to give a sample code for getting the selected GridView Row from a Gridview when a checkbox clicked from that gridview.


protected void chkSelect_CheckedChanged(object sender, EventArgs e)

{

CheckBox selectChkBox = (CheckBox)sender;

GridViewRow row = (GridViewRow)( selectChkBox.Parent.Parent);

int index = row.RowIndex;

}


Here the “index” is the row of GridView.


...S.VinothkumaR.


What is the difference between a == b and a.equals(b) ?

a == b means comparision between two variables.

a.equals(b) means comparision between two objects.

...S.VinothkumaR.

What is the difference between Int.parse and Convert.ToInt32

Both the int.Parse and Convert.ToInt32 will return the same result. But the null handling only difference between them.

For example,
string str = "15";
int Val1= Convert.ToInt32(str);
int Val2= int.Parse(str);

From the above code, both Val1 and Val2 return the value as 15. Suppose the string value str has null value, Convert.ToInt32 will return zero and int.Parse will throw ArgumentNullException error.

For example,
string str=null;
int Val1= Convert.ToInt32(str);
int Val2 = int.Parse(str); //This will throw ArgumentNullException Error

That's it...

S.VinothkumaR.

Get xml from a URL

Get xml from a URL

Hi all,
Using HTTPWebRequest and Response, we can easily get the xml file. FYI, see the below code.

First of all, we need to add the following namespaces in our application.

using System.Xml;
using System.IO;
using System.Text;
using System.Net;

Just copy the following code in your button_click event (or as your wish whichever event).

string url = "your url";
Uri fileUrl = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(receiveStream, encode);
string strValue = reader.ReadToEnd();


Now the whole xml file in strValue variable.

...S.VinothkumaR.

Swapping values between two variables without using temp variable.

There is an easy way to swapping values of two variables by using a temporary variable. But here am trying to get interchanged values between those variables without using any temporary variable. Just look in to this…


public int a = 10;

public int b = 20;


//Before swapping

textBox1.Text = a.ToString();

textBox2.Text = b.ToString();

//After swapping

a = a + b;

b = a - b;

a = a - b;

textBox1.Text = a.ToString();

textBox2.Text = b.ToString();

This has been coded in a windows application using C#.

…S.VinothkumaR.

How to combine two data tables?

I just am getting a situation to combine two data tables. Actually in my end, I had two datasets with two data tables in each of them. I needed to combine first data table in first dataset with first data table in second dataset. Similarly second data table in first dataset to second data table in second dataset.

On that moment I just found the way to merge data tables by using DataTable.Merge() method.

Then I combined my data tables as follows,

ds1.Tables[0].Merge(ds2.Tables[0], false,MissingSchemaAction.Add);
ds1.Tables[1].Merge(ds2.Tables[1], false, MissingSchemaAction.Add);

return ds1;


N.B: Here ds1 is first dataset, ds2 is second dataset.

...S.VinothkumaR.

Selecting Top N Number of Rows - SQL Server 2005

Hi all,

We can get rows from a particular table by using the Select query as follows,

select * from [Table_Name]

If we need 10 rows, we can use Top query like as follows,

select top 10 * from [Table_Name]

Suppose we need to pass the number of rows count as parameter…How to do?

Yes, the way of using ROW_NUMBER(), we can do that. For more, see the following example,

First we are going to create a table namely TestCount.

create table TestCount(SNo int, Name varchar(200))

Insert values in to that table.

insert into TestCount(SNo,Name) values(1,'aaa')
insert into TestCount(SNo,Name) values(2,'bbb')
insert into TestCount(SNo,Name) values(3,'ccc')
insert into TestCount(SNo,Name) values(4,'ddd')
insert into TestCount(SNo,Name) values(5,'eee')
insert into TestCount(SNo,Name) values(6,'fff')
insert into TestCount(SNo,Name) values(7,'ggg')
insert into TestCount(SNo,Name) values(8,'hhh')
insert into TestCount(SNo,Name) values(9,'iii')

insert into TestCount(SNo,Name) values(10,'jjj')

Now use the following query to get top n number of rows.

declare @Count int
set @Count = 5
SELECT SNo,Name FROM
(select ROW_NUMBER() over (order by [SNo])
as Row, * FROM
(SELECT SNo,Name FROM TestCount)
as userquery)
as
SelectionWithRowNumbers WHERE Row >0 AND Row<=@Count

That’s it. Hence we can get top n number of rows from a table.

…S.VinothkumaR.