.

Saturday, December 13, 2008

SQL String Functions


SQL String Functions



Sql string function is a built-in string function.
It perform an operation on a string input value and return a string or numeric value.
Below is All built-in Sql string function :



Example SQL String Function
-
ASCII
- Returns the ASCII code value of a keyboard button and the rest etc (@,R,9,*) .
Syntax - ASCII ( character)
SELECT ASCII('a') -- Value = 97
SELECT ASCII('b') -- Value = 98
SELECT ASCII('c') -- Value = 99
SELECT ASCII('A') -- Value = 65
SELECT ASCII('B') -- Value = 66
SELECT ASCII('C') -- Value = 67
SELECT ASCII('1') -- Value = 49
SELECT ASCII('2') -- Value = 50
SELECT ASCII('3') -- Value = 51
SELECT ASCII('4') -- Value = 52
SELECT ASCII('5') -- Value = 53



Example SQL String Function - SPACE
-Returns spaces in your SQL query (you can specific the size of space).
Syntax - SPACE ( integer)
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')
-- Value = SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')
-- Value = SQL TUTORIALS



Example SQL String Function - CHARINDEX
-Returns the starting position of a character string.
Syntax - CHARINDEX ( string1, string2 [ , start_location ] )
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial')

-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20)

-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)
-- Value = 0 (Because the index is count from 30 and above)


Example SQL String Function - REPLACE
-Replaces all occurrences of the string2 in the string1 with string3.
Syntax - REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')
-- Value = SQL Function


Example SQL String Function - QUOTENAME
-Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax - QUOTENAME ( 'string' [ , 'quote_character' ] )
SELECT QUOTENAME('Sql[]String')
-- Value = [Sql[]]String]


Example SQL String Function - STUFF
- Deletes a specified length of characters and inserts string at a specified starting index.
Syntax - STUFF ( string1 , startindex , length , string2 )

SELECT STUFF('SqlTutorial', 4, 6, 'Function')
-- Value = SqlFunctional
SELECT STUFF('GoodMorning', 5, 3, 'good')
-- Value = Goodgoodning


Example SQL String Function - LEFT
-Returns left part of a string with the specified number of characters.
Syntax - LEFT ( string , integer)
SELECT LEFT('TravelYourself', 6)
-- Value = Travel
SELECT LEFT('BeautyCentury',6)
-- Value = Beauty


Example SQL String Function - RIGHT
-Returns right part of a string with the specified number of characters.
Syntax - RIGHT( string , integer)
SELECT RIGHT('TravelYourself', 6)
-- Value = urself
SELECT RIGHT('BeautyCentury',6)
-- Value =
Century


Example SQL String Function - REPLICATE
-Repeats string for a specified number of times.

Syntax - REPLICATE (string, integer)
SELECT REPLICATE('Sql', 2)

-- Value = SqlSql


Example SQL String Function - SUBSTRING
-Returns part of a string.

Syntax - SUBSTRING ( string, startindex , length )
SELECT SUBSTRING('SQLServer', 4, 3)

-- Value = Ser


Example SQL String Function - LEN
-Returns number of characters in a string.
Syntax - LEN( string)
SELECT LEN('SQLServer')
-- Value =
9


Example SQL String Function - REVERSE
-Returns reverse a string.
Syntax - REVERSE( string)
SELECT REVERSE('SQLServer')

-- Value = revreSLQS


Example SQL String Function - UNICODE
-Returns Unicode standard integer value.
Syntax - UNICODE( char)
SELECT UNICODE('SqlServer')
-- Value = 83 (it take first character)
SELECT UNICODE('S')
-- Value =
83


Example SQL String Function - LOWER
-Convert string to lowercase.
Syntax - LOWER( string )
SELECT LOWER('SQLServer')

-- Value = sqlserver


Example SQL String Function - UPPER
-Convert string to Uppercase.
Syntax - UPPER( string )
SELECT UPPER('sqlserver')
-- Value = SQLSERVER


Example SQL String Function - LTRIM
-Returns a string after removing leading blanks on Left side.
Syntax - LTRIM( string )
SELECT LTRIM(' sqlserver')
-- Value = 'sqlserver' (Remove left side space or blanks)



Example SQL String Function - RTRIM
-Returns a string after removing leading blanks on Right side.

Syntax - RTRIM( string )
SELECT RTRIM('SqlServer ')
-- Value = 'SqlServer' (Remove right side space or blanks)

SQL Server DataType

SQL Server DataType

All Sql DataType

bigint
Integer data from -2^63 through 2^63-1

binary
Fixed-length binary data with a maximum length of 8,000 bytes

bit

Integer data with either a 1 or 0 value

char
Fixed-length character data with a maximum length of 8,000 characters

datetime

Date and time data from January 1, 1753, through December 31, 9999,with an accuracy of 3.33 milliseconds

decimal

Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1

float
Floating precision number data from -1.79E + 308 through 1.79E + 308

image

Variable-length binary data with a maximum length of 2^31 - 1 bytes

int
Integer data from -2^31 through 2^31 - 1

money
Monetary data values from -2^63 through 2^63 - 1

nchar
Fixed-length Unicode data with a maximum length of 4,000 characters

ntext
Variable-length Unicode data with a maximum length of 2^30 - 1 characters

nvarchar

Variable-length Unicode data with a maximum length of 4,000 characters

numeric

Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1

real
Floating precision number data from -3.40E + 38 through 3.40E + 38

smalldatetime

Date and time data from January 1, 1900, through June 6, 2079,with an accuracy of one minute

smallint

Integer data from -2^15 through 2^15 - 1

smallmoney
Monetary data values from -214,748.3648 through +214,748.3647

sysname

text

Variable-length data with a maximum length of 2^31 - 1 characters

timestamp

tinyint

Integer data from 0 through 255

varbinary
Variable-length binary data with a maximum length of 8,000 bytes

varchar

Variable-length data with a maximum of 8,000 characters

uniqueidentifier

A globally unique identifier

SQL Server Alternate of Count()

SQL Alternative Count

Both SQL Query below returns same result but the speed of retrieving data are different.
Copy Below Both Sql Query to Query analyzer to test it. Customers is a Table Name.

