Object Oriented Programming : Revisited

Firstly it is OOP and not OOPS, probably OOPS as an acronym became popular and has been widely used for many years so everyone just tags along. Anyways, OOP has 4 pillars

1. Abstraction 2. Polymorphism 3. Inheritance 4. Encapsulation

1. Abstraction :

It is the ability to generalize types i.e. it gives us the freedom to think about higher level concepts without going into too much details. Practically it is implemented with Abstract Classes and Interfaces. By using Abstract Classes or Interfaces we can create a software solution by focusing on broader concepts like AbstractCloudStorage or ICloudStorage and focus on what and how of AbstractCloudStorage or ICloudStorage  or how they will interact with browser, OS, data center etc. instead of diluting our attention towards their concrete implementations like GoogleDrive or SkyDrive or iCloud etc.

2. Polymorphism

Polymorphism (from the Greek meaning “having multiple forms”) is the characteristic of being able to assign a different meaning or usage to a variable, a parameter, a field, a property, a function, or an object in different contexts. There are fundamentally three types of Polymorphism, the first two of which were originally informally described by Christopher Strachey in 1967.

a. Ad-hoc Polymorphism which is popularly known as Method (function) and Operator Overloading.

b. Parametric Polymorphism allows us to have variable or field or parameter or property or function parameters of a function or a data type to be written generically instead of dependent on a particular type. This is popularly called as Generics in C# and one of the most popular example of it is List<T>.

c. Subtype Polymorphism (or inclusion polymorphism) is also popularly known as Overriding (though this is debatable). In C# a property or a method can be declared as virtual in base class which then we can override in derived class.

Another aspect of Subtype Polymorphism allows a function to be written to have parameter of a certain type T, but also work correctly if passed a parameter of a type S that is a subtype of T (according to the Liskov Substitution Principle). Subtype Polymorphism is complimentary to Inheritance.

3. Inheritance

Inheritance is a way to create new classes that absorb data and behavior of an already existing class and then enhancing them.

In other words, Inheritance is a way to establish “Is-a” relationship between objects

In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes called base classes, superclasses, or parent classes. The resulting classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance gives rise to a hierarchy.

However Inheritance more often than not results in the below Issues :

a) It is often confused as a way to reuse the existing code which is not a good practice because inheritance for implementation reuse leads to Tight Coupling i.e between the base class and derived class. This means when changes are done in the Parent class, mostly changes need to be done in the derived class or how the derived class is used; resulting in low maintainability. To understand this kindly visit this link.  Re-usability of code should be achieved through composition (Composition over inheritance). Another link I would highly recommend which tells why we naturally (i.e. our thought process) lean more towards Inheritance and why usually that is not such a good idea.

b) yo-yo problem is an anti-pattern that occurs when a programmer has to read and understand a program whose inheritance graph is so long and complicated that the programmer has to keep flipping between many different class definitions in order to follow the control flow of the program.

d)  Inheritance breaks encapsulation by exposing subclasses to implementation details in the superclass. That is the sub class will always have all the data and behavior of parent class and we can not choose a specific data and behavior of base class to available for derived class. 

4. Encapsulation

It is the ability to wrap “something complex” or “something which had many steps” into a single; easy to use container. Practically it is implemented with Functions or Methods. For example the below method does many things like validating customer information, opening data base connection, firing a query or SP, or use ORM framework to persist customer information in a DB. But the caller of this method need not to worry all this and just need to eat this capsule or call this method.

Code Snippet
  1. private void AddCustomerData(Customer customer)
  2. {
  3.     // Validation Logic
  4.  
  5.     // DB Connection
  6.  
  7.     // Fire Query etc..
  8. }

 

One more thing Information Hiding / Data Hiding / Hiding (in General):

It is the ability to hide unnecessary data and behavior from the end user. Here if you are writing a library your end user is some other software, if it is a class, end user is other classes of the same program etc. Practically it is implemented with Access Modifiers i.e. public, internal, protected, private in .Net world and with Properties and Fields.

By using Access Modifiers we are limiting the visibility and usage of methods (especially), fields, properties to the end user and hiding unnecessary stuff.

On the other hand, by using Properties to Get and Set data we are hiding how actually data is actually processed or manipulated or persisted by the class.

For example in the below example if the end user i.e.Program class’s Start method forget to assign Currency field of Amount object, then while setting the Amount property we can check this and set it as per current region of the computer. What I am trying to demonstrate is; by using Property we have hidden the behavior of checking and assigning currency and this will make sure whenever we Get the Amount it always has Currency.

A similar example of Data Hiding can be when Setting Amount we can normalize it to USD and store it and then while Getting it we can do the appropriate currency conversion as per the computer’s culture.

Code Snippet
  1. using System.Globalization;
  2.  
  3. namespace HidingConsoleApplication
  4. {
  5.     class Program
  6.     {
  7.         public void Start()
  8.         {
  9.             this.Amount = new Amount() { Value = 2.0 };
  10.         }
  11.  
  12.         private Amount _Amount;
  13.         public Amount Amount
  14.         {
  15.             get { return _Amount; }
  16.             set
  17.             {
  18.                 if (string.IsNullOrEmpty(value.Currency))
  19.                 {
  20.                     value.Currency = GetCurrencySymbol();
  21.                 }
  22.                 _Amount = value;
  23.             }
  24.         }
  25.  
  26.         private string GetCurrencySymbol()
  27.         {
  28.             var ri =
  29.             new RegionInfo
  30.             (System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);
  31.             return ri.ISOCurrencySymbol;
  32.         }
  33.     }
  34.  
  35.     class Amount
  36.     {
  37.         public double Value;
  38.         public string Currency;
  39.     }
  40. }

All these concepts are complimentary (rather than competing), so when you are discussing about one, you will never know when you have ventured into the territory of other concept. In my opinion a pragmatic programmer would be able to create elegant code by having strong hands on with OOP concepts. Thus OOP truly results in a code base which is Extendible, Maintainable(Changeable), Scalable,  with Low Coupling and High Cohesion.

Side Notes :

  • A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class, if that class (the derived class) is not abstract. Classes containing pure virtual methods are termed “abstract”; they cannot be instantiated directly. In C# pure virtual functions are known as abstract methods.
  • Overloading is Compile time polymorphism, Overriding is runtime polymorphism.
  • We can create a long class hierarchy (using) inheritance, however it doesn’t mean we should.
Advertisements
calvin-and-hobbes

SSRS – Crazy Issues; Stupid Solutions

calvin-and-hobbes-e1328550590232

1. Interactive Sorting Garbling Table Header Text

As per best of my knowledge and googling capabilities there is no way to place the interactive sorting up and down arrows as per your choice and they will always appear on the right hand side of the cell / textbox /column header. And this wrecks havoc rendering your SSRS report if the cell / textbox /column header are not wide enough.  Check the below image :

Interactive Sorting Issue 2

A workaround is to have a dummy row below the header row and turn on the interactive sorting for the columns of this dummy row like below :

image

image

And then the when you run the report it will come out like this :

image

2. Image with Transparent Background Getting Garbled When Exported to pdf

This one is really weird, when the image you want to display in footer had a transparent background like below and the footer has a background (sky blue in my case):

image

then when the report is exported to pdf it looks like below, which is not really sharp:

image

So the workaround for this is to provide the image a background i.e. sky blue instead of transparent and then if you export your report in pdf it should be fine as below :

image

3. Display only the Currency Symbol

Typically we want to show the currency next to the numbers whenever we are displaying money in the report and the currency symbol has to be as per the client machine or browser locale, for example like below :

image

For this what we do is :

1. Set the Language property of report to User!Language

2. Set Format property of cells to C0 or something similar

As you can see, the currency symbol is also going to occupy some cell space and when the numbers has many digits this will cause a line break which will not be nice. So the ideal case is to display the currency symbol next to the column header like below :image

