Tuesday, December 30, 2008

Resize Image with Aspect ratio

Response.ContentType = "Image/Jpeg";
System.Drawing.Image img = System.Drawing.Image.FromFile(@"images1.jpg");
float percent = 100;
if (img.Width > img.Height)
{
if (img.Width > 100)
{
float width = (float)img.Width / 100;
percent = percent / width;
}
}
else
{
if (img.Height > 100)
{
float heigth = (float)img.Height / 100;
percent = percent / heigth;
}
}

System.Drawing.Image image = ImageManipulator.ScaleByPercent(img,(int)percent);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();



public class ImageManipulator
{
public ImageManipulator()
{
//
// TODO: Add constructor logic here
//
}
public static Image ScaleByPercent(Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}
}

Sunday, December 21, 2008

Basic SQL queries

create table Test (Id int Primary Key identity(1, 1), [Name] varchar(50) not null)
alter table Test alter column [Name] int not null
alter table Test add [Age] int not null
delete from Test
DBCC CHECKIDENT (Test, RESEED, 0)
create trigger TestTrigger on Test
FOR INSERT, UPDATE, DELETE
AS
select getDate()
DISABLE TRIGGER ImageTestTrigger ON ImageTest
ENABLE TRIGGER ImageTestTrigger ON ImageTest

drop table Test
DROP trigger TestTrigger

insert into Test([Name], [age]) values('SBala', 25)
update Test Set age = 24 where [Name] = 'SBala'
delete from Test where [Name] = 'SBala'

Create function GetTest() Returns int
as
begin
declare @count int
set @count = (select count(*) from Test)
return @count
end


select dbo.GetTest() as [Count]


begin tran tt
delete from Test
rollback (or) Commit

select * from emp
select e1.[Name], e2.[Name] as Head from emp e1, emp e2
where e1.Head = e2.Id


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER Procedure [dbo].[Emp_Get](@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null')
set @query = @query + ' and Created = ' + @Created
if(@PhoneNumber != 0)
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
exec(@query)
end



alter Procedure Emp_Get(@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null' and @Name != 'null')
set @query = @query + ' and Created = ' + @Created
if(@Created != 'null' and @Name = 'null')
set @query = @query + ' Created = ' + @Created
if(@PhoneNumber != 0)
begin
if(@Created != 'null' or @Name != 'null')
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
else
set @query = @query + ' PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
end
exec(@query)
end

Monday, December 15, 2008

Select records from a Table between Row Numbers

select * from (
select ROW_NUMBER() over (Order by [column_name]) as RowId, *
from [table_name]) as Collections
where Collections.RowId > 10 and Collections.RowId < 20

Tuesday, December 9, 2008

Difference between Session and Cookies

Difference between Session and Cookies
1. The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not.
2. But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
3. The Key difference would be cookies are stored in your hard disk whereas sessions aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
4. A session as is a server-side object which stores State. A cookie is a small piece of information a browser sends to a server with every request.
5. Session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browse
6. Session and cookies differ in type and amount of information they are capable of storing.
Unable to use SQL Server because ASP.NET version 2.0 Session State is not installed on the SQL server. Please install ASP.NET Session State SQL Server version 2.0 or above.

This issue normally occurs when we use sql server for storing session. To overcome this issue, we have to do the following steps.

1) sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="data source=server_name;database=aspnetdb;user id=user;password=pass" cookieless="false" timeout="120" this tag should be in the web.config file.
2) Run the following command from the dot net installed directory.
aspnet_regsql.exe -ssadd -sstype c -d databasename -E

ex: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql.exe -ssadd -sstype c -d DATABASENAME -E

Thursday, December 4, 2008

Getting the List of Installed softwares from the local system

Here is the sample code to get the list of softwares installed in the system.


const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
ManagementClass wmiRegistry = new ManagementClass("root/default",
"StdRegProv", null);
//Enumerate subkeys
string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
object[] methodArgs = new object[] { HKEY_LOCAL_MACHINE, keyPath, null };
uint returnValue = (uint)wmiRegistry.InvokeMethod("EnumKey", methodArgs);
MessageBox.Show("Executing EnumKey() returns: " + returnValue);
if (null != methodArgs[2])
{
string[] subKeys = methodArgs[2] as String[];
if (subKeys == null) return;
ManagementBaseObject inParam =
wmiRegistry.GetMethodParameters("GetStringValue");
inParam["hDefKey"] = HKEY_LOCAL_MACHINE;
string keyName = "";

foreach (string subKey in subKeys)
{
//Display application name
keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" +
subKey;
keyName = "DisplayName";
inParam["sSubKeyName"] = keyPath;
inParam["sValueName"] = keyName;
ManagementBaseObject outParam =
wmiRegistry.InvokeMethod("GetStringValue", inParam, null);

if ((uint)outParam["ReturnValue"] == 0)
{
listBox1.Items.Add(outParam["sValue"]);
}
}
}

Wednesday, December 3, 2008

Get Logical disk drives using C# code

This is the sample code to get the disk drives, cd, removable disk etc...

private void PopulateDriveList()
{
const int Removable = 2;
const int LocalDisk = 3;
const int Network = 4;
const int CD = 5;
//const int RAMDrive = 6;

//Get Drive list

ManagementObjectCollection queryCollection = getDrives();
foreach ( ManagementObject mo in queryCollection)
{
switch (int.Parse( mo["DriveType"].ToString()))
{
case Removable: //removable drives

break;
case LocalDisk: //Local drives

break;
case CD: //CD rom drives

break;
case Network: //Network drives

break;
default: //defalut to folder

break;
}
}

}
protected ManagementObjectCollection getDrives()
{
//get drive collection
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
ManagementObjectCollection queryCollection = query.Get();
return queryCollection;
}

Create Database and tables using C# code

This is the sample code to create database and its tables, Views and SP.

string conStr = "Data Source=server_name; Initial Catalog=Master; User ID=dummy; Password=dummy;";
FileInfo fileInfo = new FileInfo(@"C:\1.sql");
string script = fileInfo.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("select [name] from sys.databases", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List databaseList = new List();
while (dr.Read())
{
databaseList.Add(dr[0].ToString());
}
conn.Close();
if (databaseList.Contains("TestDB1"))
{
MessageBox.Show("Database already exists.");
}
else
{
cmd = new SqlCommand("Create Database TestDB1", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conStr = "Data Source=server_name; Initial Catalog=TestDB1; User ID=dummy; Password=dummy;";
conn = new SqlConnection(conStr);
cmd = new SqlCommand(script, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Database created successfully.");
}