1. SELECT rows FROM sysindexes WHERE id = OBJECT_ID('Customers') AND indid <>
You can use sysindexes system table to get number of ROWS. This column contains the total row count for each table in your database. So, you can use the following select statement instead of Below one:


2. SELECT Count(*) FROM Customers
This SQL query performs full table scan to get the row count.


So, you can improve the speed of the SQL query using the Above First SQL instead of Second SQL Query

What's New in SQL Server 2008?

What's New in SQL Server 2008?

Tuesday December 4, 2007
In a recent interview, SQL Server MVP Brad McGehee offered some observations about Microsoft's pending release of SQL Server 2008. His thoughts, in a nutshell, were:
  • SQL Server continues to get more complex and many DBAs are behind the curve because they haven't yet upgraded to SQL Server 2005
  • PowerShell, included in SQL Server 2008, is unlikely to see much adoption among DBAs
  • The rewritten Reporting Services and Analysis Services are scalable and don't require IIS
  • The Declarative Management Framework (DMF) is the big selling point for 2008, offering consistent enterprise management

Simple Trigger

Simple Trigger

Simple trigger that Delete records from particular table.

Situation : There is one field type is single/joint if user select joint one field enter joint account name and if single then that fields disapears so now if user change joint type to single then joint account name is deleted form database using this trigger.

Answer :

CREATE TRIGGER Tr_Name_UpdateRecordTable
On Table_name
FOR UPDATE,insert AS
declare @Id int
declare @Type int

select @Id=Id from inserted
select @Type=Type from inserted

// @Type=1 mean single else joint

IF @Type=1

BEGIN

Update Table_name set JointAccountFirstName='' ,JointAccountMiddleName='' ,
JointAccountLastName='' where Id=@Id

END

Useful Sql Querys

Useful Sql Querys

Print Row number in Sqlserver 2005

SELECT (ROW_NUMBER() OVER (ORDER BY field_name) )as RowNumber,
field1, field2,fieldn FROM tablename

Get random record from database

SELECT TOP 1 field1, field2,fieldn FROM tablename ORDER BY NEWID()

Find Recenty executed Query in SQLSERVER 2005


SELECT

DMExQryStats.last_execution_time AS [Executed At], DMExSQLTxt.text AS [Query]
FROM
sys.dm_exec_query_stats AS DMExQryStats
CROSS APPLY
sys.dm_exec_sql_text(DMExQryStats.sql_handle) AS DMExSQLTxt
ORDER BY
DMExQryStats.last_execution_time DESC


Taking Multiple backups in SQL SERVER 2005


BACKUP DATABASE Northwind
TO DISK = 'D:\DataabseBkps1\Northwind.bak'
MIRROR
TO DISK = 'E:\DataabseBkps2\Northwind.bak'
WITH FORMAT;
  • consistent enterprise management

SQL Server Combine 2 Different Table

SQL Server : Combine 2 Different Table

This SQL is use to combine 2 different table together for other purpose.
SELECT ISNULL(a.Col1,b.Cola) , ISNULL(a.Col2,b.Colb)
FROM Table1 a
FULL JOIN Table2 b
ON a.Col1 = b.Cola

Here is 2 Different Table,
Table Name : Salary
NameSalary
emil1000
rayden2000


Table Name: Flight
FligtTicketPrice
Kuala Lumpur265
Bangkok878


Below Sql is use to combine above 2 Tables Become below 1 Table
SELECT ISNULL(a.Name,b.FlightTicket) AS Col1, ISNULL(a.Salary,b.Price) AS Col2 FROM Salary a
FULL JOIN Flight b ON a.Name = b.FlightTicket

Col1Col2
emil1000
rayden2000
Kuala Lumpur265
Bangkok878

SQL DATE Function

SQL DATENAME Function

It return specifies the part of the date name and the DATENAME for Date Time such as Year, Quarter, Month, Day, Hour, Minute and Milisecond.

SQL DATENAME Syntax
DATENAME ( datepart , date )

Example

SELECT GETDATE() = 2007-05-30 23:13:38.763

SELECT DATENAME(year, GETDATE())
SELECT DATENAME(yy, GETDATE())
SELECT DATENAME(yy, GETDATE())
- It will return value = 2007

SELECT DATENAME(quarter, GETDATE())
SELECT DATENAME(qq, GETDATE())
SELECT DATENAME(q, GETDATE())
-It will return value = 2 (because 1 quarter equal to 3 month,Detail see below table)

Month

Quarter Value

January - March

1

April - June

2

July - September

3

October - December

4





SELECT DATENAME(month, GETDATE())
SELECT DATENAME(mm, GETDATE())
SELECT DATENAME(m, GETDATE())
- It will return value = May

SELECT DATENAME(dayofyear, GETDATE())
SELECT DATENAME(dy, GETDATE())
SELECT DATENAME(y, GETDATE())
- It will return value = 150 (this is calculate total day from 1 jan 2007 until 30 may 2007)

SELECT DATENAME(day, GETDATE())
SELECT DATENAME(dd, GETDATE())
SELECT DATENAME(d, GETDATE())
- It will return value =
30

SELECT DATENAME(week, GETDATE())
SELECT DATENAME(wk, GETDATE())
SELECT DATENAME(ww, GETDATE())
- It will return value = 23 (this is 23rd week from 1 jan 2007)

SELECT DATENAME(hour, GETDATE())
SELECT DATENAME(hh, GETDATE())
- It will return value = 23 (time for 24 hour)

SELECT DATENAME(minute, GETDATE())
SELECT DATENAME(mi, GETDATE())
SELECT DATENAME(n, GETDATE())
- It will return value = 13 (minute)

SELECT DATENAME(second , GETDATE())
SELECT DATENAME(ss, GETDATE())
SELECT DATENAME(s, GETDATE())
- It will return value = 38 (second)

SELECT DATENAME(millisecond , GETDATE())
SELECT DATENAME(ms, GETDATE())
- It will return value = 763 (milisecond)

Naming Conventions

Control Naming Conventions