However the is no way to directly display the currency symbol because you need numbers so you can format them in currency but you have text

So the hack is

1. Create a placeholder instead of label for the column header and set the placeholders label as the column header text

2. Write a expression for the placeholder value which is

=”Column Header Text”
+ “<br>”
+ “(” + Replace(FormatCurrency(“0″,0),”0″,””) + “)”

which actually adds “Rs. 0” after the header text and then replaces the 0 with blank space

3. Set the markup type of the placeholder to HTML

4. Expand Drilldown while Exporting or Subscribing a Report

Drilldown is a great feature of SSRS, however if the drilldown is collapsed by default if you export or deliver a report by email by subscriptions then still the report content will be collapsed and for some use cases that’s what you will not want.

A workaround can be to add a report parameter ShowDetails with values Yes / No, default No , the drilldown visibility of groups / UI elements is governed by an expression based on this parameters value and when you subscribe the report, you subscribe it with ShowDetails = Yes

image

image

image

image

Adding Logout Feature in Microsoft Report Manager (SSRS with Forms Authentication)

Once we have configured SSRS to use Custom (Forms) authentication by deploying a custom security extension as described here, we can logon to MS Report Manager (MSRM) using credentials of our custom security framework via a logon web page.

However once you logon you will see that there is no way to logout or to expire the authentication cookie and to do so you need to close the browser. This problem is more pronounced for the “Verification Engineers”  since they have to do so n number of times to test n authentication and authorization scenarios. Also it will be a pain for the end users too since they will surely struggle to find a way to logout.

To fix this we can cook a small hack using jQuery and trusty html/css by manipulating the top right hand breadcrumb of MS Report Manager(MSRM) web pages, which looks like this :

image

Step1 :

If we carefully inspect the html of MSRM, the name of this breadcrumb is msrs-topBreadcrumb. Using some jQuery we can identify this element and append the logout href at the end of its last child. Once you do this on every page, the pages should look something like below:

——————————————————————————————————————–

<%@ Register TagPrefix=”MSRS” Namespace=”Microsoft.ReportingServices.UI” Assembly=”ReportingServicesWebUserInterface” %>
<%@ Page language=”c#” Codebehind=”CacheRefreshProperties.aspx.cs” Inherits=”Microsoft.ReportingServices.UI.CacheRefreshPropertiesPage” EnableEventValidation=”false” %>

<html>
<head>
<title></title>

<script type=”text/Javascript”  src=”jquery-1.7.1.min.js” > </script>

<script type=”text/Javascript” >

$(function() {
var a = $(‘.msrs-topBreadcrumb’);
var d = ‘<span style=”margin-left:2px;”>| <a href=”/Reportserver/logon.aspx?Logout=1″>Logout</a> </span>’;
$(d).appendTo(a.find(‘a’).last().parent());
});

</script>

</head>

</html>

——————————————————————————————————————–

Step 2:

Add the “jquery-1.7.1.min.js” file in  “C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\Pages”

We can download the jQuery file from internet.

Step 3:

Add the code to expire the authentication cookie on the logon.aspx page.

Note : Check the name of authcoooki from web.config which in our case is “sqlAuthCookie”

image

and that’s it, now the breadcrumb will look like below and clicking on “Logout” will logout the user:

image

Microsoft Pune User Group April 2012 Meeting

Well, today I attended the Microsoft Pune User Group (PUG) meeting and it was a pleasant experience. Firstly it was good to see the enthusiasm and the participation in the meeting by the fellow Pune developers. Also the speaker also had a grip over the topic.  Actually I attended only one session on Windows 8, as rest others were about SharePoint and somehow I felt uninterested in those. Mostly because I had skipped my breakfast & was simply starving. Coming back to the session on Windows 8, it was delivered by Aviraj Ajgekar and was an introductory session on Windows 8. The speaker was decent & session was informative. It felt like Microsoft is going all out to attract developers for Win 8 app development. All in all it was a good session and i would attempt to attend more of PUG meets.