A way to run nearly all functions of dotNet from SQL Server

Last night, I got a case to write a function in SQL Server 2005 to support the user account and password check against Active Directory. The user requirement is quite clear:

  • Create a scalar-valued function named LDAPUserCheck;
  • Parameter @username nvarchar(MAX) for user name to check;
  • Parameter @password nvarchar(MAX) for password matching the username specified;
  • Return bit 1 if succeeded, or 0 for all other reasons.

After a digging, I found that LDAP password authentication is not supported directly by SQL Server. But SQLCLR is a way to build the native dotnet program into SQL Server. In a new created SQLCLR project in VS 2005, I realized it’s unable to add the reference System.DirectoryServices.AccountManagement, which is required by running the code for Active Directory authentication. But a Web Service is a choice.

My steps to achieve that:

1 Create and deploy a Web Service for the authentication check.

1.1 Create a Web Service project.

1.2 Add System.DirectoryServices.AccountManagement as a reference.

1.3 Add a setting DomainName as string for storing the domain name.

1.4 Add a service like this:

    public class LDAPAuthentication : System.Web.Services.WebService
    {
        static string domainName = Settings.Default.DomainName;

        [WebMethod]
        public bool Check(string userName, string password)
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName))
            {
                // validate the credentials
                bool isValid = pc.ValidateCredentials(userName, password);
                return isValid;
            }
        }
    }

1.5 Deploy this service and use a application pool running by a domain user. This user should be added to IIS_WPG group in Windows Server 2003.

2 Create a SQLCLR project to call the Web Service.

2.1 Create a SQLCLR project in Visual Studio 2005.

2.2 Add a Web Service reference. It’s named as LDAP in my project.

2.3 Add a User Defined Functions.

    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlBoolean LDAPUserCheck(
        SqlString username, SqlString password)
    {
        using (LDAPAuthentication.LDAP.LDAPAuthentication service = new LDAPAuthentication.LDAP.LDAPAuthentication())
        {
            if (service.Check(username.ToString(), password.ToString()))
            {
                return SqlBoolean.True;
            }
            else
            {
                return SqlBoolean.False;
            }
        }
    }

2.4 Set Permission Level to External in Database page of project setting.

2.5 Build this project to get the dll files. In my case, these files are named LDAPAuthentication.dll and LDAPAuthentication.XmlSerializers.dll.

3 Deploy this project into SQL Server 2005.

3.1 Enable the CLR support in SQL Server 2005 by running this code:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO

sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO

sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO

3.2 Create a database for storing this function. Or, you can use any existed database as well. In my case, I created a database “tester”.

3.3 Set trustworthy on this database by running:

ALTER DATABASE [tester] SET trustworthy ON

3.4 Copy the 2 dll files created in step 2 to this server. In my case, these are stored in C:\SQLCLR folder.

3.5 Create assemblies in SQL Server by running:

create assembly [LDAPAuthentication] from 'C:\SQLCLR\LDAPAuthentication.dll' with permission_set = external_access
create assembly [LDAPAuthentication.XmlSerializers] from 'C:\SQLCLR\LDAPAuthentication.XmlSerializers.dll' with permission_set = external_access

3.6 Create function to run the method we’ve created in VS 2005:

CREATE FUNCTION [dbo].[LDAPUserCheck](@username [nvarchar](4000), @password [nvarchar](4000))
RETURNS [bit] WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [LDAPAuthentication].[UserDefinedFunctions].[LDAPUserCheck]

Now everything is done. You can call this function like all others created by SQL. Run this for test.

select dbo.LDAPUserCheck('myusername','mypassword')

 

Solved: Why Linq Where.FirstOrDefault is faster than use FirstOrDefault with condition on an array?

Hi all.

 

Why applying “.Where(condition).FirstOrDefault()” is much faster than “.FirstOrDefault(condition) when it’s applied on an array?

 

Answer: While calling method Where() on an Array or a List, it’s optimized to use the enumerator of the source directly. But FirstOrDefault(), which doesn’t have this mechanism, runs the virtual method version from IEnumerator.GetEnumerator().

Special thanks to Iris Sakura.

Official feedback about removing orphan collection in TFS 2013

Continued from: Remove orphan collection item without related database in TFS 2013 with Update 2

 

It’s announced that this will be fixed in Update 3 of TFS by Microsoft Officially.

https://connect.microsoft.com/VisualStudio/feedback/details/874523/delete-a-collection-without-related-database-connected-vs2013u2

 

A workaround, editing database directly, is provided also.

http://social.msdn.microsoft.com/Forums/en-US/cceec4ba-1712-4905-9e7b-8669bf81880f/damaged-project-collection-on-tfs-2013-no-solution-to-delete-it-from-server?forum=tfsadmin

But you should keep in mind that editing database directly is dangerous and will lose all supports from Microsoft.

Remove orphan collection item without related database in TFS 2013 with Update 2

Last week, the Configuration Manager in our company tested to create a collection in Team Foundation Server (TFS for short) 2013 with Update 2. After test, the database of this collection is deleted directly from SqlServer by mistake and there is no backup for it. So an orphan item for this collection is still existed there and have to be removed manually.

 

First, I try to remove it from Team Foundation Server Administration Console (TfsMgmt.exe). It failed in detach process.

Then, I try to do it with TFSconfig.exe in console mode. I’m pretty sure that’s work in previous version of TFS, maybe 2012. But in 2013 with Update 2, it failed the same as TfsMgmt.

I tried to use a database from another collection by renaming it as the deleted one, or even use a database created with another TFS instance with the same collection name, all failed.

At that time, I turned to MSDN forum. One MVP provided some tables within Tfs_Configuration database. Some deleting operations should be taken there. After that, the collection is removed from the TfsMgmt but it still can be found in Visual Studio at client side.

Finally, I detached all collections and redeployed the whole TFS instance. That works as predictable.

 

If somebody falls into the same jam, the detachment and redeployment is the only way to correct it, unless you have the backup of that deleted database.

 

Related: http://social.msdn.microsoft.com/Forums/vstudio/en-US/3a072d51-298a-48b5-a57e-301f5ef2670f/how-to-delete-a-collection-without-related-database-connected-tfs-2013-update-2?forum=tfsgeneral

Visual Studio 2013 Update 1 is not compatible with Windows 8.1 with Update (MSDN CD) while using sysprep

While the new installation CD named Windows 8.1 with Update launched for MSDN subscriptions user, I downloaded it and try to upgrade all the images from the Windows Deployment Service in my company. But I found the new version of Windows 8.1 might have some problem with Visual Studio 2013 Update 1.

 

Coz I need to upgrade some related images in batch, this is my way:

Create a VM and install Windows 8.1 (x64 enterprise version with update, downloaded from MSDN subscriptions site);

  1. Install Office 2013 with Service Pack 1 (VL version, coz there is a KMS in our company);
  2. Update to the latest patches;
  3. Run Cleanmgr to minimal the system;
  4. Create a snapshot named Office 2013;
  5. Use Sysprep to boot into the audit mode;
  6. Remove the current user;
  7. Use Sysprep to boot into the OOBE mode with Generalize checked;
  8. Use WDS to capture this status and upload, named as Office 2013. Before capturing, I deleted the pagefile, swap file and the contents within temp folder.

It works great.

Then,

  1. Reverse to snapshot Office 2013;
  2. Install Visual Studio 2013 with Blend, Office Developer Tools, SQL Server Data Tools, Web Developer Tools, Silverlight Development Kit; (No C++, nor mobile things)
  3. Install Update 1 from iso;
  4. Install Visual Studio SDK;
  5. Update to the latest patches;
  6. Run Cleanmgr to minimal the system;
  7. Create a snapshot named Visual Studio;
  8. Use Sysprep to boot into the audit mode;
  9. Remove the current user;
  10. Use Sysprep to boot into the OOBE mode with Generalize checked;
  11. Use WDS to capture this status and upload, named as Visual Studio. Before capturing, I deleted the pagefile, swap file and the contents within temp folder.

It looks familiar right? Actually, it WON’T WORK.

After deploy from this Visual Studio and create a new user, system end with this text:

The User Profile Service service failed the sign-in.

User profile cannot be loaded.

Even when trying to boot from the template VM in current status, it failed in the same way.

But if I try to install Team Explorer from Team Foundation Server with Update 2 CD instead, or using the Office 2013 image created above, it works like a charm. Even just use the old Windows 8.1 CD instead of the new one, it still works great.

I’ve check by using reg in command line. There is nothing wrong like this KB mentioned: http://support.microsoft.com/kb/947215.

I have no clue about this but just leave a message here for avoiding others go into the same jam.

 

 

Update: It fixed in VS 2013 with Update 2.

Install dotNet framework 3.5 on Win8 / WinSvr2012

We know that from Windows Vista, the original optical media is useless after you finish system installation. Enabling a role of feature do not require that media any more.

But in Windows 8 / Windows Server 2012, for some reason we don’t know, the situation is changed a little. The setup package of dotNet framework 3.5 is not pre-copied to your hard drive. It will have to be downloaded from Microsoft while enabling that feature.

If you hate this, luckily, that setup package is on installation media also. We just need to tell the system to use that instead of downloading.

You may want to run this as administrator:

DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:d:\sources\sxs

where:

  • /Online targets the operating system you’re running (instead of an offline Windows image).
  • /Enable-Feature /FeatureName:NetFx3 specifies that you want to enable the .NET Framework 3.5.
  • /All enables all parent features of the .NET Framework 3.5.
  • /LimitAccess prevents DISM from contacting Windows Update.
  • /Source specifies the location of the files needed to restore the feature (in this example, the D:\sources\sxs directory).

Source: http://msdn.microsoft.com/en-us/library/hh506443.aspx

C#: Convert a tree node and sub nodes to text

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TreeToText
{
    class TreeToText
    {
        const string LineMid = "├─";
        const string LineLast = "└─";
        const string Line = "│  ";
        const string Space = "    ";

        /// <summary>
        /// Convert a tree node to text
        /// </summary>
        /// <param name="node">Root node to convert</param>
        /// <returns>Text</returns>
        public static string Tree2Text(TreeNode node)
        {
            if (node == null) return null;
            StringBuilder builder = new StringBuilder();
            builder.AppendLine(TreeNodeText(node));
            Tree2Text(builder, node, "");
            return builder.ToString();
        }

        static string TreeNodeText(TreeNode node)
        {
            return node.Text;
        }

        static void Tree2Text(StringBuilder builder, TreeNode parent, string prefix)
        {
            int nodesCount = parent.Nodes.Count;
            if (nodesCount == 0) return;
            int nodeMaxIndex = nodesCount - 1;
            for (int i = 0; i < nodesCount; i++)
            {
                builder.Append(prefix);
                TreeNode node = parent.Nodes[i];
                if (i != nodeMaxIndex)
                {
                    builder.Append(LineMid);
                    builder.AppendLine(TreeNodeText(node));
                    Tree2Text(builder, node, prefix + Line);
                }
                else
                {
                    builder.Append(LineLast);
                    builder.AppendLine(TreeNodeText(node));
                    Tree2Text(builder, node, prefix + Space);
                }
            }
        }
    }
}