Keep up blogging

It’s about 3-4 months I didn’t blog so much. It was because of some deterrent elements such as my grandmother, work pressures and more.

Fortunately, those stuffs finished probably and from now on, I’ll try to keep blogging up again.

Lots of bugs fixed on SQL Server 2008

After SQL Server 2008 RTM released, most of database developers started working with it because of its outstanding features. But unfortunately it had lots of bugs.

Recently, Microsoft released Cumulative update package 1 for SQL Server 2008 that contains a lot of HotFixes for Microsoft SQL Server 2008 RTM and it’s available for download.

As Microsoft said, these hotfixes applies to:

  • Microsoft SQL Server 2008 Analysis Services
  • Microsoft SQL Server 2008 Developer
  • Microsoft SQL Server 2008 Enterprise
  • Microsoft SQL Server 2008 Express
  • Microsoft SQL Server 2008 Express with Advanced Services
  • Microsoft SQL Server 2008 Reporting Services
  • Microsoft SQL Server 2008 Standard
  • Microsoft SQL Server 2008 Standard Edition for Small Business
  • Microsoft SQL Server 2008 Web
  • Microsoft SQL Server 2008 Workgroup

For more details, you can checkout Cumulative update package 1 for SQL Server 2008

Visual Basic 2010 new features

Channel 9 Logo - Photo taken from: http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.pngWorking with new technology is always interesting. Since Visual Studio 2010 and .NET Framework 4 have been announced, most of developers who are developing with Visual Basic start searching about Visual Basic 10 new features.

About a month ago, Lucian Wischik and Lisa Feigenbaum described about new features in Visual Basic 2010. The show is available for download at MSDN Channel 9 website.

You can check it out by click here.

This is my recommendation: View it!

How to implement SQL LIKE keyword in LINQ to SQL

It’s about a year that .NET framework 3.5 has been released. Most of companies are still using SqlConnection, SqlCommand, SqlDataAdaptor, etc. in order to manager their data connections. About 5 month ago I started posting articles about LINQ to SQL and ways you can use in order to use LINQ as a very powerful data source.

In this post I’m going to show how you can implement SQL “LIKE” keyword in LINQ to SQL.

As you may know, SQL Server has 3 kind of LIKE keywords (%LIKE, %LIKE% and LIKE%). For each of these types, you have to use of specific LINQ to SQL:

LIKE%:

LIKE% selects all rows that start with an expression, for example:

SELECT Title, LoginID FROM HumanResources.Employee 
WHERE Title LIKE N'Acc%'

Here is the return value:

SQL result after using LIKE keyword

In order to implement such a thing in LINQ to SQL you have to use the StartsWith() method like following:

private void ImplementStartsWith()
        {
            AWDataContext db = new AWDataContext();
            var i = from item in db.Employees
                    where item.Title.StartsWith("Acc")
                    select new {Title = item.Title, UserName = item.LoginID };
            dataGridView1.DataSource = i;
        }

%LIKE:

%LIKE selects all rows that end with an expression. For example, I want to have all managers so I select titles that end with “Manager”. EndsWith() method will help you out for this:

private void ImplementEndsWith()
        {
            AWDataContext db = new AWDataContext();
            var i = from item in db.Employees
                    where item.Title.EndsWith("Manager")
                    select new { Title = item.Title, UserName = item.LoginID };
            dataGridView1.DataSource = i;
        }

%LIKE%:

This like is the most useful like type that is using for searches. If you want to have all rows that contain an expression, you must use Contains() method:

private void ImplementContains()
{
        AWDataContext db = new AWDataContext();
        var i = from item in db.Employees
                where item.Title.EndsWith("Specialist")
                select new { Title = item.Title, UserName = item.LoginID };
        dataGridView1.DataSource = i;
}

How to create a tab control using ASP.NET and JavaScript

It may happen to any ASP.NET Developer that the customers want to have a Tab Control in their websites. There are many ASP.NET components such as Telerik RAD Controls, ComponentArt, DevExpress, etc. which can help you out in this but sometimes they are expensive for your project capacity.

In this post, I’m going to show you how you can create a very simple Tab Control using ASP.NET and JavaScript.

You can do lots of thing in order to create a Tab Control but what I’m going to do is to create a class that is inherited from System.Web.UI.WebControl:

    public class TabControl : System.Web.UI.WebControls.WebControl
    {
    }

You can make your Tab Control flexible by adding some properties to it. For example, enable your developers to set CssClass to a TabItem:

 

private string _MainCssClass;
private string _ItemCssClass;
private string _InActiveCssClass;
private string _ActiveCssClass; 
private Unit _ItemWidth = 70;
private HorizontalAlign _HorizontalAlign = HorizontalAlign.NotSet;
private string _LinkCssClass;

They’re OK; but the interesting part is to use of a string array in order to store TabItem names:

private string[] _TabNames = { "Item1", "Item2" };

