Angular Js $http Provider Interceptors

The $http Service in Angular JS allow us to communicate smoothly with back-end services. I came into a scenario where I need to monitor all http requests/responses happening using $http service. we can do that with each $http use, but I strongly believe in not copy/past and duplicate the code over and over. so I was looking into an approach to that allow me to write a function or method that will be called with each http request made.

Angular Js supporting interceptors concept for $httpProviders service. The interceptor is a service function that will be called with each call for service..In our scenario,  you can think of the interceptor as a man monitor the traffic going back and forth.

Below code is basically adding a value to http request header and test the response status if it is 600 (custom value) then do certain action.

// interceptor logic.
app.factory('httpInterceptor', function ($q) {
    return {
        request: function(config) {
            config.headers['X-MyHeaderKey'] = "MyHeaderValue";
            return config;
        },
        requestError: function(rejectReason) {    
            //Do certain actions   
            return $q.reject(rejectReason);
        },
        response: function (response) {
             //Do certain actions
             return response;
         },
        responseError: function (response) {
            if (response.status === 600) {
                //Do needed logic in case of status 600
                return $q.reject(response);
            }
             else {
                return $q.reject(response);
            }
        }
    };
});
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
});

$httpProviders provides 4 main types of interceptors that you can use:

1) Request Interceptor: This service method will be called when $http service send request to back-end server. in the example able we simply injected a new key/value in the http request header.

2) Response Interceptor: This service method will be called after request sent to the server and once the $http service received the response. the response will be received as a parameter to the service method.

3) RequestError Interceptor: In some cases the request can’t be sent or other interceptors reject sending the request to back-end service. In this case, this service method will be called.

4) ResponseError Interceptor: This service method will be called whenever the back-end service has failure and return error to $http service.


How to use Log4Net C# application

log4net logo

Introduction:

Log4Net is library that you can use to manage data logging into flat files. The Log data might vary from informative messages, Diagnostics messages to Error messages and will help in debugging and troubleshooting issues on the application without the need to debug the code line by line. The main purpose of this post is to show the minimum changes that developer needs to do in order to use Log4Net library.

You can find the Log4net library’s code on github under the following url https://github.com/apache/log4net

How to Install in .Net application:

1. Get the needed references in your project

The first step to use log4net library is to add the right reference to your solution/project. in order to do that, Right click the solution project that you will use the library on it, and choose “Manage NuGet Packages” from the menu. This will show a new popup to search libraries.. Search for “Log4Net” then click on Install button as in below image

This will add Log4Net dll reference to your project references.

2. Assembly.Info changes

under the selected project, choose properties node and expand it. open assembly.info file and add the following line.

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

This line of code will tell Log4Net to be watching the xml configuration.

3. Adding the needed configuration to app.config or web.config file:

Open the configuration file and add the following line under the <configSections> tag

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

       

Add the following XML tag at the end of the config file but before the configuration closing tag  </configuration>

<log4net debug="true">
	<appender name="RollingFileConfig" type="log4net.Appender.RollingFileAppender">
		<file value="C:\\LogFolder\\Log.txt" />
		<appendToFile value="true" />
		<rollingStyle value="Size" />
		<maxSizeRollBackups value="1000" />
		<maximumFileSize value="1KB" />
		<staticLogFileName value="true" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
		</layout>
	</appender>
 
	<root>
		<level value="ERROR" />
	</root>
	<logger name="Exceptions">
		<level value="ERROR" />
		<appender-ref ref="RollingFileConfig" />
	</logger>
</log4net>

5. Log Messages from your code:

Logging messages from the code is one line of code as below:

LogManager.GetLogger("Exceptions").Error("Information to Log Goes here!");

the parameter that is passed to GetLogger function is the same Logger name on the config file. so basically you are telling the log4net to log an exception category with level Error to file

SignalR App Considerations and Constratints

SignalR Image

Before start considering SingalR to solve your business problem, you need to make sure that you have the right environment. Signal R can’t be installed in all .net environment as it has minimum requirements… below is the constraints that you have when developing SingalR applicaiotns:

1. Operating System Constraints:

SingalR applications can be installed on the followings operating systems:

    • Windows Server 2012
    • Windows Server 2008 R2
    • Windows 8 and Windows 8.1
    • Windows 7
    • Windows 10
    • Windows Azure.

 

2. .Net Framework Constraints:

You need to develop your SingalR application using .net 4.5+

 

3. IIS Constraints:

SingalR app needs to be hosted on the followings IIS versions

  • IIS 8
  • IIS 8 Express
  • IIS7 Support for extensionless URLsis required
  • IIS 7.5 Support for extensionless URLsis required
  • IIS application pool needs to be running in the integrated mode. Classic mode is not supported.

 

4. Client Side Scripting Constraints:

Web applications that SignalR communicating with needs to have JQuery version 1.6.4 or greater.

 

5. Web Browsers Constraints:

SignalR can be used with variety of web browsers, but typically only the latest 2 versions are supported.

The following is the list of web browsers that supported by SignalR at the time of writing this post:

  • Microsoft Internet Explorer versions 8, 9, 10, and 11. Modern, Desktop, and Mobile versions are supported.
  • Mozilla Firefox: for both Windows and Mac versions.
  • Google Chrome: for both Windows and Mac versions.
  • Safari: for both Mac and iOS versions.
  • Opera: for Windows only.
  • Android browser

 

Restore SQL Backup and getting Error “Specified cast is not valid (SqlManagerUI)”

SqlServerHeader

Couple of days ago,  tried to restore a SQL database backup that I got from my client. I was restoring it to my SQL 2008 R2 database engine. I followed the following steps:

1. Right click the databases folder and then chose Restore Database from the drop down list

Restore Database backup

2. I got the below popup so I choose the proper name for the database and selected the backup file

Restore Backup Popup

but I got surprised with a not meaningful message from SQL server saying “Specified cast is not valid (SqlManagerUI)”.

SQLBackupError

Although this error message doesn’t give much info, but it is telling that the SQL 2008 is not being able to read the database backup headers. So there was couple of possible causes for this:

1. The database backup is corrupted.
2. This is a backup from a newer version of SQL Server
3. This backup is password protected.

In my situation it was 2nd cause, so I only restore it on SQL 2012 Engine and things went fine with me.

What is .Net Extension Method

.Net Extension Method is one of a nice features introduced with .Net 3.0. It allows developers to add new functionalities to existing data types without having a need to inherit from these types or compile old code. For example, if you are encrypting and decrypting strings in your application, wouldn’t it nice to have a code like below
StringObject.Encrypt();
In the tradition way, we used to create a static helper method that we call and pass string to it as a parameter:

public static string Encrypt(string input)
{
//….Logic goes here
return encyptedValue;
}

Implementing Extension Methods is very easy.. All what you need to do is to create a static class and have your extension method as static method and use this keyword on the parameter list.. Below is a sample code

public static class MyExtensions {
public static string Encrypt(this string input) {
//….Logic goes here
return encyptedValue;
}
}

Note the “this” keyword that is being used on the parameter.. this what make this .Net Extension Method. You can call this method in 2 ways:
1. As extension method, str.Encrypt();
2. As regular method: MyExtensionClass.Encrypt(str);
Both syntax are equivalent to each other but the first one is less code.

Error during serialization or deserialization using the JSON JavaScriptSerializer

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

You should expecting the above error message in case you are trying to do an ajax call for a method that is returning large amount of data in JSON format. This is happening in case the size of JSON data exceeding the default maxJsonLength value for the JavaScriptSerializer. The good news is that this value is configurable and you can adjusted as needed.

  • Note:JavaScriptSerializer is a class that you can use to JSON serialize and de-serialize data in easy way.

Solving this issue require to write some code to change the default the size of maxJsonLength property’s value and inform the JSON serializer that this is a large size object. to do so, you will need to do something similar to below code snippet

public JsonResult GetLargeJson()
 {
      var response = GetLargeDataFromDataSource();
      //To handler large data results.
      jsonResultObj = new JsonResult();
      jsonResultObj.Data = response;
      jsonResultObj.MaxJsonLength = Int32.MaxValue;
      jsonResultObj.ContentType = "application/json";
 
      return jsonResultObj;
  }

Introduction to SignalR

signalr

What is ASP.Net SignalR

SignalR is a Technology that enable Real-Time messages/contents to be pushed from server to connected web clients without the need to refresh the web pages every specific period of time. In the old days, we used to have schedule timer on client side to request new data from server every specific period of time to update client UI with the new data. with SignalR this is no more the case.

Microsoft published a specific library for developers to enable them to add real-time functionlaities to asp.net web application . It is worth to mention here that SignalR is an open source project  an you can check the source code on GitHub.

Also SignalR supporting Scale out to thousands of clients using Service Bus, SQL Server or Redis. This enable SignalR to work seamlessly in  Web Farm or Web Garden environments with no issues to mention.

SignalR Usage Examples:

Chat applications over web is a great example of the usage of SignalR, Auto update client screens with currency exchange rates where user will get live updates with currency exchange rates as it is got changed

SignalR Communication Models:

There is 2 ways of communication models between Server and Clients using SignalR; Persistent Connections and Hubs

1. Persistent Connections:  A Connection represents a simple endpoint for sending single-recipient, or broadcast messages. The Persistent Connection enables the developer to have a direct access to the low-level communication protocol that SignalR exposes.
for those who worked with connection-based APIs in Windows Communication Foundation WCF, will be easily getting familiar with this model.
2. Hubs: is a more high-level that is built on top of connection API and allow server and clients to be able to call methods on each other directly and seamlessly. It is SignalR responsibility to handles the dispatching messages over the internet; SignalR MAGIC!
For those who use Remote Invocation APIs such as .NET Remoting will be getting familair with this model easily.

The Hub Communication model is suitable for most of the applications needs. For me I never get into a case where I have to use Persistent connection model, and I always go to Hubs model.

One of the Diagram that make it easy to understand the SignalR magic that I copied from www.asp.net site is the below one.. where it is showing that client can call server method easily and server can call a method on web client with no issues. This wasn’t possible without SignalR

what_is_signalr_invocation

 

 

Optimize Orchard Setup on Shared Hosting

In the past few days I was trying to setup Orchard on Godaddy shared hosting server. The steps that I follow was:

  1. Download Orchard CMS source code from the following link http://www.orchardproject.net/download   On this page, there is multiple options to download, I downloaded the one with Source Code as I’m interesting to look into Orchard code as well. but you can download the zip file which has no code. if you decided to download the zip file, then you can skip point 2
  2. Extract the source code zip file and open the solution in Visual Studio.. then publish the solution to your local drive.
  3. upload the published version to your shared hosting provide such as GoDaddy
  4. for the first time you access your website Orchard will compiling the code and building dependencies folder under App_Data.. so you need to make sure the App_Data folder has the proper permission for IIS user to write into that folder.
  5. once Orchard finish compiling the code, you will get into Setup page where you enter the site name and database information.
  6. after finishing the setup form, Orchard will start doing some internal stuff to add database tables.
  7. Once it done. you will get logged into Orchard dashboard. there you can manage Orchard CMS.
  8. Go to Module link and search for a module called “Keep Alive” install it. then enable it. this module will keep the IIS process working on Orchard website thus make it always alive and get rid of the worming up time.

Enlarge the Font Size on Visual Studio

VisualStudio

I was using Visual Studio 2013/2015 on small screen. The main issue that I was facing is the small font size for solution explorer and menu items. That was the main issue that I’m facing of using small screen. Thankfully there is a way to enlarge the font size for menu items and solution explorer.. to do so, follow these steps:

1. From tools menu, select Options

2. On the left hand size, choose “Fonts and Colors” and on the right hand side section of this, under “Show settings for” choose “Environment Font”

VS2013OptionsPopup

3. On “Font (bold type indicates fixed-width fonts) “ drop down list, change Arial font type or whatever font type you would like to have

4. And under “Size” drop down list choose the proper font size that you feel comfortable with.

5. Hit “OK” on the popup..

Hope that would help having a better development experience.

SQL Server Build Versions

SqlServerVersionsI was working on maintaining SQL Server DB backups on a new server of mine, but I faced an error message that telling me my backup file created on database engine 10.50.4042 version while my current database engine version is 10.00.5500. I believe you already faced such an error message.

Once I got that error message, the first question came into my mind is how can I know what these version numbers really menas to me and how can fix this issue.. answering to these question was nicely listed into this blog post, actually the author of this blog did a great job of creating a catalog of versioning numbers and what each one means.   https://buildnumbers.wordpress.com/sqlserver/