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.");
}

Wednesday, November 19, 2008

Windows Service errors and Solutions

1) The specified service has been marked for deletion.
* Check the service is already exist in Add Or Remove Programs and uninstall if it is. Then install the service. If the error remain occurs, just restart the computer then install the service. It will be installed fine.
2) The service did not respond to the start or control request in a timely fashion.
* Check the code in Onstart method of service by creating the test project and fix any issues found and also in service constructor method. If the service does not have access rights for creating a eventlog, this error will occur.
3) Some service start and stop automatically if they have no work to do so.
* Check the code in Service default Constructor, and check the access rights for creating eventlog if the any code written for creating eventlog and also check in the call of dll if any dlls are used.
4) Service cannot be started. System.ArgumentNullException: Value cannot be null.
* Open the service properties in Service manager then give the parameters value then start the service(like command line arguments)

Monday, October 20, 2008

Clear database log files

USE database_name
GO
DBCC SHRINKFILE(database_name_log, 1)
BACKUP LOG database_name WITH TRUNCATE_ONLY
DBCC SHRINKFILE(database_name_log, 1)

Delete Records and Reset Identity

Truncate table table_name (we use it when the table has no references)

(or)

delete from table_name
DBCC CHECKIDENT (table_name, RESEED, 0)

(we use it when the table is mapped with other table)

Delete all Stored Procedures in a Database

use [Database_name]

declare @procName varchar(500)

declare cur cursor

for Select [name] from sys.procedures where [type] = 'P' and is_ms_shipped = 0 and [name] not like 'sp[_]%diagram%'

open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin

exec('drop procedure ' + @procName)
fetch next from cur into @procName
end
close cur
deallocate cur

Friday, October 17, 2008

SQL Server 2000 vs. SQL Server 2005

1) The Data Transformation Service (DTS) system (sql server 2000) has been replaces by the SQL System Integration Service (SSIS) in sql server 2005.
2)The GUI management system is much more integrated now with the functionality of both Enterprise Manager and Query Analyser in the same application (SQL Server Management Studio).
3) Exception handling concept is new in sql server 2005. We can use Try Catch block to catch the exception. This feature is limited in sql server 2000 like @@error to show the error, no much flexibility..

Friday, October 3, 2008

Thumbnail Creation

Hi,

The following code is used to create a thumbnail image from the original image using C# code.

string file = "D:\\dcraw\\exif.jpg"; //Request.QueryString["file"];

// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(file); //Server.MapPath(file));

// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

// make a memory stream to work with the image bytes
MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

// make byte array the same size as the image
byte[] imageContent = new Byte[imageStream.Length];

// rewind the memory stream
imageStream.Position = 0;

// load the byte array with the image
imageStream.Read(imageContent, 0, (int)imageStream.Length);

// return byte array to caller with image type
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imageContent);
Hi,

Here is my sample website to check the particular mail id is present or not in any domain.


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CSharp;


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void BtnCheck_Click(object sender, EventArgs e)
{
int result;
result = ChatMailServer(TextBox1.Text.Trim());

if (result == 1)
{
Label1.Text = "Valid E-mail Address";
}
if (result == 2)
{
Label1.Text = "Not a Valid E-mail Address";
}
if (result == 3)
{
Label1.Text = "Error Occured but Domain was GOOD";
}
if (result == 4)
{
Label1.Text = "Domain was invalid";
}
}
public int ChatMailServer(string sEmail)
{
NetworkStream oStream;
string sFrom;
string sTo;
string sResponse;
string Remote_Addr;
string mserver;
string[] sText;
int returnvalue = 0;
sTo = "<" + sEmail + ">";
sText = sEmail.Split('@');
mserver = NSLookup(sText[1]);
if (mserver == "")
{
returnvalue = 4;
return returnvalue;

}
Remote_Addr = "sify.com";
sFrom = "";
TcpClient oConnection = new TcpClient();

try
{
oConnection.SendTimeout = 3000;
oConnection.Connect(mserver, 25);
oStream = oConnection.GetStream();
sResponse = GetData(oStream);
sResponse = TalkToServer(oStream, "HELO " + Remote_Addr + "\n");
sResponse = TalkToServer(oStream, "MAIL FROM: " + sFrom + "\n");
if (ValidResponse(sResponse))
{
sResponse = TalkToServer(oStream, "RCPT TO: " + sTo + "\n");
if (ValidResponse(sResponse))
{
returnvalue = 1;
}
else
{
returnvalue = 2;
}
}
TalkToServer(oStream, "QUIT" + "\n");
oConnection.Close();
oStream = null;
}
catch
{
returnvalue = 3;
}

return returnvalue;
}
private string GetData(NetworkStream oStream)
{
byte[] bResponse = new byte[1024];
string sResponse = "";
int lenStream = 0;

lenStream = oStream.Read(bResponse, 0, 1024); // Doubt

if (lenStream > 0)
{
sResponse = Encoding.ASCII.GetString(bResponse, 0, 1024);
}
return sResponse;

}
private string SendData(NetworkStream oStream, string sToSend)
{
string sResponse;
byte[] bArray = Encoding.ASCII.GetBytes(sToSend.ToCharArray());

oStream.Write(bArray, 0, bArray.Length);
sResponse = GetData(oStream);

return sResponse;
}
private bool ValidResponse(string sResult)
{
bool bResult = false;
int iFirst;

if (sResult.Length > 1)
{
iFirst = Convert.ToInt32(sResult.Substring(0, 1));
if (iFirst < 3)
{
bResult = true;
}

}

return bResult;
}
private string TalkToServer(NetworkStream oStream, string sToSend)
{
string sresponse;

sresponse = SendData(oStream, sToSend);

return sresponse;
}
private string NSLookup(string sDomain)
{
ProcessStartInfo info = new ProcessStartInfo();
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.FileName = "nslookup";
info.Arguments = "-type=MX " + sDomain.ToUpper().Trim();

Process ns;
ns = Process.Start(info);
StreamReader sout;
sout = ns.StandardOutput;
Regex reg = new Regex("mail exchanger = (?[^\\\\\\s]+)");
string mailserver = "";
string response = "";
do
{
response = sout.ReadLine();
Match amatch = reg.Match(response);
Debug.WriteLine(response);
if (amatch.Success)
{
mailserver = amatch.Groups["server"].Value;
}
} while (sout.Peek() > -1);

return mailserver;

}
}

