Sunday, September 28, 2008

Simple Practice to Employ AJAX

This post presents a very simple method to employ AJAX. You would see how AJAX can update the content of your web pages without refreshing the entire pages.
Follow the steps below to create a simple AJAX project (in ASP.NET & C#):

Step 1. Create a Website in Visual Studio 2005/2008.

Step 2. Download the AJAX library here for this practice. And add it as a reference to your Website.

Step 3. In the <system.web> of your web.config file, add the following httpHandlers tag:




<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>


Step 4. In the Page_Load of your ASP.NET page write:
Ajax.Utility.RegisterTypeForAjax(typeof(class_name));
where class_name is the name of the class of your ASP.NET page; e.g. for the page "Default.aspx", class_name would be: Default and you would write:
Ajax.Utility.RegisterTypeForAjax(typeof(Default));
Step 5. In your class add an AJAX method. An AJAX method may be written as follows:
[Ajax.AjaxMethodAttribute(HttpSessionStateRequirement.ReadWrite)]
public object ReadDataFromMyDatabase()
{
return GetData();
// GetData is a regular method to retrieve
// data from your database
}


Step 6. In the html source of your page write a JavaScript function to call your AJAX method; e.g.:
<script language="javascript" type="text/javascript">
function ReadDataFromMyDatabase(){
Default.ReadDataFromMyDatabase(ReadDataFromMyDatabase_CallBack);
}

</script>
Step 7. Your JavaScript function requires a JavaScript Call Back function that will receive data from your AJAX method:

<script language="javascript" type="text/javascript">
function
GetCounts_CallBack(data) {

var
myData = data.value;

// Use your data; e.g.:

document.getElementByID("text1").value = myData;
}


</script>






Saturday, September 27, 2008

Brighten Photo

Brighten Photo 

In this post, a simple function is presented to brighten/darken photos. In this function I use GDI+ and write code in unsafe mode (for efficiency).

using System.Drawing;
using System.Drawing.Imaging;
using GRBIF._CONST;
using System;

namespace IntelliPhoto
{

// Description: A simple GDI+ function for brightening
// Author: G. R. Roosta
// License: Free To Use (No Restriction)

public class BasicFilter
{

public static void Brighten(Bitmap bitmap, int brightness, string newFullFileName)
{
Brighten(bitmap, brightness);
bitmap.Save(newFullFileName);
return;
}

public static void Brighten(Bitmap bitmap, int brightness) // -255 <= brightness <= 255
{
if (brightness < -255 brightness > 255)
throw new Exception("Invalid 'brightness' value!");
BitmapData bmpData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
int stride = bmpData.Stride;
System.IntPtr Scan0 = bmpData.Scan0;
unsafe
{
byte* ptr = (byte*)(void*)Scan0;
int offset = stride - bitmap.Width * 3;
int netWidth = bitmap.Width * 3;
for (int y = 0; y <>
{
for (int x = 0; x <>
{
int c = ptr[0] + brightness;
if (c > 255)
c = 255;
else if (c <>
c = 0;

ptr[0] = (byte)c;
++ptr;
}
ptr += offset;
}
}

bitmap.UnlockBits(bmpData);
return;
}
}
}

Example:


Original Image (taken by Digital Camera: Sony DSC-S650)





Brightened with brightness=+40 using IntelliPhoto.BasicFilter.Brigten




Brightened with brightness=+80 using IntelliPhoto.BasicFilter.Brigten





Brightened with brightness=-40 using IntelliPhoto.BasicFilter.Brigten






Brightened with brightness=-80 using IntelliPhoto.BasicFilter.Brigten

Thursday, September 25, 2008

Retrieve Fields, Tables and SPs [LEVEL::BASIC]


Here are some simple SQL-Script (T-SQL) to retrieve:

1. List of fields of a table
2. List of user tables in a database
3. List of stored procedures in a database

NOTE: In (3), SUBSTRING([name], 1, 3) <> 'sp_' is set to filter system stored procedures (we already know that we should avoid naming stored procedures starting with "sp_" because stored procedures starting with it make the SQL Server first scan the list of system stored procedures.

1.
private const string FIELD_LIST_QUERY = "SELECT DISTINCT syscolumns.name [Name], syscolumns.length Size, ISNULL(systypes.name, 'UNKNOWN') Type, syscolumns.colid Position, syscolumns.isnullable FROM syscolumns INNER JOIN sysobjects ON syscolumns.id = sysobjects.id LEFT OUTER JOIN systypes ON syscolumns.type = systypes.type WHERE (systypes.usertype IS NULL OR systypes.usertype in (1,2,7,10,13,15,16,19,28,12)) AND sysobjects.name = '{0}' ORDER BY 4;";


2.
const string TABLE_NAME_QUERY = "SELECT [name] FROM sys.objects WHERE [type] = 'U' AND is_ms_shipped = 0 AND [name] <> 'sysdiagrams' ORDER BY 1;";

3.
const string SP_NAME_QUERY = "SELECT [name] FROM sys.objects WHERE [type] = 'P' AND SUBSTRING([name], 1, 3) <> 'sp_' ORDER BY 1;";

Execute against Large Number of Records

Execute against Large Number of Records


One way to figure out whether a stored procedure is written in an optimal (or suboptimal) way regarding the required execution time is running it against tables with large number of records. For example, the following two stored procedures perform the same task: to find out the nth highest number in a column; e.g. third highest image height from the Pictures table/view. However, the first one is far less efficient than the second one. For a large table (1,000,000+ records), one can expect that the second one will be executed (in a few seconds) in 1/6 time required for the first one.



-----------------------------------------
-- An inefficient stored procedure to get
-- the Nth highest number in a column.
-- Author: G. R. Roosta

-- License: Free To Use (No Restriction)
-----------------------------------------
CREATE PROC Nth1

@TableName sysname,
@ColumnName sysname,
@N int

AS
BEGIN

SET @TableName = RTRIM(@TableName)
SET @ColumnName = RTRIM(@ColumnName)

DECLARE @SQL CHAR(400)
IF (SELECT OBJECT_ID(@TableName, 'U')) IS NULL
BEGIN
RAISERROR('Invalid table name', 18, 1)
RETURN -1
END

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName)
BEGIN
RAISERROR('Invalid column name', 18, 1)
RETURN -1
END

IF @N <= 0 BEGIN RAISERROR('Nth highest number cannot be less than one!', 18, 1) RETURN -1 END SET @SQL = 'SELECT MAX(' + @ColumnName + ') from ' + @TableName + ' WHERE ' + @ColumnName + ' NOT IN ( SELECT TOP ' + LTRIM(STR(@N - 1)) + ' ' + @ColumnName + ' FROM ' + @TableName + ' ORDER BY ' + @ColumnName + ' DESC )' EXEC (@SQL) END



-----------------------------------------
-- An efficient stored procedure to get
-- the Nth highest number in a column.
-- Author: G. R. Roosta
-- License: Free To Use (No Restriction)
-----------------------------------------

CREATE PROC Nth2

@TableName sysname,
@ColumnName sysname,
@N int

AS
BEGIN

SET @TableName = RTRIM(@TableName)
SET @ColumnName = RTRIM(@ColumnName)

DECLARE @SQL CHAR(400)
IF (SELECT OBJECT_ID(@TableName, 'U')) IS NULL
BEGIN
RAISERROR('Invalid table name', 18, 1)
RETURN -1
END

IF NOT EXISTS(SELECT 1
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @TableName
AND COLUMN_NAME = @ColumnName)
BEGIN
RAISERROR('Invalid column name', 18, 1)
RETURN -1
END

IF @N <= 0 BEGIN RAISERROR('Nth highest number cannot be less than one!', 18, 1) RETURN -1 END SET @SQL = 'SELECT MIN(' + @ColumnName + ') FROM (SELECT TOP ' + STR(@N) + ' ' + @ColumnName + ' FROM ' + @TableName + ' ORDER BY ' + @ColumnName + ' DESC) t000'; EXEC (@SQL) END



DBREINDEX


A SQL Server database will execute queries (reports) faster by re-indexing its tables.

DBCC DBREINDEX re-builds indices for a table. DBCC DBREINDEX can rebuild all the indices for a table in one statement (much easier than running several DROP INDEX and CREATE INDEX sql statements and also DBCC DBREINDEX provides the advantage of getting more optimizations than individual DROP INDEX and CREATE INDEX sql statements).

NOTE: DBCC DBREINDEX cannot be used for system tables.The following script can be used to re-build the indices of a database:



-- This script re-builds the indices of a SQL Server database.
-- Author: G. R. Roosta
-- License: Free To Use (No Restriction)

USE database_name;
GO
DECLARE @TableName varchar(255)
DECLARE fabriclake CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'base table'

OPEN fabriclake
FETCH NEXT FROM fabriclake INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC DBREINDEX(@TableName,' ',90)
FETCH NEXT FROM fabriclake INTO @TableName
END
CLOSE fabriclake
DEALLOCATE fabriclake

MODIFY LOGICAL NAME IN SQL SERVER

To modify the logical name of a data file or a log file in SQL Server, specify the logical file name you want to rename by using the Name parameter and then specify the new logical name for the file by using the NewName parameter. To rename the logical file, run the following T-SQL statement:

ALTER DATABASE database_name MODIFY FILE ( NAME = current_logical_name, NEWNAME = new_logical_name)

Scale Images Using GDI [Level::Basic]

In this post, a simple GDI+ function is presented to Scale images. In this function an image and the required scale ratio is sent a scaled image is returned. See the examples below:





Real Size




Scaled Up (Width:%140, Height %170) [click the image to enlarge it]


Scaled Down (Width:%30, Height %30)
Here is the function:

////////////////////////////////////////////////////////////
//
// Description: A simple GDI+ function for scaling images
// Author: G. R. Roosta
// [royalty-free][digital][picture][photo][print]@
//
// License: Free To Use (No Restriction)
//
////////////////////////////////////////////////////////////

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System;

namespace FABRICLAKE.INTELLIPHOTO.GDI.BASIC
{
public partial class Transform
{
public static Bitmap Scale(Bitmap bmp, double scaleWidth, double scaleHeight)
{
int oldWidth = bmp.Width;
int oldHeight = bmp.Height;
int oldX = 0;
int oldY = 0;

int newX = 0;
int newY = 0;
int newWidth = Convert.ToInt32(oldWidth * scaleWidth);
int newHeight = Convert.ToInt32(oldHeight * scaleHeight);

Bitmap scaledBMP = new Bitmap(newWidth, newHeight, bmp.PixelFormat);
scaledBMP.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

Graphics carpetlake;

try
{
carpetlake = Graphics.FromImage(scaledBMP);
}
catch
{
scaledBMP = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
scaledBMP.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
carpetlake = Graphics.FromImage(scaledBMP);
}

carpetlake.InterpolationMode = InterpolationMode.HighQualityBicubic;

carpetlake.DrawImage(bmp,
new Rectangle(newX, newY, newWidth, newHeight),
new Rectangle(oldX, oldY, oldWidth, oldHeight),
GraphicsUnit.Pixel);

carpetlake.Dispose();
return scaledBMP;
}
}
}

A Brute-Force Duplicate Images Comparison


In this post a simple function is presented that runs a brute-force comparer to find whether two images/photos are exactly the same or not. It works well but not optimal.

using System.Drawing;
using System.Drawing.Imaging;
using System;
namespace Fabriclake.Imaging
{

internal class IntelliPhoto
{
/// <summary>
/// It runs a brute-force comparer to find whether two
/// images/photos are identical or not. It works well
/// but not optimal.
/// Author: G. R. Roosta
/// License: Free To Use (No Restriction)
/// </summary>
/// <param name="photo1">The first image/photo to compare</param>
/// <param name="photo2">The second image/photo to compare</param>
/// <returns>True if two images are identical</returns>
public static bool Identical(Bitmap photo1, Bitmap photo2)
{
int rows = photo1.Height;
int cols = photo1.Width;
if (photo2.Width != cols photo2.Height != rows)
return false;
BitmapData bmpData1 = photo1.LockBits(new Rectangle(0, 0, cols, rows), ImageLockMode.ReadWrite, photo1.PixelFormat);
BitmapData bmpData2 = photo2.LockBits(new Rectangle(0, 0, cols, rows), ImageLockMode.ReadWrite, photo2.PixelFormat);
int stride1 = bmpData1.Stride;
int stride2 = bmpData2.Stride;
IntPtr scan1 = bmpData1.Scan0;
IntPtr scan2 = bmpData2.Scan0;

unsafe
{
byte* p1 = (byte*)(void*)scan1;
byte* p2 = (byte*)(void*)scan2;
int cols3 = cols * 3;
int offs = stride1 - cols3;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols3; j++)
{
if (p1[0] != p2[0])
{
photo1.UnlockBits(bmpData1);
photo2.UnlockBits(bmpData2);
return false;
}
p1++;
p2++;
}
p1 += offs;
p2 += offs;
}
} // end unsafe

photo1.UnlockBits(bmpData1);
photo2.UnlockBits(bmpData2);
return true;
} // end of function
}
}