Singleton vs Static class : Key Differences and Usages

The debate about Singleton vs Static is quite old and it is still continuing and there are lots of confusion around this as well. In this post, I am trying to explain these two concepts, key differences and its usages.In this post I will not focus on the basics of Static and Singleton and how to write that. If you are new to these keywords, I will advise you to learn about these first to get more benefited.

So first we are going to understand the characteristics of each . Lets start with static class

Static Class :

  1. Static classes cannot be instantiated so it restricts us in many ways like it cannot implement Interfaces, inherit any class etc.
  2. Any other scenarios where this keyword is required, it cannot be used like indexer etc. Also it cannot be used as method parameter, local variable etc for the same reason.
  3. Static classes can have only static members – constructor, fields, methods, properties, events.
  4. One cannot control when static constructors are called. It’s always earlier than first access of the class. So no parameters can be passed as well.

Internally when compiler compiles static class, it marks it as a abstract and sealed. So that no instance can be created and cannot be extended as well. Now let’s talk about Singleton

Singleton Class :

  1. As name suggests it allows to have only one instance of a class.
  2. The constructor of this class are marked as private so that accidentally one cannot create multiple instances and provides a static function/property which first create one instance and returns the same each time.
  3. As singleton is a normal class, it allows us to leverage all that features of object oriented programming concepts.

Memory Management :

There is much confusion around memory management of static class and Singleton class. In simple words, any class whether it is itself static or any member if marked as static then it would not be collected by Garbage Collector.

Static variables/classes are not stored in normal Heap and there is a separate space in memory to store static resources which holds the static classes and variables.This space is beyond the scope of GC and memory get release only when corresponding process/AppDomain unloads.

Because singleton holds a static reference which cannot be collected by GC so the instance cannot be collected and both (Static and Singleton) gets destroyed with the AppDomain/Process.

Some Key common characteristics :

  • As both of the static and singleton instances are have just one copy in memory throughout the whole application, both used for holding global state in an application.
  • Both are initialized lazily, it means for static classes it is initialized only when accessed first time and for Singleton, it gets created only when it is accessed first time.

The Differences

  1. Very first difference is that Static is a language feature and Singleton is a architectural pattern so both belongs to difference arena altogether.
  2. Now a days everybody is behind using Dependency Injection and Static does not fit there because it is interface driven.
  3. Unit Testing is another topic where you can find some way to create a mock for singleton instances but testing static is a nightmare.
  4. Being singleton is a just another class, it enable you to use Object oriented concepts.

Singleton approach is much more flexible as we can see that from the differences itself. We can use interface with it and implement it in a class and use in our application. If some requirement changes and later we require to change the logic then we can just remove the older implementation and replace with new one without hiccups as long as the interface is same.. Also testing is another key benefit.

Static classes is mainly recommended for having grouping of a bunch of utility methods that can be called independently but again testing could be a problem and benefits of OOP is gone. So most of the time static should be avoided.

Having said that using global variable (like static class or singleton) makes a strong coupling between the global data and all the places where it is used.

Cheers,
Brij

 

Advertisements

Issue while creating a stock like excel chart using PowerShell

Although this post is not in continuation of my previous posts on Excel charts and PowerShell but discusses a specific issue while creating Stock like chart. As topics are same I will advice you to go through the previous posts as I will be referring few things from that. The links of my previous posts are below

So to create a basic stock like chart we need to provide the data is a specific format.
b4-1

So lets write the script for the same

$xlChart=[Microsoft.Office.Interop.Excel.XLChartType]

$xl = new-object -ComObject Excel.Application   
$fileName = ''
$wb = $xl.Workbooks.Open($fileName) 
$wsData = $wb.WorkSheets.item(1) 

#Activating the Data sheet
$wsData.activate() 

#Selecting the source data - We cn select the first cell with Range and select CurrentRegion which selects theenire table
$DataforChart = $wsData.Range("A1").CurrentRegion

# Adding a new sheet where the chart would be created
$wsChart = $wb.Sheets.Add();
$wsChart.Name = "Charts"

#Adding the Charts
$stockChart = $wsChart.Shapes.AddChart().Chart

# Providing the chart types
$stockChart.ChartType = $xlChart::xlStockHLC

#Providing the source data
$stockChart.SetSourceData($DataforChart)

# Set it true if want to have chart Title
$stockChart.HasTitle = $true

# Providing the Title for the chart
$stockChart.ChartTitle.Text = "Stock like Chart"