BackgroundWorker - bgwrk
BindingNavigator - bndnav
BindingSource - bndsrc
Button - btn
CheckBox - chk
CheckedListBox - chklb
ColorDialog - clrdlg
ComboBox - cmb
ContextMenuStrip - cms
DataGridView - grd (I don’t differentiate between variants)
DataSet - ds
DateTimePicker - dtpick
DirectoryEntry - dirent
DirectorySearcher - dirsrc
DomainUpDown - dupdn
ErrorProvider - err
EventLog - evtlog
FileSystemWatcher - fsw
FlowLayoutPanel - pnl (I don’t differentiate between variants)
FolderBrowserDialog - flddlg
FontDialog - fntdlg
GroupBox - grp
HelpProvider - hlp
HScrollBar - hscr
ImageList - imglst
Label - lbl
LinkLabel - lnklbl
ListBox - lb
ListView - lvw
MaskedTextBox - txt (I don’t differentiate between variants)
MenuStrip - mnustrp
MessageQueue - mq
MonthCalendar - cal
NotifyIcon - noticn
NumericUpDown - nupdn
OpenFileDialog - opndlg
PageSetupDialog - pgdlg
Panel - pnl (I don’t differentiate between variants)
PerformanceCounter - prfcnt
PictureBox - pic
PrintDialog - prndlg
PrintDocument - prndoc
PrintPreviewControl - ppc
PrintPreviewDialog - ppd
Process - proc
ProgressBar - prg
PropertyGrid - prpgrd
RadioButton - btn
RichTextBox - txt
SaveFileDialog - savdlg
SerialPort - prt
ServiceController - svcctr
SplitContainer - cntr
Splitter - splt
StatusStrip - stat
TabControl - tabctl
TableLayoutPanel - pnl (I don’t differentiate between variants)
TextBox - txt
Timer - tmr
ToolStrip - tstrp
ToolStripContainer - tstrpctr
ToolStripMenuItem - mnu
ToolTip - tip
TrackBar - tbar
TreeView - tvw
VScrollBar - vscr
WebBrowser - web
ReportViewer - rpt

Wednesday, November 19, 2008

Mathematical Functions in .NET

Mathematical Functions in .NET

Popular mathematical functions are summarized in the following table. Note that certain functions do not require the Math. prefix.

Mathematical Function in .NET

Math.Abs() Returns the absolute value.

Math.Abs(-10) returns 10.

Math.Ceiling() Returns an integer that is greater than or equal to a number.

Math.Ceiling(5.333) returns 6.

Fix() Returns the integer portion of a number.

Fix(5.3333) returns 5.

Math.Floor() Returns an integer that is less than or equal to a number.

Fix(5.3333) returns 5.

Int() Returns the integer portion of a number.

Int(5.3333) returns 5.

Math.Max() Returns the larger of two numbers.

Math.Max(5,7) returns 7.

Math.Min() Returns the smaller of two numbers.

Math.Min(5,7) returns 5.

Math.Pow() Returns a number raised to a power.

Math.Pow(12,2) returns 144.

Rnd() Returns a random number between 0 and 1. Used in conjunction with Randomizestatement to initialize the random number generator.

Math.Round() Rounds a number to a specified number of decimal places. Rounds up on .5.

Math.Round(1.1234567,5) returns 1.12346.

Math.Sign() Returns the sign of a number. Returns -1 if negative and 1 if positive.

Math.Sign(-5) returns -1.

Math.Sqrt() Returns the square root of a positive number.

Math.Sqrt(144) returns 12.

String Functions in .NET

String Functions in .NET

Several built-in string functions perform string manipulations to augment simple concatenation with the "&" operator.

Function in ASP.NET

Asc() Returns the character code of the first character of a string.

Asc("A") returns 65.

Chr() Returns the display character of a character code.

Chr(65) returns "A".

GetChar() Returns the character at a specified position in a string, counting from 1.

GetChar("This is a string", 7) returns "s".

InStr() Returns the starting position in a string of a substring, counting from 1.

InStr("This is a string", "string") returns 11.

InStrRev() Returns the starting position in a string of a substring, searching from the end of the string.

InStr("This is a string", "string") returns 11.

LCase() Returns the lower-case conversion of a string.

LCase("THIS IS A STRING") returns "this is a string".

Left() Returns the left-most specified number of characters of a string.

Left("This is a string", 4) returns "This".

Len() Returns the length of a string.

Len("This is a string") returns 16.

LTrim() Removes any leading spaces from a string.

LTrim(" This is a string") returns "This is a string".

Mid() Returns a substring from a string, specified as the starting position (counting from 1) and the number of characters.

Mid("This is a string", 6, 4) returns "is a".

Replace() Replaces all occurences of a substring in a string.

Replace("This is a string", " s", " longer s") returns "This are a longer string" (replaces an "s" preceded by a blank space).

Right() Returns the right-most specified number of characters of a string.

Right("This is a string", 6) returns "string".

RTrim() Removes any trailing spaces from a string.

RTrim("This is a string ") returns "This is a string".

Str() Returns the string equivalent of a number.

Str(100) returns "100".

Space() Fills a string with a given number of spaces.
"This" & Space(5) & "string" returns "This string".

StrComp() Compares two strings. Return values are 0 (strings are equal), 1 (first string has the greater value), or -1 (second string has the greater value) based on sorting sequence.

StrComp("This is a string", "This string") returns -1.

StrReverse() Reverses the characters in a string.

StrReverse("This is a string") returns "gnirts a si sihT".

Trim() Removes any leading and trailing spaces from a string.

Trim(" This is a string ") returns "This is a string".

UCase() Returns the upper-case conversion of a string.

UCase("This is a string") returns "THIS IS A STRING".

Val() Converts a numeric expression to a number.

Val( (1 + 2 + 3)^2 ) returns 36.

Tuesday, November 18, 2008

Page Directives in ASP.NET

Page Directives in ASP.NET 2.0

Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:

@ Assembly - Links an assembly to the current page or user control declaratively.

@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).

@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.

@ Import - Imports a namespace into a page or user control explicitly.

@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.

@ MasterType - Defines the class or virtual path used to type the Master property of a page.

@ OutputCache - Controls the output caching policies of a page or user control declaratively.

@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.

@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.

@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.

@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server

Useful Tips for Master Page Control access in Java Csript