Capture the screen

Hi all,

Here is my small code to capture the screen using C# windows application.

public class ScreenCapture
{
public Image CaptureScreen()
{
return CaptureWindow( User32.GetDesktopWindow() );
}

public Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle,ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest,hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle,hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}

public void CaptureWindowToFile(IntPtr handle, string filename, System.Drawing.Imaging.ImageFormat format)
{
Image img = CaptureWindow(handle);
img.Save(filename,format);
}

public void CaptureScreenToFile(string filename, System.Drawing.Imaging.ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename,format);
}

private class GDI32
{

public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
int nWidth,int nHeight,IntPtr hObjectSource,
int nXSrc,int nYSrc,int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
}

private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
}
}

private void button1_Click(object sender, EventArgs e)
{
ScreenCapture sc = new ScreenCapture();
Image img = sc.CaptureScreen();
pictureBox1.Image = img;
sc.CaptureWindowToFile(this.Handle, "D:\\temp2.gif", System.Drawing.Imaging.ImageFormat.Gif);
}

Tuesday, July 29, 2008

Set Primary Key and Foreign Key to Table using SQL Query

Primary Key:

ALTER TABLE Table_name ADD PRIMARY KEY (SID);

Foreign Key:

ALTER TABLE table_name
ADD CONSTRAINT FK_table_name1_Id FOREIGN KEY (tablename1Id) REFERENCES table_name1(Id)

Backup Database using C#.net

private void button1_Click(object sender, EventArgs e)
{
BackUpDatabase("testdb", "D:\\1.bak");
}
public void BackUpDatabase(string DBname, string setBakUpPath)
{
SqlConnection sCon = new SqlConnection("Data Source=.; Initial Catalog=testdb; Integrated Security=true;");
SqlCommand sCom = new SqlCommand("BACKUP DATABASE " + DBname + " TO DISK = '" + setBakUpPath + "' WITH NOFORMAT, NOINIT, NAME = 'Full Database Backup', SKIP, NOREWIND, NOUNLOAD,STATS = 10", sCon);
sCom.CommandType = CommandType.Text;
try
{
sCon.Open();
sCom.ExecuteNonQuery();
MessageBox.Show("Database " + DBname + " : BackUp Done!", DBname + " BackUp", MessageBoxButtons.OK, MessageBoxIcon.Information);
sCon.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Backup ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
sCom.Dispose();
}

Backup Database SQL SERVER 2005 Query

BACKUP DATABASE DBname
TO DISK = 'setBakUpPath' WITH NOFORMAT, NOINIT,
NAME = 'Full Database Backup', SKIP, NOREWIND, NOUNLOAD,STATS = 10


NOINIT

Indicates that the backup set is appended to the specified media set, preserving existing backup sets. If a media password is defined for the media set, the password must be supplied. NOINIT is the default.

NOSKIP

Instructs the BACKUP statement to check the expiration date of all backup sets on the media before allowing them to be overwritten. This is the default behavior.

SKIP

Disables the checking of backup set expiration and name that is usually performed by the BACKUP statement to prevent overwrites of backup sets. For information about the interactions between { INIT | NOINIT } and { NOSKIP | SKIP }, see "Remarks," later in this topic.

REWIND

Specifies that SQL Server will release and rewind the tape. REWIND is the default.

NOREWIND

Specifies that SQL Server will keep the tape open after the backup operation. You can use this option to help improve performance when performing multiple backup operations to a tape.

NOREWIND implies NOUNLOAD, and these options are incompatible within a single BACKUP statement.

UNLOAD

Specifies that the tape is automatically rewound and unloaded when the backup is finished. UNLOAD is the default when a session begins.

NOUNLOAD

Specifies that after the BACKUP operation the tape will remain loaded on the tape drive.

STATS [ = percentage ]

Displays a message each time another percentage completes, and is used to gauge progress. If percentage is omitted, SQL Server displays a message after each 10 percent is completed.

The STATS option reports the percentage complete as of the threshold for reporting the next interval. This is at approximately the specified percentage; for example, with STATS=10, if the amount completed is 40 percent, the option might display 43 percent. For large backup sets, this is not a problem, because the percentage complete moves very slowly between completed I/O calls.

Thursday, July 10, 2008

Get all SP and Tables and Views from the Database

To get All Stored Procedures:

use [database_name]
SELECT * FROM sys.procedures;

To get All Tables:

select * from Database_name.information_schema.tables

To get All Views:

select * from Database_name.information_schema.views

Create Role and Assign the user to the role

To Create a Role:

Create Role [role_name]

Responsibilities to the Role:

Grant Execute on sp_name to [role_name]
Grant select,insert,update,delete on table_name to role_name


Assign the user to the role:

exec sp_addrolemember N'role_name', N'login_name'

Create Login and user in SQL Server 2005

To Create a Login :

CREATE LOGIN [username] WITH PASSWORD=N'password', DEFAULT_DATABASE=[TestDB],
CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF


To Create a user:

CREATE USER [username] FOR LOGIN [login_name]