SSRS Export to PDF breaking the columns in larger reports


This is a wierd problem, one could face in SSRS. The export to PDF or Word, appears to break the columns in larger reports with 10 or more columns.

The main reason being the report size specifications.

You can check your report properties to find the report size specifications. Check the screenshot below:

Check the Width and Height properties of the dialog that pops up (Right-click on the Report -> Report Properties)

The Fix:

Find the width of your report tablix (in inches). This will be a good start. Do not worry about height now. Set the Width to the width property in the above dialog, from your calculation. This is indeed a trial and error process, until you get all the columns in one single page. You will also need to adjust the Margins accordingly.

This should solve the issue of columns being spilled over to the next page, while taking export to PDF or Word.

New Problem that can come up:

In the first page of the exported report, you see only one row in the tablix.

Fix:

Adjust the margins to a lower value, less that 0.5in. They can be real culprits in this case.

Hope this helps with your SSRS issue.

jQuery noConflict Tips


Some tips which i feel you need to know before using jQuery library:

1. You can use jQuery instead of $.

2. Predefined alias for jQuery: you can assign jQuery to any variable. With this you can load any versions of jQuery into your site.

<!– load jQuery 1.1.3 –>
<script type=”text/javascript” src=”http://code.jquery.com/jquery-1.1.3.js”></script>
<script type=”text/javascript” src=”jquery.dimensions.min.js”></script>

<!– revert global jQuery and $ variables and store jQuery in a new variable –>
<script type=”text/javascript”>
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!– load jQuery 1.3.2 –>
<script type=”text/javascript” src=”http://code.jquery.com/jquery-1.3.2.js”></script>

<!– revert global jQuery and $ variables and store jQuery in a new variable –>
<script type=”text/javascript”>
var jQuery_1_3_2 = $.noConflict(true);
</script>

3. To use the $ variable even when an alias is mentioned
 Syntax:  (function($){//$ Code goes here})(jQuery_1_3_2);

(function($) {
 $(‘<button>Use jQuery 1.1.3</button>’)
  .click(function() {
   alert(‘Top: ‘ + $(this).offset().top + ‘\n’ +
    ‘jQuery: ‘ + $.fn.jquery);
  })
  .appendTo(‘body’);
})(jQuery_1_1_3);

4. Always ensure that jQuery’s noConflict method is called above any other javascript libraries. Or else the noConflict will be of no use and gives errors.

5. Finally to check if jQuery is defined:

 if(typeof (jQuery) == “undefined”) {//jQuery undefined} else {//jQuery defined}

Basic WCF Tutorial for Beginners


I will be explaining a simple WCF service execution, using a sample project (collated from the MSDN Documentation). Lets create a Visual Studio Solution with two console application projects.
They are:
1. Service Part – Console Application
2. Client Part – Console Application
Let me take you through the Service Part:
1. Create a sample console application & Import the System. ServiceModel; & System.ServiceModel.Description; references.
2. Create an Interface with interface attribute as ServiceContract with a sample namespace for the service. This will be the Contract between the client &
the WCF service. The interface methods will have function attributes as OperationContract
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples&#8221;)] //Namespace of the cs file
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
3. Define the class Calculator inheriting the Interface & implementing the 4 functionalities.
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
4. In the main function of the Console Application, we implement the WCF service creation logic:
4.2  Create a service Host for the type as CalculatorService class & Uri as baseaddress
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
4.3  Enable metadata exchanges, using ServiceMetadataBehavior from the System.ServiceModel.Description
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb); //Add the behavior to the servicehost
4.4  Start (and then stop) the service
selfHost.Open();
4.5 Close the service once done
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
Full Code (Program.cs):
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples&#8221;)]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1 of the address configuration procedure: Create a URI to serve as the base address.
// Step 2 of the hosting procedure: Create ServiceHost.
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3 of the hosting procedure: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), “CalculatorService”);
// Step 4 of the hosting procedure: Enable metadata exchange.
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb);
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (Exception ex)
{
Console.WriteLine(“An exception occurred: {0}”, ex.Message);
selfHost.Abort();
}
}
}
}
With this the Service Part is done.You can run the Project to see the service Starting up. This normally takes time to load. Now we will create a client to listen to this service.
Let me take you through the ClientPart :(Console Application in the same solution as that of the service or you can create a new solution also)
1. Create a Console Application for the ClientPart, to listen to the Service & do some computation. Add the ServiceModel reference dll.
2. Goto Visual Studio Command Prompt. Go to the directory of your client console application,
say “C:\Users\<user name>\My Documents\Visual Studio 10\Projects\Service\Client
3. Go to your Service console application & run the service.
4. Once the service is up & running, execute the svcutil.exe command like this:
svcutil.exe /language:cs /out:GeneratedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
This will generate 2 files for you, the app.config (WCF configuration file) and the GeneratedProxy.cs file (the Proxy implementation of the service)
5. Import these two files to the Client console application. To view the app.config file, you need to select “All Files(*)” option in the file types.
6. Go to the Program.cs. Instantiate the  CalculatorClient (from the GeneratedProxy.cs)
Full Code (Program.cs):
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
{
class Client
{
static void Main()
{
//Step 1: Create an endpoint address and an instance of the WCF Client.
CalculatorClient client = new CalculatorClient();
// Step 2: Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine(“Add({0},{1}) = {2}”, value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine(“Subtract({0},{1}) = {2}”, value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine(“Multiply({0},{1}) = {2}”, value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine(“Divide({0},{1}) = {2}”, value1, value2, result);
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.WriteLine(“Press <ENTER> to terminate client.”);
Console.ReadLine();
}
}
}
Now we have both the service & the client ready in our solution.
To execute:

Step 1: Set the Service Project as the startup project & press Ctrl + F5, not F5. Ensure that the console screen says Service is up & running.
Step 2: Set the Client Project as the startup project & press Ctrl + F5. The console screen popups up with the results displayed. The service console screen
will have the status of received & returned values.
I am attaching some screenshots here to give you some heads up.
The Service Up & Running:
The Service & the Client Up & Running together:
Hope this was useful.
Special Note: This tutorial is taken from MSDN directly! But since contents were scattered across pages i just collated all of them to help readers understand the concept.

Javascript Trim, Left Trim & Right Trim Functions


Javascript string property does not have the normal trim functions like we have in any other language. And these trim functions appears play a crucial role in any code based on strings. There are two approaches i give here. One is directly creating a prototype method and other as a standalone function. You can choose the one depending on your needs.

Trim functions on the string prototype:

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,””);
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,””);
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,””);
}
// example of using trim, ltrim, and rtrim
var myString = ” hello my name is “;
alert(“*”+myString.trim()+”*”);
alert(“*”+myString.ltrim()+”*”);
alert(“*”+myString.rtrim()+”*”);

Trim functions as a standalone:

function trim(stringToTrim) {

return stringToTrim.replace(/^\s+|\s+$/g,””);

}

function ltrim(stringToTrim) {

return stringToTrim.replace(/^\s+/,””);

}

function rtrim(stringToTrim) {

return stringToTrim.replace(/\s+$/,””);

}

// example of using trim, ltrim, and rtrim

var myString = ” hello my name is “;

alert(“*”+trim(myString)+”*”);

alert(“*”+ltrim(myString)+”*”);

alert(“*”+rtrim(myString)+”*”);

Hope this helps.

Maintain scroll position on postback for gridview or div


Problem Statement:

There can be scenarios wherein your end users would appreciate to see the screen intact even after postback. In ASP .Net we use the MaintainScrollOnPostback property for the page to handle the page’s scroll position. But this will not handle the case when you have gridviews wrapped in divs and having a scroll (usually the overflow property). To maintain the scroll on postback in this case is not directly possible.

Check the gridview image above. There are a lot of checkboxes in it and the width of the grid goes beyond the screen size. Hence i have given a scroll to the div wrapping it. Under normal scenarios when the user clicks on the refresh button or Submit button or F5 in the browser, the scroll position of the div will not be retained. Instead it will look something like what you see below:

However the end user would really appreciate if the scrollbar also had maintained its position after the postback.

Solution Approach:

The solution for this kind of a problem could be easily done through javascript and a hidden variable on the page.

Solution:

Step 1 : In the scrolling div, register the onscroll event for storing the scroll position of the div.

<div id=”grdScr” onscroll=”javascript:setScroll();” >
<asp:GridView ID=”gdvPostings” runat=”server” GridLines=”None” CellPadding=”0″ CellSpacing=”0″
BorderWidth=”0″ AutoGenerateColumns=”false” CssClass=”jqPst” HeaderStyle-VerticalAlign=”Bottom”
OnRowDataBound=”gdvPostings_RowDataBound” EnableViewState=”true”>
This function will take the scrollLeft value of the div and store it in a hidden variable on the page.

Step 2 : In the page code behind, you should register the script that should run in the page load. This should take care of setting the div scroll to the state which it was, before the postback.

ClientScript.RegisterStartupScript(typeof(Page),”scroller”, “scrollToVal();“);

This function will set the value of the div scrollLeft property to the value in the hidden variable.

Step 3 : Place a hidden variable in the page, with runat server attribute. If you dont make it server side, the value will not be retained.

<input type=”hidden” id=”hdnScrPs” runat=”server” value=”” />

Step 4 : Load the javascript functions in the page.

$(document).ready(function(){

$(“#grdScr”).scroll(function(){

$(“[id$=’hdnScrPs‘]”).val($(“#grdScr”).scrollLeft());

});

});

 

function scrollToVal() {

$(“#grdScr”).scrollLeft($(“[id$=’hdnScrPs‘]”).val());

}

I have used jQuery in this case. You can use normal javascript if you need.

 

Alternative Approach (using HTML5 LocalStorage – valid for IE 8 & above N rest of the world):

Step 1: Bind a scroll event to the grid’s wrapper div, capture the scrollLeft value and store it in localstorage

Step 2: On page load, set the scroll position back to the grid’s wrapper div

 $(document).ready(function(){

// Check if the localstorage has values on page load, if yes, set the scroll left for the wrapper div

var gridScrollPos = localStorage.getItem(“GridScrollPosition”),

$grid = $(“#grdScr”);

gridScrollPos && $grid.scrollLeft(gridScrollPos);

//Bind the Scroll event to the grid to capture the scroll position and store it in localstorage

$grid.on(‘scroll’, function(){

localStorage.setItem(“GridScrollPosition”, $(this).scrollLeft());

});

});

Hope this helps. Feel free to post your queries.

Update(s):

  • The hdnScrPs id selector is changed to accept values irrespective of the prefix that is appended to it while getting rendered on the HTML, by using $(“[id$=’htnScrPs’]”) instead of $(“ctl00_cphMain_hdnScrPs”)
  • Using $.scrollLeft instead of javascript scrollLeft
  • Using $.scroll instead of javascript onscroll event
  • Added an alternate approach using localstorage

 

Horizontal Scrollbar for ASP Listbox or HTML selectbox


Problem Statement:

A normal listbox or ASP Listbox for that matter has an issue with the scroll. They have vertical scroll by default with them. However when it comes to horizontal scroll, they choke. Even if we specify a width for the listbox and give a lengthy option in the listbox content, you cant expect it to give scroll to you automatically.

Solution Approach:

The best solution approach is to wrap the listbox in a div. The div will give the horizontal scroll, while the listbox will have its own vertical one.

Let us take a simple ASP .Net ListBox control. You can do the same with even a selectbox with select=”multiple”.

<asp:ListBox ID=”lstGroupMembers” runat=”server” SelectionMode=”Multiple” style=”width:390px;height:250px;”></asp:ListBox>

You can see how the listbox gets rendered(above). Let’s assume that one of the options in the listbox was lengthy and goes beyond this width limit. Let’s see how it gets rendered.
The original text in the above listbox is “Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lorem justo, pulvinar nec viverra”, however you are able to see only the bold section. The remaining text got trimmed.
Now lets see how it gets rendered after implementing the fix.
You will be able to see the full text here since we have a horizontal scrollbar coming into picture.
Solution:
Step 1 : Wrap the listbox with a div just like the one below. Ensure that the width of the div is the same as the width of the listbox and height is [listbox height + scrollbar height (7px-8px) = 257px (here)]. The overflow is for the x axis only, since we don’t want to see the vertical scrolls. Just in case you see some vertical scroll, ensure that you increase the div height to a suitable value. This might happen because of some padding or margin of your listbox.

<div id=’groupMembers’ style=”overflow-x: auto;width:390px;height:257px;” >

<asp:ListBox ID=”lstGroupMembers” runat=”server” SelectionMode=”Multiple”></asp:ListBox>
</div>
Step 2 : Now write the javascript that does the creation of scrolling for your listbox
function changeListboxStyles(flag) {
//If flag is true, then the scroll effect happens.
//If flag is false, then the scroll effect goes and everything is reset back to normal.
if (flag) {
if ($(“#ctl00_cphMain_lstGroupMembers > option”).size() != 0) {
//Setting the width to auto to give the scroll effect, when the text goes beyond the width of the listbox.
$(“#ctl00_cphMain_lstGroupMembers”).get(0).style.width = ‘auto’;

//Setting the height to be reduced a little to take care of the scrollbar of the div coming into picture
$(“#ctl00_cphMain_lstGroupMembers”).get(0).style.height = ‘240px’;

$(“#groupMembers”).get(0).style.border = ‘1px solid #9f9f9f’;
$(“#groupMembers”).get(0).style.borderTop = ‘none’;
}
}
else {
if ($(“#ctl00_cphMain_lstGroupMembers > option”).size() == 0) {
//Resetting the width settings of the listbox back to the original value.
$(“#ctl00_cphMain_lstGroupMembers”).get(0).style.width = ‘390px’;
$(“#ctl00_cphMain_lstGroupMembers”).get(0).style.height = ‘250px’;

$(“#groupMembers”).get(0).style.overflow = ‘hidden’;
$(“#groupMembers”).get(0).style.border = ‘none’;
}
}
}
The main reason why you need this javascript into picture is due to the fact that you are fixing the width of your listbox(in 99% percent of cases). And the scroll will work only if you dynamically increase the width of the listbox based on the contents or set the width of the listbox to auto. The javascript above does the same.
If i want this scroll functionality to be implemented in the page load, i call the javascript function as changeListboxStyles(true); I just check if there are any contents in that listbox. You can go ahead and customize this to any level. Lets say you can play around with the borders and styles. Just ensure the one in the bold (in the javascript) are taken care.
I have used jquery in the above code. You can use javascript appropriate. I am not writing that here.
Step 3 : Call the function  changeListboxStyles(true); when you want to view scroll. Call the function changeListboxStyles(false); when you are done with your job and revert back to normal, especially when you don’t have any options inside the listbox.
Hope this solution helps. Do post your queries, if any.