Useful Tips for Master Page Control access in Java Csript

When we use master page in ASP.Net it will append the Content Placeholder Id with the ID of the contained controls.i.e when there is a textbox with ID “txtAccountNumber” it will be rendered as “ctl00_ContentPlaceHolder1_txtAccountNumber” where “ContentPlaceHolder1” is the ID of the Content Placeholder of the Master Page. This makes us to use the ID “ctl00_ContentPlaceHolder1_txtAccountNumber” whenever we want to access it in JScript. We can access the textbox in Jscript like,

document.getElementById(' ctl00_ContentPlaceHolder1_txtAccountNumber ') ;

But the above scenario will leads to script error if we unknowingly change the ID of the ContentPlaceholder in master Page. So whenever we change the ContentPlaceholder ID we need to revisit all the Jscript code and change the corresponding ID’s. To prevent this rework we can register a hidden control from code behind which in turn will hold the client ID of the control.

Page.RegisterHiddenField("hdnAccountNoTextID", txtAccountNumber.ClientID);

Now we can make use of this hidden variable to get the client ID of the textbox in Jscript.

//gets the Client ID of the txtAccountNumber textbox
var AccountNoTextID = document.getElementById('hdnAccountNoTextID').value;

//Access the txtAccountNumber textbox
var AccountNoText = document.getElementById('hdnAccountNoTextID');

By doing this we can prevent the rework even if someone changes the ContentPlaceholder ID in future our script will be executing without any error.
The same scenario applies when we use a control inside user control.

MaxLength in TextBox control in ASP.Net

MaxLength in TextBox control in ASP.Net


When I was use TextBOx with TextMode "MultiLine" and MaxLength "10".I can enter more than 10 characters. SO I use Java Script for that and it solve my problem.

JavaScript like this :

< language="javascript">
function limitCharsLength(Object, MaxLen)
{
return (Object.value.length <= MaxLen-1);
}
< /script >


and TextBox like this :

< asp:TextBox ID="TextBox1" runat="server" Height="173px" TextMode="MultiLine"
Width="369px" onkeypress="javascript: return limitCharsLength(this,5);"
onblur="javascript: limitCharsLength(this, 5)"
onchange="javascript : return limitCharsLength(this, 5)" >< /asp:TextBox >

Tuesday, November 11, 2008

SQL Optimization Tips

SQL Optimization Tips

• Use views and stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to
server only stored procedure or view name (perhaps with some
parameters) instead of large heavy-duty queries text. This can be used
to facilitate permission management also, because you can restrict
user access to table columns they should not see.

• Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost
performance. So, you should use constraints instead of triggers,
whenever possible.

• Use table variables instead of temporary tables.
Table variables require less locking and logging resources than
temporary tables, so table variables should be used whenever possible.
The table variables are available in SQL Server 2000 only.

• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL
statement does not look for duplicate rows, and UNION statement does
look for duplicate rows, whether or not they exist.

• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance
degradation, you should use this clause only when it is necessary.

• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in
comparison with select statements. Try to use correlated sub-query or
derived tables, if you need to perform row-by-row operations.

• Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the
GROUP BY clause. When you use GROUP BY with the HAVING clause, the
GROUP BY clause divides the rows into sets of grouped rows and
aggregates their values, and then the HAVING clause eliminates
undesired aggregated groups. In many cases, you can write your select
statement so, that it will contain only WHERE and GROUP BY clauses
without HAVING clause. This can improve the performance of your query.

• If you need to return the total table's row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table's row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*): SELECT rows
FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So,
you can improve the speed of such queries in several times.

• Include SET NOCOUNT ON statement into your stored procedures to stop
the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive
the message indicating the number of rows affected by a T-SQL statement.

• Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will
return to client only particular rows, not all rows from the table(s).
This can reduce network traffic and boost the overall performance of
the query.

• Use the select statements with TOP keyword or the SET ROWCOUNT
statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller
result set will be returned. This can also reduce the traffic between
the server and the clients.

• Try to restrict the queries result set by returning only the
particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will
return to client only particular columns, not all table's columns.
This can reduce network traffic and boost the overall performance of
the query.
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5 In worst cases Denormalization


Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES
and DELETES, so the number of indexes should not be very much. Try to
use maximum 4-5 indexes on one table, not more. If you have read-only
table, then the number of indexes may be increased.

• Keep your indexes as narrow as possible. This reduces the size of
the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather
than character values.

• If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns in the
key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

• If you want to join several tables, try to create surrogate integer
keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your
table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need
to select by a range of values or you need to sort results set with
GROUP BY or ORDER BY.

• If your application will be performing the same query over and over
on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with
"Identify Scans of Large Tables" trace to determine which tables in
your database may need indexes. This trace will show which tables are
being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to
rebuild all indexes in your database. Try to schedule it to execute
during CPU idle time and slow production periods.
sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

Saturday, November 1, 2008

How to get uploaded image Hight & Width in asp.net / c#

How to get uploaded image dimensions in asp.net

I used following code to get uploaded image dimensions .
Where flLogoUplaoded is name of asp .net file uploaded control at my application
string UploadedImageType = flLogoUpload.PostedFile.ContentType.ToString().ToLower();
string UploadedImageFileName = flLogoUpload.PostedFile.FileName;

//Create an image object from the uploaded file
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(flLogoUpload.PostedFile.InputStream);

//Determine width and height of uploaded image
float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;

Response.Write( UploadedImageWidth + “
”);
Response.Write(UploadedImageHeight + “
”);

Saturday, October 11, 2008

Show message box in ASP.NET

Show message box in ASP.NET

I've written a simple function which uses JavaScript.

private void ShowMessageBox(string Message)
{

Label lblMessageBox = new Label();

lblMessageBox.Text =

"";

Page.Controls.Add(lblMessageBox);

}

To call out the message box, just write this:

ShowMessageBox("Hello world!");

The problem with this is that I can't customize the message box. I can only pass in the message as parameter, but not changing the title, the button text or image.
Message box

Wednesday, October 8, 2008

C# - Create a thread to run an process or operation in the background.

C# - Create a thread to run an process or operation in the background.

