VB.NET and C# Comparison
Software Development October 21st, 2008
Sometimes we need a simple VB.NET & C# side by side comparison. This sheet doesn’t include all features, but its great place to start with.
Sometimes we need a simple VB.NET & C# side by side comparison. This sheet doesn’t include all features, but its great place to start with.
Microsoft announce the public release of a new developer tool - Source Analysis for C#.
Inside Microsoft this tool’s name is StyleCop and it enforces code style guidelines on the code we write
Source Analysis comes with a set of default rules analyzers covering approximately 200 best practice rules. These rules are full compatible with the default layout settings in Visual Studio 2005 and Visual Studio 2008.
Specifically, these rules cover the following, in no particular order:
After installation, Source Analysis can be run from within the Visual Studio IDE. You can set this up to be run as a part of your build process as documented here. Since this is plugged in as a MsBuild project you can use it in as a part of Team Foundation Build process as well.
Running Source Analysis:
And the results are:
Download it from: http://code.msdn.microsoft.com/sourceanalysis
Read full details:http://blogs.msdn.com/sourceanalysis/archive/2008/05/23/announcing-the-release-of-microsoft-source-analysis.aspx
Tags: C#, Code Analysis, Coding Standards, MSBuild, Team System, Team System 2008, Visual Studio 2008, Visual Studio Team System
Microsoft released a nice training kit (~126MB) (it’s a real treasure!) for the latest technologies.
This package covers a bunch of technologies and includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies
including:
Download here.
Tags: .NET, .NET 3.0, .NET 3.5, C#, Visual Studio Team System
Many applications include code that looks like:
1: string sqlStmt = "SELECT * FROM USERS WHERE UserName= '" + un + "' AND Password='" + pwd + "'";
Admit it…it’s ugly, but you constructed SQL statements like this one.
The variables un,pwd are provided by the user. The problem with this SQL string is that the attacker can piggyback SQL statements in one of them.
What if the attacker enters this:
un = maor, pwd = 123456′ OR 1=1. The following malicious statement is built:
1: string sqlStmt = "SELECT * FROM USERS WHERE UserName= 'maor' AND Password='123456' OR 1=1";
The statement will return all columns for all rows…Bad!
And what if the attacker enters this:
un=maor , pwd = 123456′ DROP TABLE Users. The following malicious statement is built:
1: string sqlStmt = "SELECT * FROM USERS WHERE UserName= 'maor' AND Password='123456' DROP TABLE Users";
This builds SQL statement that queries for a user and then drops the users table.
What can you do prevent these attacks?
1. Quoting the input
Quoting the input is not a remedy, but its often proposed to solve the problem.
if we use the statement of:
1: string pwd;
2: pwd = pwd.Replace("'","''");
The code replaces single quotes with 2 single quotes in the input. The single quote is escaped and its render to invalid SQL statement. However its not perfect. If the statement has a integer field the attacker can use it to attack.
2. Use stored procedures
Many of us probably believe that the application is immune to SQL injection if we use stored procedures. WRONG!
When we enter the 123456′ OR 1=1 to a parameter the sp will fail cause we cannot perform join across a stored procedure call. However, performing data manipulation is valid.
1: exec sp_getUser 'maor','123456' INSERT INTO Users Values('123','123')
This command will fetch data about the user and then insert a new row into the users table! What we can do? secure the stored procedure. How?
3. Never connect as sysadmin
If you see that your web application connects to the database as sysadmin account – its a BUG. Most of the web applications don’t need the capabilities of a sysadmin to run; If there is a bug in the SQL statements and the application connects as sysadmin account, the attacker can: delete any database or table in the server; delete any table data; change data; alter tables; deletes log; and more… The potential damage is unlimited.
4. Build secure SQL statements
Instead of dynamically building a string, as shown in the bad examples above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
1: // 1. declare command object with parameter
2: SqlCommand cmd = new SqlCommand(
3: "SELECT * FROM USERS WHERE UserName= @UN AND Password= @PWD", conn);
4:
5: // 2. define parameters used in command object
6: SqlParameter param1 = new SqlParameter();
7: param1.ParameterName = "@UN";
8: param1.Value = userName;
9:
10: SqlParameter param2 = new SqlParameter();
11: param2.ParameterName = "@PWD";
12: param2.Value = password;
13:
14:
15: // 3. add new parameter to command object
16: cmd.Parameters.Add(param1);
17: cmd.Parameters.Add(param2);
Summary
Code secure!!!!
Tags: .NET, C#, Security, SQL Injection
C# 3.0 has many-a-new features. This post will explain the ’var’ keywork and the concept of Implicitly Typed Variables.
The var keyword is not a late-bound or un-typed variable reference. The var keyword always generates a strongly typed variable reference. The main idea is that the developer is not required to define the type of the variable at the time of declaration, but it is the task of the compiler to decide what type of the object the variable is. The compiler infer the type of the variable from the expression used to initialize the variable when it is first declared.
Important points about var keyword:
What rules shuold you force to use the var keyword?
When you declare variable with the var keyword, you must to always do an initial value assignment. This is because the var keyword produces a strongly-typed variable declaration. Hence, the compiler needs to be able to infer the type to declare based on its usage. If you don’t, the compiler will produce a compiler error.
1: var vAge = 32;
2: var vHeight = 175.2;
3: var vName = “Maor David“;
The compiler will infer the type of the “age”, “height” and “name” variables based on the type of their initial assignment value. This means it will generate IL that is absolutely identical to the code below:
1: int age = 32;
2: double height = 175.2;
3: string name = "Maor David";
You can also use it to other data types:
1: foreach (var vTable in ds.Tables)
2: {
3: foreach (var vRow in ((DataTable) vTable).Rows)
4: {
5:
6: }
7: }
This is equal to:
1: foreach (DataTable table in ds.Tables)
2: {
3: foreach (DataRow vRow in table.Rows)
4: {
5: }
6: }
You can read this post also at Maor David’s Blog: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/15/C_2300_-3.0-var-keyword.aspx
Once you want edit a recore, add new or deleted a recored in your data grid you may want to save it in the database.
How do we do it?
Code example:
private void myDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string productName, productDescription;
// Gets the value of the key field of the row being updated
string key = myDataGrid.DataKeys[e.Item.ItemIndex].ToString();
// Gets get the value of the controls (textboxes) that the user
// updated.
// Each cell has a collection of controls. In this case, a TextBox control.
// The first column — Cells(0) — contains the Update and Cancel buttons.
TextBox tb;
// Gets the value the TextBox control in the third column
tb = (TextBox)(e.Item.Cells[2].Controls[0]);
productName = tb.Text;
// Gets the value the TextBox control in the fourth column
tb = (TextBox)(e.Item.Cells[3].Controls[0]);
productDescription = tb.Text;
// Finds the row in the dataset table that matches the
// one the user updated in the grid. This example uses a
// special Find method defined for the typed dataset, which
// returns a reference to the row.
dsProducts.CategoriesRow r;
r = dsProducts.Categories.FindByProductID(int.Parse(key));
// Updates the dataset table.
r.ProductName = productName;
r.ProductDescription = productDescription;
// Calls a SQL statement to update the database from the dataset
sqlDataAdapter1.Update(dsProducts);
// Takes the DataGrid row out of editing mode
myDataGrid.EditItemIndex = -1;
// Refreshes the grid
myDataGrid.DataBind();
}
For more information about DataSet updates, navigate to: http://msdn2.microsoft.com/en-US/library/y2ad8t9c(VS.71).aspx
I asked too much by .NET developers about attributes and their meaning. I hope that this post will help you to understand it better.
Introduction: what are attributes?
An attribute is a powerful .NET language feature that is attached to a target programming element (e.g., a class, method, assembly, interface, etc.) to customize behaviors or extract organizational information of the target at design, compile, or runtime. It is a clean approach to associate metadata with program elements and later use the metadata at design, compile or run time to accomplish some common objectives. Attributes come in two flavors: intrinsic and custom. Intrinsic attributes are supplied as part of the Common Language Runtime (CLR), and they are integrated into .NET. Custom attributes are attributes you create for your own purposes. As a thumb-rule, a class is said to be an attribute class, if it directly or indirectly derives from the System.Attribute class.
Why we need attributes?
For example, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used. ; Attributes are also used extensively in securing .NET assemblies, forcing calling code to be evaluated against pre-defined security constraints. ; DllImportAttribute that allows a program to communicate with the Win32 libraries; and more…
Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
Using attributes
Attributes are placed before the item that they will be "decorating" and they are put inside square braces [].
To understand the power of attributes, consider the serialization of an object. In .NET, you just need to mark a class Serializable to make its member variables as Serializable. Serializable attribute: (type of SerializableAttribute)
12
[Serializable()]public class CustomerData
I didnt use the SerializableAttribute class when applying the attribute to the class. The only time that you can leave off the Attribute portion of the name is when you are applying the Attribute to a class.
123456789101112 |
public class MyClass{ [Obsolete("This method replaced by CalcEx method.", true)] static int Calc(int a, int b ) { }
static int CalcEx (int a, int b ) { }
public static void Main( ) { int res = Calc(1,2); }}
|
I used the attribute Obsolete, which marks a method (in this case) that should not be used. The first parameter is the string, which explains why the item is obsolete and what to use instead. In fact, you can write any other text here. The second parameter tells the compiler to treat the use of the item as an error. The default value is false, which means the compiler generates a warning for this.
When we try to compile this program, we will get an error with the message: MyClass.Calc is obsolete: 'This method replaced by CalcEx method.'
Custom attributes
When do you define your custom attributes? query at runtime! For example, let's create CryAttribute class:
12345678910111213141516 |
public class CryAttribute : Attribute{ private string m_reason; public string Reason { get { {return m_reason;} } }
public CryAttribute( string reason) { m_reason = reason; }}
|
Now, Let's use this attribute:
123456789 |
[Cry("Because babies cry..:)")] // normal babies cry without reasonpublic class Baby{}
[Cry("The baby is hungry")] // The baby cry because he wants to eatpublic class HungryBaby : Baby{}
|
It's great…but what can we do with it?? .NET gives us a new point of the view: runtime attributes querying.
How can we query?
123456789 |
public string WhyTheBabyCry(Baby baby){ Type type = baby.GetType();
object obj = type.GetCustomAttributes()[0];// the first attribute if(obj is CryAttribute) return ((CryAttribute)obj).Reason; else// other attribute return "First attribute is not Cry!";}
|
Now we can use it:
123456 |
Baby Baby1 = new Baby();Baby Baby2 = new HungryBaby();
string reason1,reason2;reason1 = WhyTheBabyCry(Baby1);// receives "Because babies cry..:)"reason2 = WhyTheBabyCry(Baby2);// "The baby is hungry"
|
More about attributes you can find at msdn.
I frequently asked what is the difference between Interface and Abstract classes. The main difficulty is the choice of whether to design your functionality as an interface or an abstract class.
Interface
An interface is a reference type containing only abstract members. These can be events, indexers, methods or properties, but only the member declarations. A class implementing an interface must provide the implementation of the interface members. An interface cannot contain constants, constructors, data fields, destructors, static members or other interfaces. Interface member declarations are implicitly public.
An interface declaration may declare zero or more members.
All interface members implicitly have public access. It is a compile-time error for interface member declarations to include any modifiers. In particular, it is a compile-time error for an interface member to include any of the following modifiers: abstract, public, protected, internal, private, virtual, override, or static.
Abstract class
Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.
The abstract modifier is used to indicate that a class is incomplete and that it is intended to be used only as a base class. An abstract class differs from a non-abstract class is the following ways:
An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class. While it is possible to have variables and values whose compile-time types are abstract, such variables and values will necessarily either be null or contain references to instances of non-abstract classes derived from the abstract types.
An abstract class is permitted (but not required) to contain abstract members.
An abstract class cannot be sealed.
When a non-abstract class is derived from an abstract class, the non-abstract class must include actual implementations of all inherited abstract members
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
List of similarities and differences between an interface and an abstract class: