Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

AngularJS Dependency Injection

In this article I will explain AngularJS Dependency injection with some sample examples; first I will share definition of dependency injection.

Wiki Definition

In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

MSDN explanation of Dependency Injection

Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. The term "loosely coupled" deserves clarification and sometimes the best way to explain something is by first describing its opposite, which in this case is "tight coupling."

AngularJS Dependency Injection (DI)

The Angular injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.

AngualrJS provides following core components which can be injected into each other as dependencies.

1. Factory methods

Factory methods are functions registered with modules and used to return some value.

Following code sample explains how to use factory methods in AngularJS


var DoctorService = angular.module('DoctorService', [])
DoctorService.factory('DoctorsDataOp', ['$http'function ($http) {
    var urlBase = 'http://localhost:54393/Service1.svc';
    var DoctorDataOp= {};
   DoctorDataOp.getDoctors = function () {
        return $http.get(urlBase + '/GetallDoctors');
    return DoctorDataOp;

In this example we retrieve data using $http.get(),to use the $http service we have to pass this as dependency to the service factory.

2. Module methods

You can use functions to run at configuration and run time for a module by calling the config and run methods. These functions are used same like factory methods with your module, following code sample explains how to use module methods.

angular.module('myDcotAppModule', [])
.config(['appDepProvider'function (appDepProvider) {
    // ...
.run(['doctorService'function (doctorService) {
    // ...

3. Value

Here we consider value is simple JavaScript object used to pass value as parameter.

You can use this to pass controller or inject some vale to angularJS service.


var myTestModule =angular.module("myTestModule", []);
myTestModule.value("myValue"  , "nk1985");
function MyService(myValue) {
    this.doIt = function() {
        //perform some task with myValue
myModule.service("myService", MyService);

4. Service

A service in AngularJS is a singleton JavaScript object which contains a set of functions, here set of functions contain logic to complete task you want.

AngularJS services are created using the service() function on a module.


var app = angular.module("EmpApp", []);
app.service("EmployeeService"function ($http) {
    // Get Employee data
    this.getEmployee = function () {
        return $http.get("/Home/GetAllEmployees");
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
        return response;

5. Provider

Providers are most flexible in AngularJS you can use providers to create custom services, factory etc, providers tells angular how to create injectable things we can call these things services in technical term.
Services are defined by things called providers, which is what you're creating when you use $provide.

You can use Factory,value,service shortcuts to define provider , I will explain value in next section with current example I will define $provide with factory and service.


ProviderTestModule.config(function ($provide) {
    $provide.provider('AppConfig',function () {
        this.$get = function () {
            return function () {
                //here some configuration code

$provide with factory

ProviderTestModule.config(function ($provide) {
    $provide.factory('WebAppConfig', function () {
        return function (settingVal1, setttingVal2) {
            //here some configuration code

$provide with service


ProviderSampleModule.service('WebAppConfig', function () {
    return function (configSettingsValues) {
        //here some configuration code

$provide with value

ProviderSampleModule.config(function ($provide) {
    $provide.value('WebAppConfig', function (settings) {
        //here some configuration code

The Injector ($injector)

The injector is responsible for actually creating instances of our services using the code we provided via $provide.

You can get an instance of a defined service by calling get on it with the name of the service.

Sample Code

var myTestInjector =$injector.get('myTestInjector');
myTestInjector('Injected successfully');

Using injector you can inject services into any function you have using the injector's invoke method

Sample Code

var mySampleFunction = function (SomeVal) {
    //perform some task with SomeVal

6. Constant

You can create config provider using AngularJS module.config() function, Unfortunately you cannot inject values into the module.config() function but you can inject constants here.

Constants in AngularJS are defined using the module.constants() function.


var appModule = angular.module("EmpApp", []);
appModule.constant("configValue", "some constant config value");
myservices.config(function (mySecondServiceProvider, configValue) {

7. Controllers

You can inject things (i.e Service, method, value) into controllers but you can't inject controllers into things, reason controllers aren't created via the provider.


Angular App

var app= angular.module("EmpApp", []);

Angular Service

app.service("EmployeeService", function ($http) {
    // Get Employee data
    this.getEmployee = function () {
        return $http.get("/Home/GetAllEmployees");

Angular Controller injects Service

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    function GetAllEmployee() {
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees =;
        }, function () {
            alert('Employee data not found');

References used

1. Dependency injection article shared on website
2. Tutorial shared by

 धन्यवाद मित्रानो, आपला प्रत्येक दिवस आनंदी आणि सुखी जावो   

HTML Encode and Decode in web application

WebUtility.HtmlEncode and WebUtility.HtmlDecode


Previously I shared around six articles on security , in this article I am going to explain what is html encoding and how It prevent from xss attacks in web application and also I a am going to explain html decoding with sample example.


WebUtility.HtmlEncode Method converts a string to an HTML-encoded string.

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application.

WebUtility.HtmlEncode converts characters as follows,

=> The apostrophe character (‘) is converted to '
=> The less-than character (<) is converted to &lt;.
=> The greater-than character (>) is converted to &gt;.
=> The ampersand character (&) is converted to &amp;.
=> The double-quote character (") is converted to &quot;.

Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where is the ASCII character value.

HTML encode and Cross Site Scripting

What is XSS?

Cross Site Scripting (often abbreviated as XSS) when attacker uses web application send or injects malicious code like browser script, to different user. This malicious script executes and access user resources, trusted website data, website critical information. More info…

HTML encode used to prevent possible XSS attack?

Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

It prevents XSS (cross site scripting) attacks, means that if you are going to save some data In database that allow following script and you used WebUtility.HtmlEncode method to encode string in that case following actual string special characters (i.e “< “is converted to “&lt”) converted into safe plain string.

  In web environment this script will be rendered safely rather than actually executing script.

Actual Script:

<script type="text/javascript">
    function FetchSomeCriticlInfo() { /* some dangerous script code */ }

In this case, Server.HTMLEncode would encode the <, >, and " characters leaving this:

Encoded Script:

&lt;script type=&quot;text/javascript&quot;&gt;
    function FetchSomeCriticlInfo() { /* some dangerous script code*/ }



This script, if rendered in the browser will look like this


<script type="text/javascript"> function FetchSomeCriticlInfo() { /* some dangerous script code */ }



HTML Decode


WebUtility.HtmlDecode(String) Method converts a string that has been HTML-encoded for HTTP transmission into a decoded string.


HtmlDecode(String, TextWriter) overloaded method converts a string that has been HTML-encoded into a decoded string, and sends the decoded string to a TextWriter output stream.



Follwing address is encoded using WebUtility.HtmlEncode Method

Encoded Address:

Bill Address
Nagnath Kendre
Kendre&apos;s Villa,Kendrewadi


If I want to use this address into email or display to user I require to decode this &apos; string to actual character.


Following Address is Decoded using WebUtility.HtmlDecode Method

Decoded Address:

Bill Address
Nagnath Kendre
Kendres Villa,Kendrewadi


धन्यवाद मित्रानो !! Thanks  friends !!

Creating Dynamic HTML table using C#

Creating Dynamic HTML table using C# in Windows Form/Windows Service/Library Project

In this code example post I will explain how to create Dynamic HTML table using C# in Windows Form/Console Application/Windows Service/Windows Library project.

   For example, I want to send products detail email in proper html table format using existing C# generic Product list data. In following code example I will share code only to create dynamic html table and in next code example post I will share html table with email code.

C# Code

   public class DynamicHtmlTable
        //table tag constants
        private const string HtmlTableStart = "<table cellspacing=0 cellpadding=0 style=\"border-collapse:collapse; text-align:center;\">";
        private const string HtmlTableEnd = "</table>";
        private const string HtmlTrStart = "<tr>";
        private const string HtmlTrEnd = "</tr>";
        private const string HtmlThStart = "<th style=\" border-color:#5c87b2; border-style:solid;text-align:center;border-width:thin;\">";
        private const string HtmlThEnd = "</th>";
        private const string HtmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid;border-width:thin;\">";
        private const string HtmlTdEnd = "</td>";
        public void GetTableData()
            var Products=Dal.DAL.GetProducts();
            var EmailData = BuildDynamicTable(Products, "Dynmaic Html Table").ToString();
        //This method creates dynamic table
        private StringBuilder BuildDynamicTable(List<Product> Products,string appName)
            var DynamicTable = new StringBuilder();
            DynamicTable.AppendFormat("<h2>CodeChef4u Example To Create{0}</h2>", appName);
            //dynamic table
            //header row
            //table row
            foreach (var product in Products)
                CreateTableRow(product, DynamicTable);
            //Table ends
            return DynamicTable;
        //This method create table header row with columns names
        private static void CreateTableHeaderRow(StringBuilder DynamicTable)
            DynamicTable.AppendLine(HtmlThStart + "Name" + HtmlThEnd);
            DynamicTable.AppendLine(HtmlThStart + "Category" + HtmlThEnd);
            DynamicTable.AppendLine(HtmlThStart + "Price" + HtmlThEnd);
            DynamicTable.AppendLine(HtmlThStart + "Image URL" + HtmlThEnd);
         //This method create new table row with data
        private static void CreateTableRow(Product Product,
           StringBuilder emailDynamicTable)
            emailDynamicTable.AppendLine(HtmlTdStart + Product.ProductName + HtmlTdEnd);
            emailDynamicTable.AppendLine(HtmlTdStart + Product.CategoryId + HtmlTdEnd);
            emailDynamicTable.AppendLine(HtmlTdStart + Product.Price + HtmlTdEnd);
            emailDynamicTable.AppendLine(HtmlTdStart + Product.ImageUrl + HtmlTdEnd);