Tuesday, May 31, 2011

Renaming Excel Sheets Exported from Reporting Services 2005 via an Excel Add-In


Intro

When a Reporting Services 2005 report with multiple pages is exported to excel to creates an excel document with multiple sheets where the first sheet is an index sheet or document map and the remaining sheets are report pages. Reporting Services 2005 gives these sheets generic names Sheetxy. Unlike the situation with Reporting Services 2008 [R2] there's no straight forward way of telling Reporting Services 2005 how name the report pages. One way to rename this sheets in excel to match the entries in the document map (which are more meaningful than sheetXY) is through an excel add-in. Below is an Excel add-in written in VB to rename sheets based on the document map. The code is tested on Windows XP/7 with Office 2003 Professional/Basic. If you decide to use the code below, make sure it has no unwanted side-effects in your environment and make sure you test it.

The basic idea of the code is:


  • Each document map entry points to a named range (which is stored in the built-in array Names
  • Using the range name we can find out the sheet that's being pointed to by an entry in the document map
  • Once the sheet is found, its name is changed to that of the hyperlink's DisplayText property of the pointing document map entry.

Steps to Create Excel Add-In using VBA

  1. Open a new excel workbook and go to the Visual Basic Editor
  2. In the left pane, right-click on VBAProjects (Book1) and Insert -> module. This module will have the code that will rename the sheets. The code in this module will be called when the custom menu item is clicked.
  3. This code does the renaming (you can paste in the newly created module
    Private Const INVALID_CHARS As String = "[]*/\?:"
    Private Const SHEET_NAME_MAX_LENGTH As Integer = 31
    Private Const DOCMAP_SHEET_NAME As String = "document map"
    Private Const DOCMAP_SHEET_NEW_NAME As String = "__INDEX__"
    Public Sub RunRenameSheetsCode()
        If Not Application.ActiveWorkbook Is Nothing Then
            Call RenameSheets(Application.ActiveWorkbook)
        End If
    End Sub
    Public Sub RenameSheets(ByRef wb As Workbook)
        On Error GoTo Error
        Dim sh As Worksheet
        Dim row As Integer
        Dim cell As Range
        Dim newName As String
        row = 1
        If Not IsFirstSheetDocMap(wb) Then
            Exit Sub
        End If
        Do While True
            Set cell = wb.Sheets(1).Range("$A$" & CStr(row))
            If Len(cell.Value) <= 0 Then
                Exit Do
            End If
            If cell.Hyperlinks.Count > 0 Then
                Set sh = GetSheetByRangeName(wb, cell.Hyperlinks(1).SubAddress)
                If Not sh Is Nothing Then
                    newName = CleanSheetName(cell.Value)
                    sh.name = newName
                End If
            End If
            row = row + 1
        Loop
        wb.Worksheets(1).name = DOCMAP_SHEET_NEW_NAME
        Exit Sub
    Error:
         MsgBox ("An error occurred while trying to rename sheets")
    End Sub
    Public Function CleanSheetName(ByVal name As String)
        Dim newName As String
        newName = name
        For i = 1 To Len(INVALID_CHARS)
           newName = Replace(newName, Mid(INVALID_CHARS, i, 1), "")
        Next
        newName = Left(newName, SHEET_NAME_MAX_LENGTH)
        CleanSheetName = newName
    End Function
    Public Function GetSheetByRangeName(ByRef wb As Workbook, rangeName As String) As Worksheet
        Dim i As Integer
        Dim sheetName As String
        Dim charIndex As Integer
        For i = 1 To wb.Names.Count
        If wb.Names(i).name = rangeName Then
            sheetName = wb.Names(i).RefersTo
            charIndex = InStr(1, sheetName, "!")
            If charIndex > 0 Then
                sheetName = Left(sheetName, charIndex - 1)
                sheetName = Right(sheetName, Len(sheetName) - 1)
                Exit For
            End If
        End If
        Next
        charIndex = InStr(1, sheetName, "'")
        If charIndex > 0 Then
            sheetName = Right(Left(sheetName, Len(sheetName) - 1), Len(sheetName) - 2)
        End If
        If Len(sheetName) > 0 Then
            Set GetSheetByRangeName = wb.Sheets(sheetName)
        End If
    End Function
    Public Function IsFirstSheetDocMap(ByRef wb As Workbook) As Boolean
        If wb.Worksheets.Count > 0 Then
            If LCase(wb.Worksheets(1).name) = DOCMAP_SHEET_NAME Then
                IsFirstSheetDocMap = True
                Exit Function
            End If
        End If
        IsFirstSheetDocMap = False
    End Function
    
    
      
  4. Go back to the left pane and expand VBAProjects and also expand Microsoft Excel Objects and double click the ThisWorkBook node . The ThisWorkBook will host the code responsible for creating the custom menu and hooking the OnAction event to the code responsible for renaming the sheets.
    Private Const MENU_CAPTION As String = "&Custom Menu"
    Private Const MENU_ITEM_CAPTION As String = "&Rename Sheets"
    Private Sub AddMenus()
    'ResetMenuBar
     On Error Resume Next
     Me.Application.CommandBars("Worksheet Menu Bar").Controls(MENU_CAPTION).Delete
     Dim mainMenu As CommandBar
     Dim customMenu As CommandBarControl
     Dim customMenuItem As CommandBarButton
     Dim helpMenuIndex As Integer
     Set mainMenu = Me.Application.CommandBars("Worksheet Menu Bar")
     helpMenuIndex = mainMenu.Controls("Help").Index
     Set customMenu = mainMenu.Controls.Add(Type:=msoControlPopup, Before:=helpMenuIndex)
     customMenu.Caption = MENU_CAPTION
     Set customMenuItem = customMenu.Controls.Add(Type:=msoControlButton)
     customMenuItem.Caption = MENU_ITEM_CAPTION
     customMenuItem.OnAction = "RunRenameSheetsCode"
    End Sub
    Private Sub ResetMenuBar()
        Application.CommandBars("Worksheet Menu Bar").Reset
    End Sub
    Private Sub Workbook_Open()
        Call AddMenus
    End Sub
    
  5. Save the current workbook as an excel add-in. From File menu select save as and in the save-as dialog in the "Save as type" list find and select Microsoft Office Excel Add-in (*.xla).
    By default excel saves new addins in the add-ins folder designated for the current user which is %USERPROFILE%\Application Data\Microsoft\AddIns. You can also place the add-in in C:\Program Files\Microsoft Office\OFFICE11\XLSTART causes excel to load your add-in when excel is started regardless of the user who started excel.
  6. Every time you start excel now you'll see your custom menu. If you the first sheet is name "document map" and the user clicks on the menu item which we created to rename sheets, the add-in will attempt renaming sheets based on what's in the document map.

Wednesday, May 4, 2011

Reporting Services Exception: Execution cannot be found

The rsExceutionNotFound Problem:

On an instance of SQL Server Reporting Services 2005 I noticed for a good while that the service is throwing rsExecutionNotFound exception and logging those as warnings to Windows application event log. A typical warning may look like


Event Type: Warning
Event Source: ASP.NET 2.0.50727.0
Event Category: Web Event
Event ID: 1309
Date:
Time:
User:
Computer: SERVERNAME
Description:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time:
Event time
Event ID: 5be391324153445f9e5e3ace93334c55
Event sequence: 38
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/1/Root/Reports-1-129490022321612580
    Trust level: RosettaMgr
    Application Virtual Path: /Reports
    Application Path: ...\Reporting Services\ReportManager\
    Machine name: SERVERNAME

Process information:
    Process ID:
    Process name: w3wp.exe
    Account name:

Exception information:
    Exception type: ReportServerException
    Exception message: Execution '<SESSION ID>' cannot be found (rsExecutionNotFound)

Request information:
    Request URL: http://SERVERNAME/Reports/Reserved.ReportViewerWebControl.axd?ReportSession=SessionID really long URL
    Request path: %21 {I guess these %numbers are supposed to substituted }
    User host address: %22
    User: %23
    Is authenticated: %24
    Authentication Type: %25
    Thread account name: %26

After some searching I found this blog entry http://blogs.msdn.com/b/jgalla/archive/2006/10/11/session-timeout-during-execution.aspx. But the problem described in the mentioned blog is different and the suggested solution does not work in the cases I am describing here. The problem here is not that the report execution takes too long that the reporting services session times out.

The Cause of the Exception:

After some tracking and playing around I can say with a very high degree of certainty that the cause of the problem is  Internet Explorer [8]'s way of saving URLs when a user bookmarks (adds to favorites) a report's reporting services' URL.


I noticed that the exception (rsExecutionNotFound) is always thrown and the warning is logged in Windows when the user requests a report via a click on a favorite's URL. Of course the exception won't be thrown if the user visits the bookmarked report before its Reporting Services session expires. But typically with bookmarks they're visited days after the sessions are deleted and will for sure causes an rsExecutionException to be thrown.

If you look at an Internet Explorer 8 favorites shortcut file (*.url) you'll see some addition information saved along side the base URL of the bookmarked page. I believe this additional information is saved because when the report is rendered in the browser the page typically contains many iframes so the IE save their URLs as well. And in this case the additional information includes the Reporting Services SessionID. So when the user clicks on the favorite report, IE does try to make requests with old Reporting Services SessionIDs.

Here's a snippet of *.url file


[DEFAULT]
BASEURL=http://SERVERNAME/Reports/Pages/Report.aspx?ItemPath=/some/report/here
[DOC_ctl140TouchSession0]
BASEURL=http://SERVERNAME/Reports/Reserved.ReportViewerWebControl.axd?ReportSession=SessionID really long URL {the same shown in event log}
ORIGURL=javascript:''
[DOC_ctl140_ctl00_ctl03_ctl01]
....


A Solution:


Luckily if the cause of the exception is what I described here the user does not see on their screens and the exception itself is nothing serious although it might be bothersome to see those warnings in the events log. So in reality it does not affect the user's experience.

If the cause of the exception is that fact that the report takes tremendously long time to run to the point its session on Reporting Services times out, then the above mentioned link offers an easy solution.

Friday, April 15, 2011

SharePoint: The List That is Referenced Here no Longer Exists

While updating list items in a SharePoint list using the SharePoint web service API and specifically through calling
UpdateListItems method you may get everything setup correctly (authentication, authorization, retrieving the list using GetListItems etc.) but when you attempt to update the list using the API your updates are not reflected in the list and when poking around the returned object from UpdateListItems you'll notice it contains the detailed error message "The list that is referenced here no longer exists."

If that's the case make sure you are referencing the correct subsite and not the main site when you create the web reference to Lists.asmx web service. Alternatively you could set the Url property programmetically.

Here is an example:

If your site URL is http://my_share_point_site, the list.asmx can be found at http://my_share_point_site/sites/main/_vti_bin/lists.asmx?WSDL and you could use that URL to reference the API and some things might work. When you attempt to update a list found under some sub_site, your updates will silently fail. You have to reference http://my_share_point_site/sites/main/sub_site/_vti_bin/lists.asmx?WSDL for updates to your.

Some code:

string fieldName = "SomeListFieldToUpdate";
 SPLists.Lists listService = new Lists();
 listService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
 listService.Url = "http://my_share_point_site/sites/main/sub_site/_vti_bin/lists.asmx?WSDL";
 /* setting Url not required except you referenced a different sub_site or the main site when 
 you created your web reference to Lists.asmx */
 XmlDocument batchDoc = new XmlDocument();
 XmlElement batchElement = batchDoc.CreateElement("Batch", "http://schemas.microsoft.com/sharepoint/soap/");
 batchElement.SetAttribute("OnError", "Continue");
 batchElement.SetAttribute("ListVersion", "21");
 batchElement.SetAttribute("ViewName", editListViewGUID);
 string xml = string.Format(@"        
   {0}        
   {2}
   ", ID, fieldName, fieldValue);
 batchElement.InnerXml = xml;
 var result = listService.UpdateListItems(listGUID, batchElement);
 int.TryParse(result.FirstChild.FirstChild.InnerText, out errorCode);
 return errorCode;

Tuesday, March 29, 2011

Equals vs IEquatable

IEquatable is not a replacement of Object.Equals. If your object implements IEquatable<T> it still HAS TO override Equals and GetHashCode http://blogs.msdn.com/b/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.aspx 


Here is how the MSDN docs puts it:
If you implement IEquatable<T>, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable<T>.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals method return consistent results. http://msdn.microsoft.com/en-us/library/ms131187.aspx 

Wednesday, December 29, 2010

A trip, book, random code and additional non-sense

On a 24 hr train trip from Halifax to Toronto I enjoyed some reading from Clean Code: A Handbook of Agile Software Craftsmanship most interesting chapter so far is Object and Data Structures.

Some random coding here

Integer partition:


void gen(int lead,int postfix,int number,int *arr,int index,int originalNumber){
if(postfix<1)
return;
do{
int i=index;
arr[i++] = number - postfix;
arr[i] = postfix;
int j = 0;
int sum =0;
for(j=0;j<=index+1;j++){
cout << arr[j] << " ";
sum += arr[j];
}
cout << endl;
counter++;
gen(lead,postfix-1,postfix,arr,index+1,originalNumber-1);
lead++;
postfix = originalNumber - lead;

}while(lead < originalNumber);
}


which I thought is an awful implementation so I stole a python implementation as below


## {{{ http://code.activestate.com/recipes/218332/ (r1)
import sys
def partitions(n):
# base case of recursion: zero is the sum of the empty list
if n == 0:
yield []
return

# modify partitions of n-1 to form partitions of n
for p in partitions(n-1):
yield [1] + p
if p and (len(p) < 2 or p[1] > p[0]):
## print ["DEBUG: "] +  p
yield [p[0] + 1] + p[1:]
## end of http://code.activestate.com/recipes/218332/ }}}
print "Enter a number (0 to quit): "
n = int(sys.stdin.readline())
while n>0:
counter = 0
for p in partitions(n):
print p
counter = counter + 1
print "There were " + str(counter) + " unqiue partitions"
print "Enter a number (0 to quit): "
n = int(sys.stdin.readline())


the equivalent C# implementation is


public static IEnumerable<List<int>> intpart(int n)
 {
   if (n < 0)
                yield return null;
            if (n == 0)
                yield return new List<int>();
            foreach (List<int> list in intpart(n - 1))
            {
                if (list == null) break;
                var temp = new List<int>();
                temp.Add(1);
                temp.AddRange(list);
                yield return temp;

                if (list.Count > 0 && (list.Count < 2 || list[1] > list[0]))
                {
                    var newList = new List<int>();
                    newList.Add(list[0] + 1);
                    newList.AddRange(list.GetRange(1, list.Count - 1));
                    yield return newList;
                }
            }
  }


and playing with python and generating permutations


def ListPermutations(prefix,original):
    if original == "":
        print prefix
    else:
        index = 0
        length  = len(original)
        while index < length:
            if index < length-1 and original[index]==original[index+1]:
                index = index + 1
                continue
            newprefix = prefix + original[index]
            neworiginal = original[0:index]+original[index+1:]
            index = index + 1
            ListPermutations(newprefix,neworiginal)
          
##
and now java


public static void generate(int []array){
        while(array[0]
        {
            int sum = 0;
            int n = array.length;
            int stopIndex = -1;          
            for(int i:array){
                sum+= i;
                stopIndex++;              
                if(sum>=n){
                    System.out.print( ((sum-n)>0?(sum-n):i) );                  
                    break;
                }
                System.out.print(i + " ");
            }
            sum = 0;
            counter++;
            System.out.println();                                  
            int startIndex = 1;          
            for(int i=stopIndex-1;i>=startIndex;i--)
            {
                if(array[i]
                {
                    array[i]++;
                    for(int j=i+1;j
                        array[j]=1;
                    generate(array);
                   
                }
            }
            array[0]++;
            for(int i=1;i
            {
                array[i]=1;
            }
        }
    }

as for the additional non-sense, seize your moment for you may not get a second chance and enjoy http://www.youtube.com/watch?v=g9hMLnmeNm4  awfully nice sound and words

Monday, December 27, 2010

DEBUG.exe no more

this is old stuff. debug.exe let you write assembly instructions in DOS and execute them. i was told it will no longer be on windows operating systems i think the 64 bit versions.

here is some code to print A-Z with spaces between.

a
MOV AH,02
MOV DL,41
CMP DL,5B
JE 0114
INT 21
MOV DH,DL
MOV DL,20
INT 21
MOV DL,DH
ADD DL,01
JMP 0104
RET

g
q

Wednesday, December 15, 2010

Add Page Breaks Conditionally

Sometimes after developing a report you may have a requirement to conditionally add a page break after or before each logical portion of the report. Some users may need to see all of the logical units in consecutive pages and some prefer to see each logical unit in its own page.

Here is a simple trick to conditionally add the page break. Two simple steps:


  • Put your data control(s) that you'd like to conditionally paginate within a list control.










  • Edit the Detail Group of the list control and set the Group Expression to a condition a statement that uses a parameter or some other flag to determine whether to group the list based on a variable or a constant. Here is an example: =Iif(Parameters!PageBreak.Value, Fields!ProductID.Value,"")
  • Make sure you check the "Add page break at end" in the Grouping and Sorting Properties dialog box of the enclosing list dialog; see screen shot below.



Hope this helps.