# Setting up the position of chart (Not required if the sheet has just one chart). It will create the chart at top left corner
$wsChart.shapes.item("Chart 1").top = 0
$wsChart.shapes.item("Chart 1").left = 0

# Saving the sheet
$wb.Save();

# Closing the work book and xl
$wb.close() 
$xl.Quit()
# Releasting the com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

So the above code looks fine as similar to our previous posts but when we run it throws an exception as
exceptionb4

It does not show any specific details for this exception and the error code also does not lead to any details but we do get default bar chart.

So it a look a little while to find the cause as it was not a common as for other charts it was working very smoothly.

For stock charts, it expects the data before providing chart types so if we change the below lines


# Providing the chart types
$stockChart.ChartType = $xlChart::xlStockHLC

#Providing the source data
$stockChart.SetSourceData($DataforChart)

to


# Providing the source data
$stockChart.SetSourceData($DataforChart)

# Providing the chart types
$stockChart.ChartType = $xlChart::xlStockHLC

Its starts running. Let’s see a quick look on resultant chart
stock-chart

So it was very peculiar as the resolution does not seem to have any logic but next time you face similar issue, it may be helpful.

Cheers,
Brij

How to create Excel Chart using PowerShell – Part 3

This post is in continuation of my previous two posts on creating excel chart using PowerShell and in the first post we created a basic chart then in the next post we we added some more features to our chart and added two charts. The link of the previous posts are given below

Today we will see some more useful features.

Let’s first discuss the chart types. In our previous post, we created two charts in which first one was Bar chart which was default and second one was line where we provided the chart type as 4 which turned into Line chart. The better way to use the chart enums for that. To use that first we need to get the chart type as

$xlChart=[Microsoft.Office.Interop.Excel.XLChartType]

Now we can assign the chart type as

$chart.ChartType=$xlChart::xlBarClustered

One key difference here is property name casing, when we provide the number it was chartType and now ChartType which takes enum as above.

Note- It may not work for you as is as show that it is not able to load/recognize Microsoft.Office.Interop.Excel.XLChartType so you need to add the type as

<em>Add-Type -AssemblyName Microsoft.Office.Interop.Excel</em>
/sourcecode]
In our example, I have chart types as

$firstChart.ChartType = $xlChart::xlBarClustered
$secondChart.ChartType = $xlChart::xlLine
$thirdChart.ChartType = $xlChart::xlAreaStacked

It looks more professional. To know the complete list of chart types click here

In this post, we will create three different charts and put it in a new sheet. Adding a sheet in the excel is pretty simple and can be added as

$wsChart = $wb.Sheets.Add();
$wsChart.Name = "Charts"

In the second line, I have provided the sheet name.

Now we will be adding charts in this new sheet as

$firstChart = $wsChart.Shapes.AddChart().Chart
$secondChart = $wsChart.Shapes.AddChart().Chart
$thirdChart = $wsChart.Shapes.AddChart().Chart

So lets just see the data in our sheet

dataforchart-3

Now let’s run script and see the charts

threecharts

So lets see the complete script

$xlChart=[Microsoft.Office.Interop.Excel.XLChartType]

$xl = new-object -ComObject Excel.Application   
$fileName = ''
$wb = $xl.Workbooks.Open($fileName) 
$wsData = $wb.WorkSheets.item(1) 

#Activating the Data sheet
$wsData.activate() 

#Selecting the source data - We cn select the first cell with Range and select CurrentRegion which selects theenire table
$DataforFirstChart = $wsData.Range("A1").CurrentRegion
$DataforSecondChart = $wsData.Range("A11").CurrentRegion
$DataforThirdChart = $wsData.Range("A21").CurrentRegion

# Adding a new sheet where the chart would be created
$wsChart = $wb.Sheets.Add();
$wsChart.Name = "Charts"

#Adding the Charts
$firstChart = $wsChart.Shapes.AddChart().Chart
$secondChart = $wsChart.Shapes.AddChart().Chart
$thirdChart = $wsChart.Shapes.AddChart().Chart

# Providing the chart types
$firstChart.ChartType = $xlChart::xlBarClustered
$secondChart.ChartType = $xlChart::xlLine
$thirdChart.ChartType = $xlChart::xlAreaStacked

#Providing the source data
$firstChart.SetSourceData($DataforFirstChart)
$secondChart.SetSourceData($DataforSecondChart)
$thirdChart.SetSourceData($DataforThirdChart)