Using threads is an easy way to stop your user interface from freezing up. In C# .Net creating a thread is as easy as draging and dropping. The component to be used is the "BackgroundWorker" that is located in the Components section of your toolbar.
Steps for using threads.

  • Create a new Windows Form Project.
  • Add 2 buttons to your form. One to start the thread and one to stop it.(btnStartThread, btnEndThread).
  • Add a BackgroundWorker component to your form.
Image

  • Create “Click” event handlers for both the buttons. (Go to the properties window, click on the event icon and then dbl-click on the event handlers you want created. ).
Image

  • Create a “DoWork” and “RunWorkerCompleted” event handler for the BackgroundWorker.
Image

  • Change the BackgroundWorker’s WorkerSupportCancellation property to true. This will enable the cancellation of a running thread.
  • Add “using System.Threading;” To the using part of your program. This will be used to create sleep event.
Next add the following example code to the event handlers you just created.


Code for the "Start Thread" button.

private void btnStartThread_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}


Code for the "End Thread" button.

private void btnEndThread_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}


Code for the Process you want to run.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Make the thread result false by default.
e.Result = false;

// listen for when the cancel button is pressed...
while (!backgroundWorker1.CancellationPending)
{
//-- Background Code Begin -----------------------------------
// This is the process that you want to run. My Example will
// wait for 3 seconds.
//------------------------------------------------------------

for (int k = 1; k < 3000; k++)
{
Thread.Sleep(1);
// Test if the thread was canceled.
if (backgroundWorker1.CancellationPending) break;
}

//-- Background Code Ends- -----------------------------------

// This is a result indicator that shows the background
// process has finished successful.
e.Result = true;

// Run the loop once and exit
break;
}


if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
// Do a roll back if you need to.
}
}


Result of the process that was run.

private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("The operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else if ((bool)e.Result)
{
// The operation completed normally.
string msg = String.Format("Process was completed successful ");
MessageBox.Show(msg);
}

}

Tuesday, October 7, 2008

30 Common String Operations in C# and VB.NET

30 Common String Operations in C# and VB.NET – Part II
All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
VB.NET
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
16. Count Words and Characters In a String – You can use Regular Expression to do so as shown below:
C#
// Count words
System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
MessageBox.Show(wordColl.Count.ToString());
// Count characters. White space is treated as a character
System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charColl.Count.ToString());
VB.NET
' Count words
Dim wordColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, "[\S]+")
MessageBox.Show(wordColl.Count.ToString())
' Count characters. White space is treated as a character
Dim charColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, ".")
MessageBox.Show(charColl.Count.ToString())
17. Remove characters in a String - The String.Remove() deletes a specified number of characters beginning at a given location within a string
C#
// Removes everything beginning at index 25
strModified = strOriginal.Remove(25);
MessageBox.Show(strModified);
or
// Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5);
MessageBox.Show(strModified);
VB.NET
' Removes everything beginning at index 25
strModified = strOriginal.Remove(25)
MessageBox.Show(strModified)
Or
' Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5)
MessageBox.Show(strModified)
18. Create Date and Time from String – Use the DateTime.Parse() to convert a string representing datetime to its DateTime equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in various formats.
C#
strOriginal = "8/20/2008";
DateTime dt = DateTime.Parse(strOriginal);
VB.NET
strOriginal = "8/20/2008"
Dim dt As DateTime = DateTime.Parse(strOriginal)
19. Convert String to Base64 - You will have to use the methods in System.Text.Encoding to convert string to Base64. The conversion involves two processes:
a. Convert string to a byte array
b. Use the Convert.ToBase64String() method to convert the byte array to a Base64 string
C#
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);
VB.NET
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)
20. Convert Base64 string to Original String - In the previous example, we converted a string ‘strOriginal’ to Base64 string ‘strModified’. In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:
a. The FromBase64String() converts the string to a byte array
b. Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();
C#
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
VB.NET
Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)
21. How to Copy a String – A simple way to copy a string to another is to use the String.Copy(). It works similar to assigning a string to another using the ‘=’ operator.
C#
strModified = String.Copy(strOriginal);
VB.NET
strModified = String.Copy(strOriginal)
22. Trimming a String – The String.Trim() provides two overloads to remove leading and trailing spaces as well as to remove any unwanted character. Here’s a sample demonstrating the two overloads. Apart from trimming the string, it also removes the "#" character.
C#
strOriginal = " Some new string we test ##";
strModified = strOriginal.Trim().Trim(char.Parse("#"));
VB.NET
strOriginal = " Some new string we test ##"
strModified = strOriginal.Trim().Trim(Char.Parse("#"))
23. Padding a String – The String.PadLeft() or PadRight() pads the string with a character for a given length. The following sample pads the string on the left with 3 *(stars). If nothing is specified, it adds spaces.
C#
strModified = strOriginal.PadLeft(34,'*');
VB.NET
strModified = strOriginal.PadLeft(34,"*"c)
24. Create a Delimited String – To create a delimited string out of a string array, use the String.Join()
C#
string[] strArr = new string[3] { "str1", "str2", "str3"};
string strModified = string.Join(";", strArr);
VB.NET
Dim strArr As String() = New String(2) { "str1", "str2", "str3"}
Dim strModified As String = String.Join(";", strArr)
25. Convert String To Integer - In order to convert string to integer, use the Int32.Parse(). The Parse method converts the string representation of a number to its 32-bit signed integer equivalent. If the string contains non-numeric values, it throws an error.
Similarly, you can also convert string to other types using Boolean.Parse(), Double.Parse(), char.Parse() and so on.
C#
strOriginal = "12345";
int temp = Int32.Parse(strOriginal);
VB.NET
strOriginal = "12345"
Dim temp As Integer = Int32.Parse(strOriginal)
26. Search a String – You can use IndexOf, LastIndexOf, StartsWith, and EndsWith to search a string.
27. Concatenate multiple Strings – To concatenate string variables, you can use the ‘+’ or ‘+=’ operators. You can also use the String.Concat() or String.Format().
C#
strModified = strOriginal + "12345";
strModified = String.Concat(strOriginal, "abcd");
strModified = String.Format("{0}{1}", strOriginal, "xyz");
VB.NET
strModified = strOriginal & "12345"
strModified = String.Concat(strOriginal, "abcd")
strModified = String.Format("{0}{1}", strOriginal, "xyz")
However, when performance is important, you should always use the StringBuilder class to concatenate strings.
28. Format a String – The String.Format() enables the string’s content to be determined dynamically at runtime. It accepts placeholders in braces {} whose content is replaced dynamically at runtime as shown below:
C#
strModified = String.Format("{0} - is the original string",strOriginal);
VB.NET
strModified = String.Format("{0} - is the original string",strOriginal)
The String.Format() contains 5 overloads which can be studied over here
29. Determine If String Contains Numeric value – To determine if a String contains numeric value, use the Int32.TryParse() method. If the operation is successful, true is returned, else the operation returns a false.
C#
int i = 0;
strOriginal = "234abc";
bool b = Int32.TryParse(strOriginal, out i);
VB.NET
Dim i As Integer = 0
strOriginal = "234abc"
Dim b As Boolean = Int32.TryParse(strOriginal, i)
Note: TryParse also returns false if the numeric value is too large for the type that’s receiving the result.
30. Determine if a String instance starts with a specific string – Use the StartsWith() to determine whether the beginning of a string matches some specified string. The method contains 3 overloads which also contains options to ignore case while checking the string.
C#
if (strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase))
MessageBox.Show("true");
VB.NET
If strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase) Then
MessageBox.Show("true")
End If
So those were some 30 common string operations that we saw in these two articles. Since these articles contained only a short introduction of each method, I would suggest you to explore each method in detail using the MSDN documentation. Mastering string operations can save us a lot of time in projects and improve application performance too. I hope this article was useful and I thank you for viewing it.

