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
Hosting WCF Service in IIS and Configuration may be needed
This article is an attempt to depict steps may needed to configure IIS for hosting WCF application. An important thing that should be considered is that all user do not face following situations. First of all I try to create a simple WCF application and then I try to publish this simple WCF simple application.
In order to create a WCF application we just need to know ABC of WCF application which are Address, Binding and Contract. (You can download code from here)
First of all I created a blank solution with Visual Studio 2008 by clicking File > New > Project and selecting Other Project Types > Visual Studio Solutions > Blank Solution
I created solution named AccountSolution. I added new project named Accounting by right clicking on AccountingSolution and selecting Add > New project menu. In the next step I added reference of System.ServiceModel to project references.
I changed name of class1.cs to IAccount.cs and I added new class named AccountService.cs. Here is code for IAccount and AccountService:
IAccount.cs
using System;
using System.Text;
using System.ServiceModel;
namespace Accounting
{
[ServiceContract]
public interface IAccount
{
[OperationContract]
int GetBalance(int accountNumber);
}
}
AccountService.cs
using System;
using System.Text;
using System.ServiceModel;
namespace Accounting
{
public class AccountService : IAccount
{
#region IAccount Members
public int GetBalance(int accountNumber)
{
Random rnd = new Random(1000000);
return Convert.ToInt32(rnd.Next());
}
#endregion
}
}
I added new web site named WCFServiceAccount and added new project reference of Accounting. Since I added project reference to Accounting project, cs under App_Data folder is no longer needed. So let delete two cs file under App_Data.

I changed Service.svc source to:
<%@ ServiceHost Language="C#" Debug="true" Service="Accounting.AccountService"%>
Setting Service and end points:
In order to setService and end points I used WCF Configuration option by right-clicking on web.config.
Tip: Sometimes "Edit WCF Configuration" does not appear in right-click menu. Once open "WCF Service Configuration" from tools menu and close it, this cause menu appear next time in right click menu.
I set first service name to Accounting.AccountService by browsing Accounting.dll in bin directory.

And I set first end point contract attribute to Accounting.IAccount and delete second end point.

And at last save the WCF configuration and build solution. Before running web site let set WCFServiceAccount as startup project and set Service.svc as start page. Our web site is ready to be executed. After successful execution let host our website to local IIS. Simply website could be hosted by publishing web site to local IIS. If IIS is installed before visual studio 2008 you may not face with any following errors and simply you can jump next step.
I tried to publish WCFServiceAccount by right clicking on Web site project and selecting "…" then Local IIS but I’ve got following errors. (My windows was Vista Ultimate)
To Access local IIS Web sites, you must install the following IIS component.
- IIS 6 Metabase and IIS 6 Configuration Compatibility
- ASP.NET
- Windows Authentication

Configuring IIS to publish a web site (Specially WCF web site):
To rectify mentioned errors I’ve found a document in Technet for installing IIS6 Metabase and IIS 6 Configuration
To install the IIS 6.0 Management Compatibility Components by using the Windows Vista Control Panel
- Click Start, click Control Panel, click Programs and Features, and then click Turn Windows features on or off.
- Open Internet Information Services.
- Open Web Management Tools.
- Open IIS 6.0 Management Compatibility.
- Select the check boxes for IIS 6 Metabase and IIS 6 configuration compatibility and IIS 6 Management Console.
- Click OK.
Pasted from <http://technet.microsoft.com/en-us/library/bb397374.aspx>
Following image shows how to install "IIS6 Metabase and IIS 6 Configuration ". Surprisingly you can set other option such as Installing ASP.NET and Windows Authentication.

Alternatively, For installing ASP.NET you can use visual studio command prompt and running aspnet_regiis with -i parameter:
aspnet_regiis -i
Publishing WCFServiceAccount to local IIS:
- Right click on WCFServiceAccount select publish from menu
- Select local IIS option
- Select create new application icon
- Type web application (e.g. WCFServiceAccount)
- Now open a browser to test your application "http://localhost/WCFServiceAccount/Service.svc"
- Then select Open button
If you get following error:
Server Error in ‘/WCFServiceAccount’ Application.Configuration ErrorDescription: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.Parser Error Message: Unrecognized configuration section system.serviceModel. Source Error:
Source File: C:\inetpub\wwwroot\WCFServiceAccount\web.config Line: 103 Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 |
OR
|
Server Error in Application "Default Web Site/WCFServiceAccount" HTTP Error 404.3 – Not Found Description: The page you are requesting cannot be served because of the Multipurpose Internet Mail Extensions (MIME) map policy that is configured on the Web server. The page you requested has a file name extension that is not recognized, and is not allowed. Error Code: 0×80070032 Notification: ExecuteRequestHandler Module: StaticFileModule Requested URL: http://localhost:80/WCFServiceAccount/Service.svc Physical Path: E:\Projects\Learning\Blog\WCFServiceAcount\Service.svc Logon User: Anonymous Logon Method: Anonymous Handler: StaticFile Most likely causes:
What you can try:
More Information…This error occurs when the file extension of the requested URL is for a MIME type that is not configured on the server. You can add a MIME type for the file extension for files that are not dynamic scripting pages, database, or configuration files. Process those file types using a handler. You should not allows direct downloads of dynamic scripting pages, database or configuration files.
|
You should register service model according to following steps:
-
Run a Visual studio Command prompt
-
Enter "cd c:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\" And press enter
- Run "servicemodelreg -i"
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


_1372.png?psid=1)