# Set it true if want to have chart Title
$firstChart.HasTitle = $true
$secondChart.HasTitle = $true
$thirdChart.HasTitle = $true

# Providing the Title for the chart
$firstChart.ChartTitle.Text = "Domain controller's usage- Bar Chart"
$secondChart.ChartTitle.Text = "Events- Line Chart"
$thirdChart.ChartTitle.Text = "Events Daily- Stacked Area Chart"

# Setting up the position of chart (Not required if the sheet has just one chart). It will create the chart at top left corner
$wsChart.shapes.item("Chart 1").top = 0
$wsChart.shapes.item("Chart 1").left = 0

$wsChart.shapes.item("Chart 2").top = 250
$wsChart.shapes.item("Chart 2").left = 0

$wsChart.shapes.item("Chart 3").top = 500
$wsChart.shapes.item("Chart 3").left = 0


# Saving the sheet
$wb.Save();

# Closing the work book and xl
$wb.close() 
$xl.Quit()
# Releasting the com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Above script is self explanatory. We provided different positions (top and left) for each chart so that it gets located at properly on sheet.There are more customizations available which we can use based on our need.

Cheers,
Brij

How to create Excel Chart using PowerShell – Part 2

This post is in continuation of my previous post on creating excel charts using PowerShell where we discussed how can we create a basic excel chart. Refer below link for first post

How to create Excel Chart using PowerShell – Part 1

Today we will see some more useful features. Let me start with a question

What if there are multiple data sets available in the sheet?

As in previous post, we didn’t provide any data source to the chart but in an ideal case we should. Now we have multiple sets of data and we want to create a chart based on each set. Say our sheet looks like

MultipleSetofData

We want to create two charts based on the two data tables as above. So we need to provide it as a data source. The easy way to select data, is using the current region property. Lets see that

#Select the first cell via Range and select CurrentRegion which selects the entire table
$DataforFirstChart = $wsData.Range("A1").CurrentRegion

Here we DataforFirstChart refers the first table. A1 is the first cell of the table and current region returns the complete table. Similarly we can get the second table

$DataforSecondChart = $wsData.Range("A11").CurrentRegion

First cell of the second table is A11 so we used the same.

As we are going to create two charts we need to define the positions as well. It provides two properties top and left which can be used as

$wschart.shapes.item("Chart 1").top = 0
$wschart.shapes.item("Chart 1").left = 0

What about chart types? In previous post, we didn’t provide any chart type and by default the bar chart was rendered. We can provide the chart type based on our requirement. We will set the second chart as Line chart and we will discuss it in bit more details in next post.

$secondChart.chartType = 4

So let’s the complete code

$xl = new-object -ComObject Excel.Application	
$fileName = 'D:\TestP\DataforCharts.xlsx'
$wb = $xl.Workbooks.Open($fileName)	
$wsData = $wb.WorkSheets.item(1) 

# Activating the Data sheet
$wsData.activate() 

# Selecting the source data - We cn select the first cell with Range and select CurrentRegion 
# which selects the entire table
$DataforFirstChart = $wsData.Range("A1").CurrentRegion
$DataforSecondChart = $wsData.Range("A11").CurrentRegion

# Adding the Charts
$firstChart = $wsData.Shapes.AddChart().Chart
$secondChart = $wsData.Shapes.AddChart().Chart

# Providing the chart type - Line chart
$secondChart.chartType = 4

# Providing the source data
$firstChart.SetSourceData($DataforFirstChart)
$secondChart.SetSourceData($DataforSecondChart)

# Set it true if want to have chart Title
$firstChart.HasTitle = $true
$secondChart.HasTitle = $true

# Providing the Title for the chart
$firstChart.ChartTitle.Text = "Domain controller's usage- Bar Chart"
$secondChart.ChartTitle.Text = "Events- Line Chart"

# Setting up the position of chart (Not required if the sheet has just one chart). 
# It will create the chart at top left corner
$wsData.shapes.item("Chart 1").top = 0
$wsData.shapes.item("Chart 1").left = 350

$wsData.shapes.item("Chart 2").top = 250
$wsData.shapes.item("Chart 2").left = 350

# Saving the sheet
$wb.Save();

# Closing the work book and xl
$wb.close()	
$xl.Quit()
# Releasting the xl object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Above code is self explanatory, we provided different positions for the both charts. Now it’s time to run the script and see the output.

multichart-b2

Awesome, so we can see two charts one is Bar and another line chart as expected. In the next post, we will add some more features to it and see more options.

