Archive for the ‘Blog’ Category
Value type property and C# compilation error
Two days ago a question was asked in StackOverflow.com and I found this question so good to prepare a post. I want to explain this question:
Petr asked: I do not understand why there is Control.padding.all which is int and according to hint there is set as well as get but I cannot set it (Control.Padding.All=5)? I would be grateful for explanation.
For example when you want to set
textBox1.Padding.All = 5;
You will get this compiling error: Cannot modify the return value of ‘System.Windows.Forms.TextBoxBase.Padding’ because it is not a variable

Following example is an implementation of this error:
public class ARAControl
{
public ARAPadding Padding { get; set; }
}
public struct ARAPadding
{
public int All { get; set; }
}
If you use this you’ll get mentioned error:
ARAControl control = new ARAControl(); control.Padding.All = 10;
And why this compiling error happens. It hapens because structure is a value type. By setting this property you first call get Method. “Property Get” will return a copy of ARAPadding, so it is a value type and C# will detect out mistake and prevent compiling.
Screen size in WPF applications
I was about to write a simple application deal with screen size in WPF. Previously in windows form applications we could get WorkingArea parameters from System.Windows.Forms.WorkingArea but in WPF application typically we don’t have this assembly (however this assembly could be added to project). In WPF applications screen size could be obtained from System.Windows.SystemParameters. Following code is an example of setting a form right-bottom aligned in screen.
Windows form application:
this.Top = Screen.PrimaryScreen.WorkingArea.Height - this.Height; this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
WPF application:
this.Top = System.Windows.SystemParameters.WorkArea.Height - this.Height; this.Left = System.Windows.SystemParameters.WorkArea.Width - this.Width;
P.S. 2009/11/30: A friend of mine just asked “Is it possible to get all screen size (in multiple screen) in WPF without refering to System.Windows.Forms”. As far as I see, It seems it is not possible to get other screens than current workarea unless you Use System.Windows.Forms.
LINQ-To-SQL Uses magic ROW_NUMBER() function
Recently I founded that LINQ-To-SQL Uses magic ROW_NUMBER() function. ROW_NUMBER() function is a magic function which was added in SQL Server 2005. Microsoft put this function in version 2005 so that developers will not take it for granted and appreciate it. ROW_NUMBER "returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition".
ROW_NUMBER() Syntax:
ROW_NUMBER ( ) OVER ( [ ] <order_by_clause> )
For example following query add a number field which is partitioned by ProductID (reset on new ProductID) in descending order on UnitPrice * OrderQty.
SELECT ROW_NUMBER() OVER (Partition by ProductID ORDER BY UnitPrice * OrderQty DESC) AS ROWNUM,* FROM Sales.SalesOrderDetail
ROW_NUMBER() helps programmer to select specified amount of rows within a select command. This feature commonly used in paging. Following example returns @P1th to @P2th rows which list is ordered by ProductId.
SELECT * FROM SELECT *, ROW_NUMBER() OVER (ORDER BY ProductID) AS ROWNUMBER FROM Sales.SalesOrderDetail) AS ALLDATA WHERE ALLDATA.ROWNUMBER BETWEEN @P1 and @P2
Skip() and Take()LINQ-To-SQL functions generate ROW_NUMBER syntax in query result. I created a LINQ-TO-SQL dbml file on AdventureWorks. I selected SalesOrderDetail as Data Class.
AdventureWorksDataContext advDC = new AdventureWorksDataContext();
IQueryable orderDetails = advDC.SalesOrderDetails.OrderBy(f => f.SalesOrderDetailID)
.Skip(20).Take(10);
foreach (SalesOrderDetail orderDetail in orderDetails)
Console.WriteLine(orderDetail.ProductID);
Console.ReadLine();
Above code generates following SQL for orderDetails:
{SELECT [t1].[SalesOrderID], [t1].[SalesOrderDetailID], [t1].[CarrierTrackingNumber], [t1].[OrderQty],
[t1].[ProductID], [t1].[SpecialOfferID], [t1].[UnitPrice], [t1].[UnitPriceDiscount],
[t1].[LineTotal], [t1].[rowguid], [t1].[ModifiedDate]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[SalesOrderDetailID]) AS [ROW_NUMBER],
[t0].[SalesOrderID], [t0].[SalesOrderDetailID], [t0].[CarrierTrackingNumber],
[t0].[OrderQty], [t0].[ProductID], [t0].[SpecialOfferID], [t0].[UnitPrice],
[t0].[UnitPriceDiscount], [t0].[LineTotal], [t0].[rowguid], [t0].[ModifiedDate]
FROM [Sales].[SalesOrderDetail] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
}
As you see, Skip and Take functions interpreted as ROW_NUMBER() function.
Migrating to BlogEngine.net
Finally, I’ve decided to convert my weblog engine from Graffiti CMS to BlogEngine. Moving to BlogEngine doesn’t mean weakness of Graffiti blogging engine or indicating any problem. But after surveying BlogEngine and comparing to current version of Graffity CMS I’ve found lots of features more sophisticated than Graffiti and in my opinion blogEngine is handier. Although you can full features here but in my opinion following features are cool and convincing to migrate:
- Easy installation
- Cool widgets
- Advanced comment system (Supporting Nested reply)
- Cool themes (more themes are available on web)
- Supporting ping service
- Static pages
Code contracts (Part 2): Creating my first project with code contracts
I downloaded code contracts from here. After installing code contract, I tried to create my first project with code contracts. I created new console project name CodeContractTest . I added reference to Microsoft.Contracts library which is appeared in .Net references after installation.
I wrote following code this is clearly compiled without any warning.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using System.Diagnostics;
namespace CodeContractTest
{
class Program
{
static void Main(string[] args)
{
Swap(new string[] { "Code", "Contract" }, 1, 4);
}
static void Swap(string[] arr, int item1, int item2)
{
string temp;
temp = arr[item1];
arr[item1] = arr[item2];
arr[item2] = temp;
}
}
}
However, after running this application we will encounter with IndexOutOfRangeException. This is occurred because illegal parameter in Swap method call.
Let take a look at new feature added to Visual Studio 2008. I open properties window of project. New tab is added named "Code Contracts". I checked "Perform Static Contract Checking" and "Implicit Array Bound Obligations". If I rebuild project new warnings and message will be appeared in Error window.