This is also a property, so developers can add their own items. Another important property is a list of Panels of those TabItems. Actually, Panels are the content of each TabName:

private List<Panel> _Panels = new List<Panel>();

In the field above, developers can add their specified panels for each TabItem. The most important method in creating custom web controls is the Render() method which enable you to design your control using HTML tags. Here is my Render() method:

 

protected override void Render(System.Web.UI.HtmlTextWriter w)
{
    if (_Panels.Count == 0 || _Panels == null)
        throw new NullReferenceException("Please specify at least one panel.");
 
    w.WriteLine("<!-- Developed by Mohammad Mahdi Ramezanpour. © 2008 Marlik. -->");
    w.WriteLine(String.Format(@"<table cellpadding=""0"" cellspacing=""0""
    class=""{0}""><tr id=""MarlikTabControl"">", _MainCssClass));
    foreach (Panel p in this.Panels)
    {
        cols.Add("Tab_" + _itemIndex);
        w.WriteLine(String.Format(@"<td onmouseover=""javascript:this.style.cursor='hand';""
        class=""{0} {3}"" align=""{5}"" id=""Tab_{4}"" 
        onclick=""ShowTabContent('{1}', 'Tab_{4}');"" width=""{2}"">",
         _ItemCssClass, p.ClientID, this._ItemWidth, this._InActiveCssClass, 
         this._itemIndex, this._HorizontalAlign.ToString()));
        w.WriteLine(String.Format(@"<a class=""{1} {2}"">{0}</a>",
        _TabNames[_itemIndex], _LinkCssClass,  _ItemCssClass));
        _itemIndex++;
        w.WriteEndTag("td");
    }
    w.Write("</tr></table>");
    w.WriteLine(JavaFunctions().ToString());
    base.Render(w);
}

How it works?

In the first I checked for available panels and if there was no panels so an exception will be throwing using NullReferenceException.

As you know, there is a writer parameter as System.Web.UI.HtmlTextWriter in Render() method that enable you to generate HTML codes in your web component. You have to use that if you want to use HTML or any client-side code in your web control. Add I did above is to create a HTML <table></table> tag but rows and columns will be generating dynamically using HtmlTextWriter.

You can download the full code here: TabControl

SQL Server 2008 MERGE Statement

It was about two months I was working on SQL Server 2008 (My main profession) and it’s new features. One of the most interesting features of SQL Server 2008 is the MERGE statement and today I’m going to explain what is it and how it works?

Microsoft teased us with the possibility in prerelease Beta versions of SQL Server 2005, but it yanked the MERGE statement out of T-SQL right before the SQL Server 2005 RTM was released. SQL Server 2008 fixes this situation by finally giving us a fully functional MERGE statement. The MERGE statement is a combination statement that can perform INSERT, UPDATE, and DELETE statements based on whether rows that match the selection criteria exist in the target table or not.

Because it is so flexible, the MERGE statement syntax is a bit more complex than other Data Manipulation Language (DML) statements. It definitely takes some getting used to.

 

CREATE TABLE #TempShifts
(
Name varchar(50) NOT NULL,
StartTime time NOT NULL,
EndTime time NOT NULL
);
 
INSERT INTO #TempShifts
(
Name,
StartTime,
EndTime
)
VALUES
(
'Morning Part-time',
'08:00:00',
'12:00:00'
),
(
'Evening Part-time ',
'18:00:00',
'22:00:00'
),
(
'Midnight Swing Shift',
'00:00:00',
'04:00:00'
);
 
MERGE HumanResources.Shift AS target
USING #TempShifts AS source
ON (target.Name = source.Name)
OR (target.StartTime = source.StartTime
AND target.EndTime = source.EndTime)
WHEN MATCHED THEN
UPDATE
SET
Name = source.Name,
StartTime = source.StartTime,
EndTime = source.EndTime
WHEN TARGET NOT MATCHED THEN
INSERT
(
Name,
StartTime,
EndTime
)
VALUES
(
source.Name,
source.StartTime,
source.EndTime
);
 
SELECT ShiftID,
Name,
StartTime,
EndTime,
ModifiedDate
FROM HumanResources.Shift;
 
DROP TABLE #TempShifts;

The MERGE sample begins by creating a temporary table into which you insert names and start and end times for three different work shifts. If you check that out, you’ll notice that one of the new shifts, Evening Part-time, already exists with a start time of 18:00:00 and an end time of 22:00:00. Another shift, Midnight Part-time, exists for the hours between 00:00:00 and 04:00:00. The Morning Part-time shift does not exist at all.

The interesting part of the code sample is the actual MERGE statement itself. This statement begins with the MERGE keyword and the target table. Notice that the table name is aliased, which will make it easier to reference later in the ON clause.

MERGE HumanResources.Shift AS target

The USING clause specifies the data rows to match against the target table. In this case, I’m matching the rows I created in the #TempShifts table against the target HumanResources.Shift table. The USING clause is very important to get right, since the rows returned by this clause determine the actions taken later in the MERGE statement. In this case, I’m simply using the

#TempShifts table as the source, but you can also use a derived table.

USING #TempShifts AS source

The ON clause determines which rows between the target table and the USING clause data rows are matches. This example uses a compound predicate that flags any two rows as matches when they both have either the same Name or the same StartTime and EndTime.

ON (target.Name = source.Name)

OR (target.StartTime = source.StartTime

AND target.EndTime = source.EndTime)

The WHEN MATCHED clause performs its action whenever two rows match based on your ON clause criteria. The action is specified in the THEN clause, and can be either an UPDATE or a DELETE. This example is using the UPDATE clause, which looks like an abbreviated UPDATE statement. Notice that the UPDATE clause does not specify a target table, since the target table is

already specified in the MERGE clause at the beginning of the statement.

WHEN MATCHED THEN

UPDATE

SET Name = source.Name,

StartTime = source.StartTime,

EndTime = source.EndTime

The MERGE statement can have only one WHEN TARGET NOT MATCHED clause. This clause can only perform an INSERT when a row is found in the USING clause source that does not match a row in the target table.

WHEN TARGET NOT MATCHED THEN

INSERT

(

Name,

StartTime,

EndTime

)

VALUES

(

source.Name,

source.StartTime,

source.EndTime

);

How to copy a folder with all of its subfolders and files using Microsoft .NET Framework

It was about 1 month I didn’t post any blog because of my situation. I was bloody busy with 2 of my projects. Yesterday I passed one of them so I have more free time. Today I want to keep my blogs up with a new blog post about how you can copy a folder with all of its subfolders and files using .NET Framework.

I used Microsoft Visual Basic 2008 for this post. You can convert to C# using offline/online tools. I recommend DeveloperFusion Convertor.

We have 2 main sections:

  1. Copy Files.
  2. Copy folders.

Copy Files:

For each of our folders, we need to copy its files. So we need to write a method that copies all files contains in a folder. I use “CopyFiles” as a name for my method:

Private Sub CopyFiles(ByVal sourcePath As String, ByVal desPath As String)
End Sub

As you can see, my method has two input parameters:

  1. SourcePath: which gives my method the path of a folder I want to copy files from.
  2. desPath: which tells my method where to copy files.

Because this method wants to work on a directory, I have to declare a new variable of System.IO.DirectoryInfo:

Dim d As New System.IO.DirectoryInfo(sourcePath)

DirectoryInfo requires a parameter which takes the path of your specific directory.

After that, I need to search for file with a For Each statement. DirectoryInfo has a method named GetFiles() that gives an array of System.IO.FileInfo:

For Each fi As System.IO.FileInfo In d.GetFiles()
Next

In my For Each statement, I used some checking such as file existence and more; but the only thing that’s important is to copy files:

For Each fi As System.IO.FileInfo In d.GetFiles()
            If Not System.IO.File.Exists(System.IO.Path.Combine(d.FullName, fi.Name)) Then
                System.IO.File.Copy(d.FullName & "\" & fi.Name, desPath & "\" & fi.Name)
            Else
                System.IO.File.Delete(desPath & "\" & fi.Name)
                System.IO.File.Copy(d.FullName & "\" & fi.Name, desPath & "\" & fi.Name)
            End If
 Next

OK, now you can copy files but, what about folders? What about files in folders?

Copy Folders:

Public Sub CopyFolders(ByVal sourcePath As String, ByVal desPath As String)
    Dim d As New System.IO.DirectoryInfo(sourcePath)

Again, a new instance of System.IO.DirectoryInfo but we want to search for folders this time:

For Each di As System.IO.DirectoryInfo In d.GetDirectories()
Next

As you can see, I used GetDirectory() method this time because it will gives us an array of System.IO.DirectoryInfo of our main folder. Again some checking and the important part is the use of System.IO.Directory.CreateDirectory() method which makes a new directory for us:

For Each di As System.IO.DirectoryInfo In d.GetDirectories()
            If Not System.IO.Directory.Exists(desPath & "\" & di.Name) Then
                System.IO.Directory.CreateDirectory(desPath & "\" & di.Name)
            Else
                System.IO.Directory.Delete(desPath & "\" & di.Name, True)
                System.IO.Directory.CreateDirectory(desPath & "\" & di.Name)
            End If
            CopyFiles(di.FullName, desPath & "\" & di.Name)
            If di.GetDirectories().Length > 0 Then
                CopyFolders(di.FullName, desPath & "\" & di.Name)
            End If
Next

Pay attention that we want to look folders up recursively. So I called my “CopyFolders” method again in it. Another important section is that, I called “CopyFiles” method. It means, for each Folder, copy all of its files.

Download full source code based on WPF here: Click Here