LastIndexOf in TSQL

I came a cross a case where I need to parse a string and get a everything after specific character. Unfortunately there is no a function that is being shipped out of the box with MS SQL Server that is doing the needed job. So we had to use 3 built-in functions in SQL in order to do the job, here is a sample TSQL statement that demonstrate how you can do it

DECLARE @SomeString VARCHAR(100)
SET @SomeString = 'Part1;Part2;Part3'

SELECT RIGHT(@SomeString, CHARINDEX(';', REVERSE(@SomeString) + ';') - 1)

Deploy Angular app to IIS Web Server

After finishing development your Angular 2+ application, I think you would be thinking of what available options to publish your app, there is plenty of options available and described on Angular website but I’m summarizing the list of actions needed to deploy  your app to IIS server.

Deploying Angular 2+ applications to IIS Web server is very easy step, it is only couple of steps.. to do so follow the below steps:

1. Build your AngularJs application for production. to do so type the following command

ng build -prod --output-path [Path]

2. Copy the generated files from step# 1 into your IIS folder.

3. Create a new website for new your application.

4. Create a new web.config file with the following contents:\

<?xml version="1.0" encoding="utf-8"?> 
<configuration>   
   <system.webServer>     
      <rewrite>       
         <rules>         
            <rule name="Angular Routes" stopProcessing="true">           
               <match url=".*" />           
               <conditions logicalGrouping="MatchAll">
                  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />            
                   <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />          
                </conditions>           
               <action type="Rewrite" url="/" />        
             </rule>      
          </rules> 
       </rewrite>   
   </system.webServer> 
</configuration> 

It is very important to make sure that your IIS web Server has the rewrite module installed on it.. the following URL has the downloadable file

https://www.iis.net/downloads/microsoft/url-rewrite

Restarting Computer Remotely using cmd

I came across and issue where I can’t RDP to my PC which is located on another country and I need to get connected to it. Unfortunately, while there is no one physically can restarting the PC. So I had no option but restarting the PC remotely.. Thankfully, there was an easy way where I can restarting the PC using command prompt. Below are the steps that I follow to restart the PC

1. Run the Command Prompt with admin mode. to do so, right click cmd short cut and choose “run as Administrator”

2. type the following command:

net use \PCIPAddressIPC$

lets assume the IP Address is 192.168.1.5 then the command will be

net user \192.168.1.1IPC$

you will get this response

The password or user name is invalid for \192.168.1.1IPC$.
Enter the user name for '192.168.1.1':

3. Enter username along with domain name like below

Enter the user name for '192.168.1.1':   DomainName\UserName

4. you will get prompted to enter the Password as below

Enter the password for 192.168.1.1 :

if the username and password is correctly provided, then you will get the below message confirming things are good:

The command completed successfully.

5. Now we are ready to send the restarting command to the target PC as bellow

shutdown /r /m \192.168.1.1 /c "Comments"

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