Cheers,
Brij

How to create Excel Chart using PowerShell – Part 1

Recently, I had to automate a complete test suite for a very complex system which uses lot of internal and external tools and generate different kind of reports. PowerShell is a primary tool for writing the automation scripts so we started using it. I found it very powerful although any nice editor (free) or proper documentation, best practices etc not available. So I explored many things with my team and I will be sharing few things here. In the coming couple of posts, I will discuss about creating excel charts using PowerShell  and in this post we will start with creating a basic chart.

To create a chart, we need the data in a tabular format which is to be used to create a chart. Lets understand what all basic steps need to be followed for creating the chart.

  • Open the excel and correct sheet .
  • Add a new sheet (Optional)
  • Provide the name to sheet (Optional)
  • Add a chart in the sheet
  • Set the Title if required
  • Save the excel
  • Releasing the com objects

Now let’s go straight to the example. Say we have a excel with data like this

chartExcel

Now its time to see the real script. Refer inline comments for detail

# Creating excel com object
$xl = new-object -ComObject Excel.Application   
$fileName = <path of the excel file>
$wb = $xl.Workbooks.Open($fileName)
#Open the first sheet of the excel 
$wsChart = $wb.WorkSheets.item(1) 

# Activating the Data sheet
$wsChart.activate() 

# Adding the Chart
$chart = $wsChart.Shapes.AddChart().Chart

# Set it true if want to have chart Title
$chart.HasTitle = $true

# Providing the Title for the chart
$chart.ChartTitle.Text = "Domain controller's usage"

# Save the sheet
$wb.Save()  

# Closing the work book and xl
$wb.close() 
$xl.Quit()
# Releasting the excel com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Now its time to run the script and see the chart.

barchart

Looking perfect.

Note – You may not be able to run the script as it may show the script execution permission denied. For that you need to run the following command (Details here).

Set-ExecutionPolicy Unrestricted

Above code is pretty basic and there are couple of things which is taken by default like Chart Type (which is Bar chart), Data range used for chart (Since single data set is present), position of the chart etc.

In the next post, we will take a step further and use more APIs.

Cheers,
Brij

 

Learning ASP.NET Web API [Packt] – ASP.NET Core RC1 to ASP.NET Core 1.0

Hello All,

Recently, I published a video course on ASP.NET Web API using ASP.NET Core framework. Initially, when I started working on it, it was named as ASP.NET 5 and as it progressed till last section, Microsoft announced to rename it as ASP.NET Core and RC2 got released few days prior to the course release date. Microsoft took more than six months to release the next RC version. Although the concept was same but there were major changes in tooling and libraries. As it was not the final version so we decided to provide the details of differences once RTM releases.

In this post, I will be putting the details of the changes by section and also update the sample which will be available with the course. As ASP.NET 5 got renamed to ASP.NET Core, accordingly the names of libraries got changed to ASP.NET Core as well so we need to change all the references. The following table contains the details of packages that we need to update in our sample with the video number.

ASP.NET 5 Reference (Earlier) ASP.NET Core 1.0 Reference (Current) Video#
Microsoft.AspNet.Mvc Microsoft.ASPNETCore.MVC 2.2
EntityFramework.Core
EntityFramework.MicrosoftSqlServer
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
2.3
Microsoft.AspNet.Mvc.Formatters.Xml Microsoft.AspNetCore.Mvc.Formatters.Xml 2.4
Microsoft.AspNet.Mvc.TagHelpers
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNetCore.Mvc.TagHelpers
Microsoft.AspNetCore.Identity.EntityFrameworkCore
5.4

Updated sample is available with the course and refer the project.json to find the updated references. Also, Microsoft again reintroduced web.config file but it will be there along with Project.json.

Note – The details will be included for only for those those sections where changes are required.

Section 2   
As this was the first section where we started our discussion on ASP.NET Core Web API and started working on our sample so this section got many changes. Let’s discuss each

Video 2.1 : There are changes in the project creation flow. Earlier when we used to create ASP.NET Core project, it used to have two sets of references – one for core and other for full framework. We either used to build the application using both the framework and remove one based on our needs. As there were many libraries which could not work in both the platforms so Microsoft has provided the option to select the framework upfront while creating the project which makes the complete process simpler. Also, in real world scenarios, there are rare chances when we need to build the binaries for both the framework.  Now when we open New Project window and select web from left side then we get three options as
2.1Here we have three options.

  1. First one is a traditional ASP.NET application using .NET 4.6.
  2. Selected one is ASP.NET Core application using .NET Core framework and the same is used in our course.
  3. Third one is again ASP.NET Core application but uses the standard .NET framework.

When we select the second option, it shows the following dialog

2.1_2

It also got revamped completely. We had earlier lots of options which included standard ASP.NET templates. Now it contains only ASP.NET Core templates and has three options same as earlier ASP.NET 5 templates and we used the empty template for our course. Just to mention again, now we have just one bag named as .NETCoreApp,Version=v1.0  which contains set of libraries for .NET Core only in the references.

There are some more changes as below

a) Earlier we used to have following line in startup.cs which was entry point for the web application

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);

but now we have a new file program.cs which contains the main method which is now entry point for the web application.

b) Configuration file web.config is also back in project file and available along with project.json although all the settings should be put in project.json and we will be using the same.

c) There are also changes in the number of the parameters in ConfigureServices method in startup.cs which includes Hosting Environment and logger factory but we will not be using it in our sample.

Video 2.2: Only change in the references. Refer the initial table.

Video 2.3: In this video, we discussed that there are four options to register a service but we found AddSingleton and AddInstance very similar, both allows single instance across multiple requests with a difference in the instance creation. Now we have only AddSingleton where either we can pass the instance or provide the type info as.

To register via interface and class name

services.AddSingleton<IBookStoreRepository, BookStoreRepository>();

and to register an instance

IBookStoreRepository bookStoreRepository = new BookStoreRepository(new BookStoreContext());
services.AddSingleton(bookStoreRepository);

Video 2.4: Only change in the references. Refer the table.

Section 3
In this section we added CRUD operations to our sample using  HTTP verbs. Only few changes are required in the section as mentioned below.

Video 3.2: Microsoft did an awesome change with it by making the JSON response in camel case by default. In our sample we added serialize settings in statrtup.cs as

options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

It is no more required.

Video 3.3 :  We returned various status codes from the action methods based on the request.The classes that we used also got renamed as

ASP.NET 5 ASP.NET Core 1.0
HttpUnauthorized Unauthorized
HttpNotFound (and its overloads) NotFound
HttpBadRequest (and its overloads) BadRequest

The above changes has taken place in all the action methods wherever used.

Section 4 
In this section, we added few more features to our sample like sorting, paging etc. Here there is a change in the way we access URL Helper as discussed below.

Video 4.3: We used URL helper for generating the URLs and it was injected via constructor without any other changes as it was by default available which is not the case now.

Now we need to access it via UrlHelperFactory and action context. ActionContext is accessed via ActionContextAccessor, for that we need to register it in startup.cs as

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

and we need to inject the UrlHelperFactory and ActionContextAccessor in constructor to get the URL helper as

  public BooksController(IBookStoreRepository _repository, IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor)
        {
            this.repository = _repository;
            this.urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
        }

Rest of the code would be same as we got the similar URL helper.

Section 5
In this section we talked about security implementation. In it we have only few changes as below.

Video 5.2 : We created a custom authorization attribute RequireHttpsAttribute which inherited from AuthorizationFilterAttribute where we checked the scheme from the URL. Now RequireHttpsAttribute is itself available under the namespace Microsoft.AspNetCore.Mvc so we can use the same to enforce the SSL in complete application or any specific controller/action.

Video 5.4 : Only few references changes. Refer the table

Section 6 
In this section, we discussed some advanced topics like DI, CORS etc and there are few changes in DI. Let’s see that

Video 6.1:
a) As discussed earlier that now we don’t have AddInstance option for registering the service, same can be achieved via AddSingleton.

b) We discussed that we can also inject services via property using FromServices attribute but it is not available any more as it was creating confusion and issues. Constructor injection is always preferable. From services is available and can be used for Action Injection as

public IEnumerable<Book> Get([FromServices] IBookStoreRepository repository)
{
...
}

These are the key changes that took place specific to Web API and our course. I created again the sample from scratch using the ASP.NET Core 1.0 which can be downloaded from the course.

Thanks a lot for your support and feedback.

Cheers
Brij

How to test email functionality without configuring Smtp Client

Writing code for sending mail is one of the common tasks that we need to work every now and again. Sometimes it is one of the requirements in our application and some time we develop to send alerts to all when application looses its control on production :).

.NET made it very simple to send the mail which normally looks a complicated task. We can easily write 4-5 lines of the code to send the mail. Lets just have a look on a sample code

Continue reading