Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Category list

Value type property and C# compilation error

by Ahmadreza Atighechi 28. November 2009 21:48

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.

 

Tags:

Blog

LINQ-To-SQL Uses magic ROW_NUMBER() function

by Ahmadreza Atighechi 5. August 2009 23:39

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 ( [ <partition_by_clause> ] <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.

kick it on DotNetKicks.com

Tags: ,

Blog

Migrating to BlogEngine.net

by Ahmadreza Atighechi 24. June 2009 16:12

 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

 

 

Tags:

Blog

Code contracts (Part 2): Creating my first project with code contracts

by Ahmadreza Atighechi 22. May 2009 04:35

 

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

 

kick it on DotNetKicks.com

 

Tags:

Blog

Visual Studio trick: Adding namespace

by Ahmadreza Atighechi 20. May 2009 05:17

 

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.

 

 

kick it on DotNetKicks.com

Tags:

Blog

Axum

by Ahmadreza Atighechi 13. May 2009 01:06

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

Tags:

Blog

Code contracts (Part 1): Introduction

by Ahmadreza Atighechi 5. May 2009 12:13

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:

 


kick it on DotNetKicks.com

Tags:

Blog

Simple theme for Graffiti CMS

by Ahmadreza Atighechi 24. April 2009 04:38

Simple Theme

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

 

Tags:

Blog

Where are the Northwind and Pubs?

by Ahmadreza Atighechi 15. April 2009 10:44

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.

Tags:

Blog

How to change mouse cursor icon in windows mobile application

by Ahmadreza Atighechi 6. April 2009 12:28

 

Informing user about application state is one of important aspects in user experience. In windows applications mouse icon indicates one of great application states. When an application is busy mouse icon should be changed to wait cursor mode or hourglass icon. In windows application you can achieve this by changing Cursor property of any Control, Usually by changing "this.Cursor" which "this" is current form in application. See example:

 

this.Cursor = Cursors.WaitCursor;

 

Since control class in compact framework does not have Cursor property, not only developer could not change every control cursor icon but also he could not change form cursor property. So what should developer do in order to indicate application state?

There is a static class in System.Windows.Forms named Cursor and it has a property named "Current" which developer should set it to an appropriate cursor based on application state.

 

 

System.Windows.Forms.Cursor = Cursors.WaitCursor;

Or

System.Windows.Forms.Cursor = Cursors.Default;

 

Tags: ,

Blog

The information on this web site is provided "AS IS" with no warranties, and confers no rights.

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen