Joseph Michael Pesch
VP Programming

ASP.Net WCF Data Services Error Hosting on Multiple Environments

by 25. September 2011 16:25

I encountered an error when attempting to access a WCF Data Service from my hosted web site.  This error did not occur when running the service on my local development PC.  This is the error I received: "This collection already contains an address with scheme http.  There can be at most one address pr scheme in this collection. Parameter name: item"  To resolve this error my web.config required and additional entry to provide the host name as shown here.

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
        <add prefix="" />



Deploying SSAS Cube from Development to Test/Production

by 23. September 2011 08:47

The easiest way to deploy the cube is to generate a create database script from within SQL Management Studio.  When generating a database script of an Analysis Server database the resulting script file will be XMLA rather than SQL script (as when generating a normal SQL database script).  The resulting XMLA file will contain a DataSources section that contains connection information about the relational database (e.g. datawarehouse database) that the SSAS cube will be reading it's data from.  Below is an example of that section where I have put in variable placeholders to replace the original values of the following items:

  • $(DWServer) - Target database server where the relational data exists.
  • $(DWDatabase) - Target database where the relational data exists.
  • $(DwReaderAccount) - User account name that has read access to the relation database.
  • $(DwReaderPassword) - Password of the reader account.

Here is a sample section of the XMLA file with the above indicated replacements:

  <DataSource xsi:type="RelationalDataSource">
    <ConnectionString>Data Source=$(ImpacDWServer);Initial Catalog=$(ImpacDWDatabase);Integrated Security=True</ConnectionString>
        <ID>DataSourcePermission 1</ID>
        <Name>DataSourcePermission 1</Name>
        <RoleID>Role 1</RoleID>

In order to run the XMLA file through command line (rather than directly in SQL Management Studio) you will need the ASCMD.EXE utility from Microsoft.  You can download it from the SQL Server Analysis Samples page on (below are links to the SQL 2005 and 2008 pages).

SQL 2005

SQL 2008



SQL Script to Generate Table Inserts

by 23. September 2011 07:46

This script will accept a database name and comma delimited list of table names.  It will generate insert statements for all the records in the desired tables.  I will be adapting the script to include schema as well as table name.  The original script was provided by:

CREATE Procedure [dbo].[sp_CreateDataLoadScript]
@databaseName	varchar(128) ,
@TblNames varchar(max)
as begin

	set nocount on;

	create table #a (id int identity (1,1), ColType int, ColName varchar(128))
	create table #out (lnr int, statements varchar(max))
	declare @sql nvarchar(4000)
	declare @TblName as varchar(128)
	declare @idx as bigint
	declare @previdx as bigint
	declare @last as bit
	declare @hasIdentity as bit
	declare @lnr as int

	set @lnr=0

	set @idx=charindex(',',@TblNames)
	set @previdx=1

	if @idx>0 begin  /* many tables */
		set @TblName=ltrim(rtrim(substring(@TblNames,@previdx,@idx-@previdx)))
		set @previdx=@idx+1
		set @last=0
	else begin /* 1 table */
		set @TblName=ltrim(rtrim(@TblNames))
		set @last=1

	while len(@TblName)>0 begin

		select @sql = 'select case when DATA_TYPE like ''%char%'' or DATA_TYPE like ''%date%'' or DATA_TYPE like ''uniqueidentifier'' then 1 else 0 end , COLUMN_NAME
			from 	information_schema.columns
			where 	TABLE_NAME = ''' + @TblName + '''

		select 	@sql = 'exec ' +  @databaseName + '.dbo.sp_executesql N''' + replace(@sql, '''', '''''') + ''''
		insert 	#a (ColType, ColName)
		exec (@sql)

		select @hasIdentity=max(cast(clmns.is_identity as int))
		from sys.tables AS tbl
		INNER JOIN sys.all_columns AS clmns ON  clmns.object_id = tbl.object_id
		where = @TblName

		declare	@id int ,
		@maxid int ,
		@cmd1 varchar(7000) ,
		@cmd2 varchar(7000)

		insert into #out select @lnr, '/* ' + @TblName + ' */'
		set @lnr = @lnr+1
		insert into #out select @lnr, 'truncate table ' + @TblName
		set @lnr = @lnr+1

		if @hasIdentity=1 begin
			insert into #out select @lnr, 'set identity_insert ' + @TblName + ' ON'
			set @lnr = @lnr+1
		select 	@id = 0 , @maxid = max(id)
		from 	#a

		select	@cmd1 = 'insert into #out select ' + cast(@lnr as varchar) + ', '' insert ' + @TblName + ' ( '
		select	@cmd2 = ' + '' select '' + '
		while @id < @maxid
			select @id = min(id) from #a where id > @id

			select 	@cmd1 = @cmd1 + '[' + ColName + '],'
			from	#a
			where	id = @id

			select @cmd2 = 	@cmd2
					+ ' case when [' + ColName + '] is null '
					+	' then ''null'' '
					+	' else '
					+	  case when ColType = 1 then  ''''''''' + replace(convert(varchar(max),[' + ColName + ']),'''''''','''''''''''') + ''''''''' else 'convert(varchar(50),[' + ColName + '])' end
					+ ' end + '','' + '
			from	#a
			where	id = @id

		select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
		select @cmd2 = left(@cmd2,len(@cmd2)-8) + ' from ' + @databaseName + '.dbo.' + @tblName

		exec (@cmd1 + @cmd2)
		truncate table #a

		if @hasIdentity=1 begin
			insert into #out select @lnr, 'set identity_insert ' + @TblName + ' OFF'
			set @lnr = @lnr+1

		insert into #out select @lnr, 'go'
		set @lnr = @lnr+1

		-- next table
		set @idx=charindex(',',@TblNames,@previdx)
		if @idx>0 begin  /* more tables */
			set @TblName=ltrim(rtrim(substring(@TblNames,@previdx,@idx-@previdx)))
			set @previdx=@idx+1
		else if @last=0 begin /* one more */
			set @TblName=ltrim(rtrim(substring(@TblNames,@previdx,8000)))
			set @last=1
		else  /* done */
			set @TblName=''

	drop table #a

	print 'use ' + @databaseName
	print 'go'
	print 'set nocount on'

	declare @statement varchar(max)
	declare @o int
	declare c_out cursor  LOCAL FAST_FORWARD for select statements from #out order by lnr
	open c_out

	declare @i int
	set @i=0
	fetch next from c_out into @statement

	while @@fetch_status=0 begin
		set @i=@i+1
		if @i=1000 begin
			print 'go'
			set @i=0

		print @statement

		fetch next from c_out into @statement

	close c_out
	deallocate c_out
	drop table #out


SQL Server

Sample jQuery - Reading oData Using XML and JSON

by 21. September 2011 13:50

Below are some sample jQuery script methods that illustrate reading data from an oData service.  One uses XML, while the other uses JSON.  The attached zip file contains the full source code, including the AdventureWorks sample database and the C# WCF Data Service that binds to it.  NOTE: That the jQuery JSON call will fail if the web site is compiled under .Net 3.5 framework; however, it will work correctly if compiled under the .Net 4.0 framework.  I saw some other posts indicating that this was a known issue in 3.5 where the JSON was not valid (the jQuery JSON call then errors out claiming the JSON is not valid).

ODataWeb.zipx (603.57 kb)

$.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) {

$(document).ready(function () {

function TestAjax() {
  // setup sample url to find all product descriptions that contain the word "alloy"
  var url = "http://localhost:4241/adventureworks_wcfdataservice.svc/ProductDescriptions?$filter=indexof(Description, 'alloy') ne -1";
  $('#TestAjaxLink').click(function () {
      url: url,
      beforeSend: function (xhr) {
        xhr.overrideMimeType('text/plain; charset=x-user-defined');
      success: function (data) {
        var xml = $.parseXML(data);
        $(xml).find('entry').each(function () {
          var propXml = $(this).find('content').find('m\\:properties');
          var line = '
' + (propXml.find('d\\:ProductDescriptionID').text()) + ': ' + (propXml.find('d\\:Description').text()) + '
' $('#TestAjaxData').append(line); }); } }); }); } function TestJSON() { // setup sample url to find all product descriptions that contain the word "alloy" var url = "http://localhost:4241/adventureworks_wcfdataservice.svc/ProductDescriptions?$filter=indexof(Description, 'alloy') ne -1"; $('#TestJsonLink').click(function () { $.getJSON(url, function (results) { $.each(results.d, function (i, item) { var line = '
' + item.ProductDescriptionID + ': ' + item.Description + '
' $('#TestJsonData').append(line); }); }); }); }



C# Code to Get AD Members of a Security Group

by 15. September 2011 09:57

This method will accept a domain name and security group name and return all the AD members of that group.

using System.Collections.Generic;
using System.DirectoryServices;

namespace AdReader
  class Program
    static void Main(string[] args)
      List users = GetGroupMembers("", "security group name");
      foreach (DirectoryEntry user in users)
        System.Diagnostics.Debug.WriteLine(user.Name.Replace("CN=", ""));
    /// Gets a list of members in the specified group.        
    public static List GetGroupMembers(string domain, string groupName)
      List users = new List();
      string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "group", groupName); // principal);            
      string[] properties = new string[] { "fullname" };
      DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
      DirectorySearcher searcher = new DirectorySearcher(adRoot);
      searcher.SearchScope = SearchScope.Subtree;
      searcher.ReferralChasing = ReferralChasingOption.All;
      searcher.Filter = filter;
      SearchResult result = searcher.FindOne();
      if (result != null)
        DirectoryEntry directoryEntry = result.GetDirectoryEntry();
        foreach (object dn in directoryEntry.Properties["member"])
          DirectoryEntry member = new DirectoryEntry("LDAP://" + dn);
          //Add users from other groups within this group (only go 1 level deep).      
          if (!IsGroup(member))
      return users;
    /// Determine whether the object is a group.        
    private static bool IsGroup(DirectoryEntry de)
      return de.Properties["objectClass"][1].ToString() == "group";



C# Code to Extract Binary Data from SQL and Save to Disk File

by 14. September 2011 14:24

This code will allow a simple SQL connection to select a single record with binary data in image column and save it as a file on the local disk.

string SQL = "select [FileData] from [MyTable] where [RecordID] = 1";
string cnString = @"Data Source=Server\Instance,Port;Initial Catalog=DB;Integrated Security=True;";
SqlConnection cn = new SqlConnection(cnString);
SqlCommand cmd = new SqlCommand(SQL, cn);
byte[] byt = (byte[])cmd.ExecuteScalar();
FileStream fs = new FileStream(@"c:\temp\tempfile.txt"
  , FileMode.CreateNew, FileAccess.Write);
fs.Write(byt, 0, byt.Length);





Microsoft SSAS OLAP Error: A duplicate attribute key has been found when processing table column value

by 9. September 2011 21:28

Here is the specific error I encountered:

"Errors in the OLAP storage engine: A duplicate attribute key has been found when processing: Table: 'MyTableHere', Column: 'MyColumnHere', Value: '0'. The attribute is 'MyAttributeHere'."

At first I was very confused because I didn't understand how having multiple values of 0 was an issue. It turns out the real issue is having both 0 values AND null values. The issue is manifest by the processing engine as it performs a select distinct which results in one row for the 0 values and another for the null values. However, the null value is then converted into a 0 by default (if you have the "NullProcessing" attribute of the Dimension set to "Automatic").  This is what causes the conflict.  In my case making the nulls 0 before processing the cube resolved the issue.

NOTE: With the default NULL processing for dimension attributes being set to 'Automatic' nulls will be converted to a Zero (for numerical values) or an empty string (for string values). The issue is that the engine first performs a "select distinct ..." on the raw values, so it will come up with one row for NULL and another row for ZERO/BLANK (depending on data type), then the conversion from NULL to the corresponding default occurs thus resulting in conflicting (or duplicate) keys.

Thanks to this post for helping me out:



MDX CellSetGrid Source Code - Browse SSAS Cube

by 2. September 2011 08:38

This is a C# .Net framework 2.0 based custom web control that allows dynamic navigation of SSAS cube through a standard Asp.Net web page using the Microsoft.AnalysisServices.AdomdClient for data access.  To use it in Visual Studio, create a new solution and include the attached CellsetGrid project.  Then add a new file based web site and reference the CellsetGrid project from the web site.  Then drag the "CellSetGrid2" custom control onto the web page and set the ConnectionString and Cube properties.  ConnectionString will need at a minimum "Data Source=ServerName\InstanceName;Catalog=DatabaseName;".  Below is a screen shot of the control in action.