Four warnings are about Array access and four suggestion message plus one summary message.

In order to improve code and get rid of warnings I should add preconditions in swap method. I added four line of precondition which assure item1 , item2 is in array boundary. I used Contract class and Requires static method which is used for preconditions it has two overloads first overload has a bool parameter. We can use this method to explicitly define the conditions of input parameters.
static void Swap(string[] arr, int item1, int item2)
{
Contract.Requires(item1 < arr.Length);
Contract.Requires(item1 >= 0);
Contract.Requires(item2 < arr.Length);
Contract.Requires(item2 >= 0);
string temp;
temp = arr[item1];
arr[item1] = arr[item2];
arr[item2] = temp;
}
After rebuilding project new warning is appeared. It shows that one of contract precondition rules is broken.

If I change the swap with proper input parameters after rebuilding project warning messages will be disappeared.
Swap(new string[] { "Code", "Contract" }, 0, 1);
If I check "Implicit Non-Null Obligation" on code contracts tab of property window building application will be face with new warning "contracts: Possible use of a null array ‘arr’"

Swap method should be called with non-null array parameter. This is another contract that should be added to preconditions. So I changed Swap method as follow.
static void Swap(string[] arr, int item1, int item2)
{
Contract.Requires(arr != null);
Contract.Requires(item1 < arr.Length);
Contract.Requires(item1 >= 0);
Contract.Requires(item2 < arr.Length);
Contract.Requires(item2 >= 0);
string temp;
temp = arr[item1];
arr[item1] = arr[item2];
arr[item2] = temp;
}
In this case developer of Swap method define contract for input parameters and there is no need to swap caller know all swap code in order to prevent bad parameter calling.
You can download code from here
Visual Studio trick: Adding namespace
A few days ago I saw a clip of PDC 2008 about MVC .Net which is great concept. It was performed by Phil Haack. In this video Phil shows a trick of Visual studio which is very useful.
Most of the time during application development you want use a class which its name space has not been included. Guess what should you do? Oh yes ! You should type name space completely or leave current line and go to top of class adding appropriate "using" statement get back to your line of code. Surprisingly there is a trick in visual studio 2008 (I tested in visual studio 2008). If reference of class included in project you can Type class name completely at the same time a tooltip bar will be appeared under your class name. At the same time press Ctrl+. (dot). A menu will be appeared which offers you two options. First option will add using statement at the top of code class file. Second option will insert full class name including name space.