Tuesday, September 16, 2008

VB.NET and C# Comparison

VB.NET and C# Comparison


VB.NET

Program Structure

C#

Imports System

Namespace Hello
Class HelloWorld
Overloads Shared Sub Main(ByVal args() As String)
Dim name As String = "VB.NET"

'See if an argument was passed from the command line
If args.Length = 1 Then name = args(0)

Console.WriteLine("Hello, " & name & "!")
End Sub
End Class
End Namespace

using System;

namespace Hello {
public class HelloWorld {
public static void Main(string[] args) {
string name = "C#";

// See if an argument was passed from the command line
if (args.Length == 1)
name = args[0];

Console.WriteLine("Hello, " + name + "!");
}
}
}

VB.NET

Comments

C#

' Single line only
REM Single line only
'''

XML comments

// Single line
/* Multiple
line */
///

XML comments on single line
/** XML comments on multiple lines */

VB.NET

Data Types

C#

Value Types
Boolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date

Reference Types
Object
String

Initializing
Dim correct As Boolean = True
Dim b As Byte = &H2A 'hex
Dim o As Byte = &O52 'octal
Dim person As Object = Nothing
Dim name As String = "Dwight"
Dim grade As Char = "B"c
Dim today As Date = #12/31/2007 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL

Type Information
Dim x As Integer
Console.WriteLine(x.GetType()) ' Prints System.Int32
Console.WriteLine(GetType(Integer)) ' Prints System.Int32
Console.WriteLine(TypeName(x)) ' Prints Integer

Type Conversion
Dim d As Single = 3.5
Dim i As Integer = CType(d, Integer) ' set to 4 (Banker's rounding)
i = CInt(d) ' same result as CType
i = Int(d) ' set to 3 (Int function truncates the decimal)

Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime (not a built-in C# type)

Reference Types
object
string

Initializing
bool correct = true;
byte b = 0x2A; // hex

object person = null;
string name = "Dwight";
char grade = 'B';
DateTime today = DateTime.Parse("12/31/2007 12:15:00");
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;
ulong ulTotal = 123;

Type Information
int x;
Console.WriteLine(x.GetType()); // Prints System.Int32
Console.WriteLine(typeof(int)); // Prints System.Int32
Console.WriteLine(x.GetType().Name); // prints Int32

Type Conversion
float d = 3.5f;
int i = (int)d; // set to 3 (truncates decimal)

VB.NET

Constants

C#

Const MAX_STUDENTS As Integer = 25

' Can set to a const or var; may be initialized in a constructor
ReadOnly MIN_DIAMETER As Single = 4.93

const int MAX_STUDENTS = 25;

// Can set to a const or var; may be initialized in a constructor
readonly float MIN_DIAMETER = 4.93f;

VB.NET

Enumerations

C#

Enum Action
Start
[Stop] ' Stop is a reserved word
Rewind
Forward
End Enum

Enum Status
Flunk = 50
Pass = 70
Excel = 90
End Enum

Dim a As Action = Action.Stop
If a <> Action.Start Then _
Console.WriteLine(a.ToString & " is " & a) ' Prints "Stop is 1"

Console.WriteLine(Status.Pass) ' Prints 70
Console.WriteLine(Status.Pass.ToString()) ' Prints Pass

enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
Console.WriteLine(a + " is " + (int) a); // Prints "Stop is 1"

Console.WriteLine((int) Status.Pass); // Prints 70
Console.WriteLine(Status.Pass); // Prints Pass

VB.NET

Operators

C#

Comparison
= < > <= >= <>

Arithmetic
+ - * /
Mod
\ (integer division)
^ (raise to a power)

Assignment
= += -= *= /= \= ^= <<= >>= &=

Bitwise
And Or Xor Not << >>

Logical
AndAlso OrElse And Or Xor Not

Note: AndAlso and OrElse perform short-circuit logical evaluations

String Concatenation
&

Comparison
== < > <= >= !=

Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are ints)
Math.Pow(x, y)

Assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --

Bitwise
& | ^ ~ << >>

Logical
&& || & | ^ !

Note: && and || perform short-circuit logical evaluations

String Concatenation
+

VB.NET

Choices

C#

greeting = IIf(age <>

' One line doesn't require "End If"
If age <>Then greeting = "What's up?"
If age <>Then greeting = "What's up?" Else greeting = "Hello"

' Use : to put two commands on same line
If x <> 100 And y <>Then x *= 5 : y *= 2

' Preferred
If x <> 100 And y <>Then
x *= 5
y *= 2
End If

' To break up any long single line use _
If whenYouHaveAReally < longLine And _
itNeedsToBeBrokenInto2 > Lines Then _
UseTheUnderscore(charToBreakItUp)

'If x > 5 Then
x *= y
ElseIf x = 5 Then
x += y
ElseIf x <>Then
x -= y
Else
x /= y
End If

Select Case color ' Must be a primitive data type
Case "pink", "red"
r += 1
Case "blue"
b += 1
Case "green"
g += 1
Case Else
other += 1
End Select

greeting = age <>? "What's up?" : "Hello";

if (age < 20)
greeting = "What's up?";
else
greeting = "Hello";

// Multiple statements must be enclosed in {}
if (x != 100 && y < 5) {
x *= 5;
y *= 2;
}

No need for _ or : since ; is used to terminate each statement.





if
(x > 5)
x *= y;
else if (x == 5)
x += y;
else if (x < 10)
x -= y;
else
x /= y;



// Every case must end with break or goto case
switch (color) { // Must be integer or string
case "pink":
case "red": r++; break;
case "blue": b++; break;
case "green": g++; break;
default: other++; break; // break necessary on default
}

VB.NET

Loops

C#

Pre-test Loops:

While c < 10
c += 1
End While

Do Until c = 10
c += 1
Loop

Do While c < 10
c += 1
Loop

For c = 2 To 10 Step 2
Console.WriteLine(c)
Next


Post-test Loops:

Do
c += 1
Loop While c <>

Do
c += 1
Loop Until c = 10

' Array or collection looping
Dim names As String() = {"Fred", "Sue", "Barney"}
For Each s As String In names
Console.WriteLine(s)
Next

' Breaking out of loops
Dim i As Integer = 0
While (True)
If (i = 5) Then Exit While
i += 1
End While

' Continue to next iteration
For i = 0 To 4
If i <>Continue For
Console.WriteLine(i) ' Only prints 4
Next

Pre-test Loops:

// no "until" keyword
while (c < 10)
c++;

for (c = 2; c <= 10; c += 2)
Console.WriteLine(c);



Post-test Loop:

do
c++;
while (c < 10);



// Array or collection looping
string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
Console.WriteLine(s);

// Breaking out of loops
int i = 0;
while (true) {
if (i == 5)
break;
i++;
}

// Continue to next iteration
for (i = 0; i < 5; i++) {
if (i < 4)
continue;
Console.WriteLine(i); // Only prints 4
}

VB.NET

Arrays

C#

Dim nums() As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next

' 4 is the index of the last element, so it holds 5 elements
Dim names(4) As String
names(0) = "David"
names(5) = "Bobby" ' Throws System.IndexOutOfRangeException

' Resize the array, keeping the existing values (Preserve is optional)
ReDim Preserve names(6)



Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5

Dim jagged()() As Integer = { _
New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged(0)(4) = 5

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);


// 5 is the size of the array
string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby"; // Throws System.IndexOutOfRangeException


// C# can't dynamically resize an array. Just copy into new array.
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0);

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

VB.NET

Functions

C#

' Pass by value (in, default), reference (in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
x += 1
y += 1
z = 5
End Sub

Dim a = 1, b = 1, c As Integer ' c set to zero by default
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) ' 1 2 5

' Accept variable number of arguments
Function Sum(ByVal ParamArray nums As Integer()) As Integer
Sum = 0
For Each i As Integer In nums
Sum += i
Next
End Function ' Or use Return statement like C#

Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10

' Optional parameters must be listed last and must have a default value
Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub

SayHello("Strangelove", "Dr.")
SayHello("Madonna")

// Pass by value (in, default), reference (in/out), and reference (out)
void TestFunc(int x, ref int y, out int z) {
x++;
y++;
z = 5;
}

int a = 1, b = 1, c; // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5

// Accept variable number of arguments
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}

int total = Sum(4, 3, 2, 1); // returns 10

/* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
Console.WriteLine("Greetings, " + prefix + " " + name);
}

void SayHello(string name) {
SayHello(name, "");
}

VB.NET

Strings

C#

Special character constants
vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""

' String concatenation (use & or +)
Dim school As String = "Harding" & vbTab
school = school & "University" ' school is "Harding (tab) University"

' Chars
Dim letter As Char = school.Chars(0) ' letter is H
letter = Convert.ToChar(65) ' letter is A
letter = Chr(65) ' same thing
Dim word() As Char = school.ToCharArray() ' word holds Harding

' No string literal operator
Dim msg As String = "File is c:\temp\x.dat"


' String comparison
Dim mascot As String = "Bisons"
If (mascot = "Bisons") Then ' true
If (mascot.Equals("Bisons")) Then ' true
If (mascot.ToUpper().Equals("BISONS")) Then ' true
If (mascot.CompareTo("Bisons") = 0) Then ' true

Console.WriteLine(mascot.Substring(2, 3)) ' Prints "son"

' String matching
If ("John 3:16" Like "Jo[Hh]? #:*") Then 'true

Imports System.Text.RegularExpressions ' More powerful than Like
Dim r As New Regex("Jo[hH]. \d:*")
If (r.Match("John 3:16").Success) Then 'true

' My birthday: Oct 12, 1973
Dim dt As New DateTime(1973, 10, 12)
Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")

' Mutable string
Dim buffer As New System.Text.StringBuilder("two ")
buffer.Append("three ")
buffer.Insert(0, "one ")
buffer.Replace("two", "TWO")
Console.WriteLine(buffer) ' Prints "one TWO three"

Escape sequences
\r // carriage-return
\n // line-feed
\t // tab
\\ // backslash
\" // quote



// String concatenation
string school = "Harding\t";
school = school + "University"; // school is "Harding (tab) University"

// Chars
char letter = school[0]; // letter is H
letter = Convert.ToChar(65); // letter is A
letter = (char)65; // same thing
char[] word = school.ToCharArray(); // word holds Harding

// String literal
string msg = @"File is c:\temp\x.dat";
// same as
string msg = "File is c:\\temp\\x.dat";

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons") // true
if (mascot.Equals("Bisons")) // true
if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.CompareTo("Bisons") == 0) // true

Console.WriteLine(mascot.Substring(2, 3)); // Prints "son"

// String matching
// No Like equivalent - use regular expressions

using System.Text.RegularExpressions;
Regex r = new Regex(@"Jo[hH]. \d:*");
if (r.Match("John 3:16").Success) // true

// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");

// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer); // Prints "one TWO three"

VB.NET

Exception Handling

C#

' Throw an exception
Dim ex As New Exception("Something is really wrong.")
Throw ex

' Catch an exception
Try
y = 0
x = 10 / y
Catch ex As Exception When y = 0 ' Argument and When is optional
Console.WriteLine(ex.Message)
Finally
Beep()
End Try

' Deprecated unstructured error handling
On Error GoTo MyErrorHandler
...
MyErrorHandler: Console.WriteLine(Err.Description)

// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up; // ha ha

// Catch an exception
try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { // Argument is optional, no "When" keyword
Console.WriteLine(ex.Message);
}
finally {
// Requires reference to the Microsoft.VisualBasic.dll
// assembly (pre .NET Framework v2.0)
Microsoft.VisualBasic.Interaction.Beep();
}

VB.NET

Namespaces

C#

Namespace Harding.Compsci.Graphics
...
End Namespace

' or

Namespace Harding
Namespace Compsci
Namespace Graphics
...
End Namespace
End Namespace
End Namespace

Imports Harding.Compsci.Graphics

namespace Harding.Compsci.Graphics {
...
}

// or

namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}

using Harding.Compsci.Graphics;

VB.NET

Classes / Interfaces

C#

Accessibility keywords
Public
Private
Friend
Protected
Protected Friend
Shared

' Inheritance
Class FootballGame
Inherits Competition
...
End Class

' Interface definition
Interface IAlarmClock
...
End Interface

// Extending an interface
Interface IAlarmClock
Inherits IClock
...
End Interface

// Interface implementation
Class WristWatch
Implements IAlarmClock, ITimer
...
End Class

Accessibility keywords
public
private
internal
protected
protected internal
static

// Inheritance
class FootballGame : Competition {
...
}


// Interface definition
interface IAlarmClock {
...
}

// Extending an interface
interface IAlarmClock : IClock {
...
}


// Interface implementation
class WristWatch : IAlarmClock, ITimer {
...
}

VB.NET

Constructors / Destructors

C#

Class SuperHero
Private _powerLevel As Integer

Public Sub New()
_powerLevel = 0
End Sub

Public Sub New(ByVal powerLevel As Integer)
Me._powerLevel = powerLevel
End Sub

Protected Overrides Sub Finalize()
' Desctructor code to free unmanaged resources
MyBase.Finalize()
End Sub
End Class

class SuperHero {
private int _powerLevel;

public SuperHero() {
_powerLevel = 0;
}

public SuperHero(int powerLevel) {
this._powerLevel= powerLevel;
}

~SuperHero() {
// Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
}
}

VB.NET

Using Objects

C#

Dim hero As SuperHero = New SuperHero
' or
Dim hero As New SuperHero

With hero
.Name = "SpamMan"
.PowerLevel = 3
End With

hero.Defend("Laura Jones")
hero.Rest() ' Calling Shared method
' or
SuperHero.Rest()

Dim hero2 As SuperHero = hero ' Both reference the same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) ' Prints WormWoman

hero = Nothing ' Free the object

If hero Is Nothing Then _
hero = New SuperHero

Dim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
Console.WriteLine("Is a SuperHero object.")

' Mark object for quick disposal
Using reader As StreamReader = File.OpenText("test.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
End Using

SuperHero hero = new SuperHero();


// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method



SuperHero hero2 = hero; // Both reference the same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); // Prints WormWoman

hero = null ; // Free the object

if (hero == null)
hero = new SuperHero();

Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");

// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) {
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
}

VB.NET

Structs

C#

Structure StudentRecord
Public name As String
Public gpa As Single

Public Sub New(ByVal name As String, ByVal gpa As Single)
Me.name = name
Me.gpa = gpa
End Sub
End Structure

Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu

stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints Bob
Console.WriteLine(stu2.name) ' Prints Sue

struct StudentRecord {
public string name;
public float gpa;

public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;

stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue

VB.NET

Properties

C#

Private _size As Integer

Public Property Size() As Integer
Get
Return _size
End Get
Set (ByVal Value As Integer)
If Value < 0 Then
_size = 0
Else
_size = Value
End If
End Set
End Property

foo.Size += 1

private int _size;

public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}


foo.Size++;

VB.NET

Delegates / Events

C#

Delegate Sub MsgArrivedEventHandler(ByVal message As String)

Event MsgArrivedEvent As MsgArrivedEventHandler

' or to define an event which declares a delegate implicitly
Event MsgArrivedEvent(ByVal message As String)

AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
' Won't throw an exception if obj is Nothing
RaiseEvent MsgArrivedEvent("Test message")
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

Imports System.Windows.Forms

Dim WithEvents MyButton As Button ' WithEvents can't be used on local variable
MyButton = New Button

Private Sub MyButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyButton.Click
MessageBox.Show(Me, "Button was clicked", "Info", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

// Delegates must be used with events in C#


MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); // Throws exception if obj is null
MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);



using System.Windows.Forms;

Button MyButton = new Button();
MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {
MessageBox.Show(this, "Button was clicked", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

VB.NET

Console I/O

C#

Console.Write("What's your name? ")
Dim name As String = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age)
' or
Console.WriteLine(name & " is " & age & " years old.")

Dim c As Integer
c = Console.Read() ' Read single char
Console.WriteLine(c) ' Prints 65 if user enters "A"

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");


int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user enters "A"

VB.NET

File I/O

C#

Imports System.IO

' Write out to text file
Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()

' Read all lines from text file
Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
reader.Close()

' Write out to binary file
Dim str As String = "Text data"
Dim num As Integer = 123
Dim binWriter As New BinaryWriter(File.OpenWrite("c:\myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()

' Read from binary file
Dim binReader As New BinaryReader(File.OpenRead("c:\myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()

using System.IO;

// Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();

// Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();

// Write out to binary file
string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

.