Axum
Axum has been released in Microsoft DevLabs
What is Axum:
Axum is a language that builds upon the architecture of the Web and principles of isolation, actors, and message-passing to increase application safety, responsiveness, scalability, and developer productivity.
Axum aims to validate a safe and productive parallel programming model for .NET.
you can find more inforamtion about Axum here
And here is Axum blog
Code contracts (Part 1): Introduction

During developing applications we have always use unwritten rule in programming or if it is written in design documents user should consider them in development. For example if developer wants to call a method which has an integer parameter and this parameter is used as an index of array he should be aware calling that method with negative value or greater than array lenght. Calling method with negative value causes runtime error.
There are lots of contracts that a developer should consider during development. Recently I came across new concept (However it is in research phase) named CodeContracts which is really wonderful. It seems that this concept will be in VS 2010. CodeContracts will organized all written and unwritten rules & contract in development. In order to clarify CodeContract usage imagine following code:
static void Swap(string[] arr, int itemIndex1, int itemIndex2)
{
string temp;
temp = arr[itemIndex1];
arr[itemIndex1] = arr[itemIndex2];
arr[itemIndex2] = temp;
}
What are possible errors when we want to call Swap method?
- None of itemIndex1 and itemIndex2 could be negative (both should be positive)
- None of itemIndex1 and itemIndex2 could be greater than arr.length
- Array arr should be not null
Before code contracts developer should always consider possible situation and avoid breaking rule. But CodeContracts provides rich methods by which you can add your Code Contracts to your method and after compiling application Contracts checker will warn about breaking rules. Let see how it should be implemented with CodeContracts
static void Swap(string[] arr, int itemIndex1, int itemIndex2)
{
Contract.Requires(arr != null);
Contract.Requires(itemIndex1 >= 0);
Contract.Requires(itemIndex1 < arr.Length);
Contract.Requires(itemIndex2 >= 0);
Contract.Requires(itemIndex2 < arr.Length);
string temp;
temp = arr[itemIndex1];
arr[itemIndex1] = arr[itemIndex2];
arr[itemIndex2] = temp;
}
I added five contracts to this method which mean this method needs not null array as first parameter, second and third parameter (itemIndex1, itemIndex2) should be greater or equal to zero and should be less than array length.
In the next post I will show how to implement this with CodeContracts
But now I want to introduce some resources:
Simple theme for Graffiti CMS
Graffiti CMS express edition is popular amid developers as well as Community Server. At the moment I wanted to decide between Graffiti And Community Server I couldn’t made my mind. Blog subsystem of community server has a simple theme which is similar to MSDN blog theme (Like current theme). This theme was inducement of community server. Finally, I used graffiti because of simplicity, anyway , Recently I decided to convert simple theme of community server 2008 to graffiti CMS theme.
I put first version of simple theme here
Where are the Northwind and Pubs?
SQL Server 2005 is installed without any samples – at least versions I installed don’t contain Northwind and pubs databases -. However Microsoft put SQL Server 2005 Samples and Sample Databases in Codeplex, light version of these two sample databases were always famous in a way that you can find one of them in most database related samples with high probability. You can find SQL Server 2000 Sample here. After installation file is downloaded take following two steps:
1. Install msi file. Some files will be copied in C:\SQL Server 2000 Sample Databases
2. Attach Northwind.mdf file which is located in C:\SQL Server 2000 Sample Databases. Repeat this step for pubs mdf file.


_1372.png?psid=1)