Sunday, October 16, 2016

Top 10 new Features of ASP.net Core

1. Cross Platform Support:Windows,mac,linux
2. Open Source:
3. Project.json:
4. Appsettings.json:
5. Startup.cs:
6. Grunt, Gulp and Bower:
7. Dependency Injection:
8. Single Programming model for MVC and Web API:
9. wwwroot folder and Static files:
10. MVC Tag Helpers:

Monday, July 11, 2016

About Rest API

1. What is REST?
Representational state transfer(REST) is an abstraction of architecture of world wide web. REST is an architectural style to design networked application.REST makes communication between remote computers easy by using the simple HTTP protocol which support for CRUD (Create, Read, Update, and Delete) operations on the server.

2. Name some of the commonly used HTTP methods used in REST based architecture?
Below are the commonly used HTTP methods used in REST.

GET − Provides a read only access to a resource.
PUT − Used to update an existing resource.
DELETE − Ued to remove a resource.
POST − Used to create a new resource.
OPTIONS − Used to get the supported operations on a resource.


3. What is a Resource in REST?
The service has a base URI that represents whole set of resources
ex: CsharpStar.com/posts

The base uri can be qualified with an identifier specifying an individual resource
ex: CsharpStar.com/posts/1053
RESTful services are hierarchical, resources offered by one service can contain more service
REST uses various representations to represent a resource where text, JSON, XML. XML and JSON are the most popular representations of resources


4. Explain REST design principles
There are 5 design principles on REST.
REST Design Principles
You can read more on this here.


5. Explain different REST Architectural Goals
REST_Architectural_Goals

You can read detailed explanation on each goal here.


6. Which protocol is used by RESTful webservices ?
RESTful web services make use of HTTP protocol as a medium of communication between client and server.


7. What is messaging in RESTful webservices?
A client sends a message in form of a HTTP Request and server responds in form of a HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself.


8. What are the core components of a HTTP Request and HTTP Response?
There are 5 major components for HTTP Request.
Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
URI − Uniform Resource Identifier (URI) to identify the resource on server.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client ( or browser) type, format supported by client, format of message body, cache settings etc.
Request Body − Message content or Resource representation.

There are 4 major components for HTTP Response.
Status/Response Code − Indicate Server status for the requested resource. For example 404 means resource not found and 200 means response is ok.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Response Header − Contains metadata for the HTTP Response message as key-value pairs. For example, content length, content type, response date, server type etc.
Response Body − Response message content or Resource representation.


9. What is addressing in RESTful webservices?
Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person.


10. What is URI?
URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its URI.

Operations on the base URI affect the set of resources as a whole
1. GET lists them
2. POST adds a new resource to the set
3. DELETE deletes the whole set
4. PUT replaces the set with a new set

Operations on an ID-qualified URI affect an individual resource
1. GET retrieves it
2. DELETE destroys it
3. PUT replaces it or create if doesnot exists

11. What is the purpose of HTTP Verb in REST based webservices?
VERB identifies the operation to be performed on the resource.


12. What is statelessness in RESTful Webservices?
The communication between client and server must be stateless. This means that each request from a service consumer should contain all the necessary information for the service to understand the meaning of the request, and all session state data should then be returned to the service consumer at the end of each request


13. What are the advantages and disadvantages of statelessness in RESTful Webservices?
Advantages:

Web services can treat each method request independently.
Web services need not to maintain client’s previous interactions. It simplifies application design.
As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly with HTTP protocol
Disadvantages:

Web services need to get extra information in each request and then interpret to get the client’s state in case client interactions are to be taken care of.


14. What is the difference between PUT and POST operations?
PUT − Used to create a new resource and POST − Used to update a existing resource or create a new resource.

15. What should be the purpose of OPTIONS and HEAD method of RESTful web services?
OPTIONS : list down the supported operations in a web service and should be read only.
HEAD : return only HTTP Header, no Body and should be read only.

16. Explain different statemanagement principles in REST service?
REST State Management
You can read more on state management here.

17. What is caching?
Caching refers to storing server response in client itself so that a client needs not to make server request for same resource again and again. A server response should have information about how a caching is to be done so that a client caches response for a period of time or never caches the server response.


18. What is the purpose of HTTP Status Code?
HTTP Status code are standard codes and refers to predefined status of task done at server.

HTTP Status Code:

200 – OK, shows success.
201 – CREATED, when a resource is successful created using POST or PUT request. Return link to newly created resource using location header.
204 – NO CONTENT, when response body is empty
304 – NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET requests
400 – BAD REQUEST, states that invalid input is provided
401 – FORBIDDEN, states that user is not having access to method being used
404 – NOT FOUND, states that method is not available
409 – CONFLICT, states conflict situation while executing the method
500 – INTERNAL SERVER ERROR, states that server has thrown some exception while executing the method

19. Explain the REST Constraints
REST Constraints

Client-Server:
Cache:
Stateless:
Uniform Contract:
Layered System:
Code-On-Demand:

20. Difference between SOAP and REST services
REST is simpler to program than SOAP
Retrieval consists of a URL(GET)
Creation consists of a URL(POST)
Update and Delete also simple (PUT,DELETE)
SOAP semantics are opaque, so it bypasses the features of layered internet
REST is lightweight on the client side
you need to write a little bit of script codeand you are off and running
Javascript frameworks make it browser independent and easy to integrate
REST is lightweight in server side
you need to write a little bit of script codeand you are off and running
Frameworks support the web servers

Friday, July 1, 2016

pass data from one controller to another controller using $rootScope in angularjs

<html>
<head>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>
    <script>
        var app = angular.module('MyApp', []);
        app.controller('ParentCtrl',
        function ParentCtrl($scope, $rootScope) {
            $scope.Parents = "Parent Controller";
            $scope.go = function () {
                $rootScope.$broadcast('parent', $scope.Parents)
            }
        });
        app.controller('SiblingCtrl',
        function SiblingCtrl($scope, $rootScope) {
            $scope.Childs = "Child Controller";
            $rootScope.$on('parent', function (event, data) {
                alert(data);
                $scope.transdata = data + " parent";
            });
        });

    </script>
    <div ng-app="MyApp">
        <div ng-controller="ParentCtrl">
            {{Parents}}
            <button ng-click="go()">Button </button>
            <div ng-controller="SiblingCtrl">
                {{Childs}}
                {{transdata}}
            </div>
        </div>
    </div>
</body>
</html>


pass data from one controller to another controller using $scope in angularjs

Understanding Angular’s $scope event system with $broadcast and $on


$broadcast — dispatches the event downwards to all child scopes,
$emit — dispatches the event upwards through the scope hierarchy.

<html>
<head>
    <script src="Scripts/angular.min.js"></script>
   
</head>
<body>
    <script>
        var app = angular.module('sathya', []);
        app.controller('ParentCtrl',
        function ParentCtrl($scope) {
         
            $scope.g = "Parent Controller";
            $scope.go = function () {
                $scope.$broadcast('parent', $scope.g)

            }

        });

        app.controller('SiblingCtrl',
        function SiblingCtrl($scope) {
            $scope.g1 = "Child Controller";
            $scope.$on('parent', function (event, data) {            
                $scope.h = data+" parent";
            });

        });


    </script>
    <div ng-app="sathya">
        <div ng-controller="ParentCtrl">
            {{g}}
            <button ng-click="go()">Button </button>
            <div ng-controller="SiblingCtrl">
                {{g1}}
                {{h}}
            </div>
        </div>
    </div>
</body>
</html>

Friday, May 20, 2016

Enable Attribute routing

  1. public class RouteConfig
  2. {
  3. public static void RegisterRoutes(RouteCollection routes)
  4. {
  5. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  6.  
  7. //enabling attribute routing
  8. routes.MapMvcAttributeRoutes();
  9. }
  10. }

How to prevent F12 on webpage?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>


<script>
    $(document).keydown(function (event) {
        if (event.keyCode == 123) {
            return false;
        }
        else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) {
            return false;
        }
    });

    $(document).on("contextmenu"function (e) {
        e.preventDefault();
    });
</script>

Tuesday, March 8, 2016

Create Insert script in sql



--sp_CreateInsertScript 'ntrp.tblreceiptpurposemaster','PurposeStatusId=556',1
CREATE  PROC  procCreateInsertScript (
    @tablename NVARCHAR(256) -- table name
    ,@con NVARCHAR(400) -- condition to filter data
    ,@ignoreIdentityCol bit=0 --indicate if ignore columne with identity
    )
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @sqlstr NVARCHAR(MAX);
    DECLARE @valueStr1 NVARCHAR(MAX);
    DECLARE @colsStr NVARCHAR(MAX);
    SELECT @sqlstr='SELECT ''INSERT '+@tablename;
    SELECT @valueStr1='';
    SELECT @colsStr='(';
    SELECT @valueStr1='VALUES (''+';

    IF RTRIM(LTRIM(@con))=''
        SET @con='1=1';

    SELECT @valueStr1=@valueStr1+col+'+'',''+'
            ,@colsStr=@colsStr+name +','
    FROM (
            SELECT
                        CASE
                        /* xtype=173 'binary'*/WHEN a.xtype =173 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR('+CONVERT(NVARCHAR(4),a.length*2+2)+'),'+a.name +')'+' END'
                        /*xtype=104 'bit'*/WHEN a.xtype =104 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(1),'+a.name +')'+' END'
                        /*xtype=175 'char'*/WHEN a.xtype =175 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'REPLACE('+a.name+','''''''','''''''''''')' + '+'''''''''+' END'
                        /*xtype=61 'datetime'*/WHEN a.xtype =61 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'CONVERT(NVARCHAR(23),'+a.name +',121)'+ '+'''''''''+' END'
                        /*xtype=106 'decimal'*/WHEN a.xtype =106 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR('+CONVERT(NVARCHAR(4),a.xprec+2)+'),'+a.name +')'+' END'
                        /*xtype=62 'float' */WHEN a.xtype =62 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(23),'+a.name +',2)'+' END'
                        /*xtype=56 'int'*/WHEN a.xtype =56 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(11),'+a.name +')'+' END'
                        /*xtype=60 'money'*/WHEN a.xtype =60 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(22),'+a.name +')'+' END'
                        /*xtype=239 'nchar'*/WHEN a.xtype =239 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'REPLACE('+a.name+','''''''','''''''''''')' + '+'''''''''+' END'
                        /*xtype=108 'numeric'*/WHEN a.xtype =108 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR('+CONVERT(NVARCHAR(4),a.xprec+2)+'),'+a.name +')'+' END'
                        /*xtype=231 'nvarchar'*/WHEN a.xtype =231 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'REPLACE('+a.name+','''''''','''''''''''')' + '+'''''''''+' END'
                        /*xtype=59 'real'*/WHEN a.xtype =59 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(23),'+a.name +',2)'+' END'
                        /*xtype=58 'smalldatetime'*/WHEN a.xtype =58 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'CONVERT(NVARCHAR(23),'+a.name +',121)'+ '+'''''''''+' END'
                        /*xtype=52 'smallint'*/WHEN a.xtype =52 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(12),'+a.name +')'+' END'
                        /* xtype=122 'smallmoney'*/WHEN a.xtype =122 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(22),'+a.name +')'+' END'
                        /*xtype=127 'bigint'*/WHEN a.xtype =127 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(6),'+a.name +')'+' END'
                        /*xtype=48 'tinyint'*/WHEN a.xtype =48 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR(6),'+a.name +')'+' END'
                        /*xtype=165 'varbinary'*/WHEN a.xtype =165 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'CONVERT(NVARCHAR('+CONVERT(NVARCHAR(4),a.length*2+2)+'),'+a.name +')'+' END'
                        /*xtype=167 'varchar'*/WHEN a.xtype =167 THEN 'CASE WHEN '+a.name+' is null THEN ''NULL'' ELSE '+'''N''''''+'+'REPLACE('+a.name+','''''''','''''''''''')' + '+'''''''''+' END'
                        ELSE '''NULL'''
                        END    AS col
                ,a.colid
                ,a.name
            FROM syscolumns a
            WHERE a.id = object_id(@tablename)
            and a.xtype <>189 and a.xtype <>34 and a.xtype <>35 and a.xtype <>36
            and (columnproperty(a.id, a.name, 'IsIdentity') = 0 OR @ignoreIdentityCol=0)
            ) AS t
    ORDER BY colid;

    SELECT @sqlstr=@sqlstr+left(@colsStr,len(@colsStr)-1)+') '+left(@valueStr1,len(@valueStr1)-3)+')'' AS sql FROM '+@tablename +  ' WHERE 1=1 AND  ' + isnull(@con,'1=1');
    PRINT @sqlstr;
    EXEC( @sqlstr);
    SET NOCOUNT OFF
END

How to hash your binary data that exceed the limit (8000bytes) of input parameter of HASHBYTES in Sql

Introduction

Some times, we store binary data in database and need to hash them in order to get an identifier of the binary data. We know the Sql server has a built-in function to do that, it's HASHBYTES. But it's allowed input values are limited to 8000 bytes. Then how to hash the binary data that exceed 8000 bytes? We know Sql Server can be extended with CLR. Here there are mainly two hash algorithms: MD5 and SHA1. Now let us get started.
Background

You should know the  knowledges on C#, Sql, SHA1, MD5
Using the code

1. In Visual Studio 2015, create a Sql Server Database Project.

2. Add a file with template Sql CLR C# User Dfined Function

3. Add the SHA1 and MD5 method as below in your .cs file

The  C# method code lines of hash binary data using SHA1:
Hide   Shrink   Copy Code

/// <summary>
///  Encrypt data with type [varbinary](max) in sql server using SHA1 then return the encrypted data
/// </summary>
/// <param name="content">Input data you will enterd to encrypt it</param>
/// <returns>Return the encrypted text as hexadecimal string</returns>
[SqlFunction(DataAccess = DataAccessKind.None)]
public static String ComputeSHA1(SqlBytes content)
{
    String hashSHA1 = String.Empty;
    //Create new instance of SHA1 and convert the input data to array of bytes
    SHA1 calculator = SHA1.Create();
    Byte[] buffer = calculator.ComputeHash(content.Stream);
    calculator.Clear();

    //loop for each byte, convert it to hexadecimal string and add it to StringBuilder
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < buffer.Length; i++)
    {
        stringBuilder.Append(buffer[i].ToString("x2"));
    }
    hashSHA1 = stringBuilder.ToString();

    // return hexadecimal string
    return hashSHA1;
}

The  C# method code lines of hash binary data using MD5:


/// <summary>
///  Encrypt data with type [varbinary](max) in sql server using MD5 then return the encrypted data
/// </summary>
/// <param name="content">Input data you will enterd to encrypt it</param>
/// <returns>Return the encrypted text as hexadecimal string</returns>
[SqlFunction(DataAccess = DataAccessKind.None)]
public static String ComputeMD5(SqlBytes content)
{
    String hashMD5 = String.Empty;

    //Create new instance of md5 and convert the input data to array of bytes
    MD5 calculator = MD5.Create();
    Byte[] buffer = calculator.ComputeHash(content.Stream);
    calculator.Clear();

    //loop for each byte, convert it to hexadecimal string and add it to StringBuilder
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < buffer.Length; i++)
    {
        stringBuilder.Append(buffer[i].ToString("x2"));
    }
    hashMD5 = stringBuilder.ToString();

    //return hexadecimal string
    return hashMD5;
}

4. build your project and you will get a dll file in bin directory.

5. Publish your assembly file into your Sql Server database. There are two ways to do this.

    Use the publish tool provided by visual studio. You can generate script file and use the script file to pulish or directly publish it into your database.

    Manually register assembly into your database using Transact-SQL

First, you should ensure to enable CLR in your database. If not, execute the following sql


EXEC sp_configure 'clr enabled',1
go
RECONFIGURE
go

Use this sql to register your assembly as below:


CREATE ASSEMBLY [hashassembly]
    AUTHORIZATION [dbo]
    FROM 'c:\hashassembly.dll' WITH PERMISSION_SET = SAFE;

Create sql functions in your database using the following sql


CREATE FUNCTION [dbo].[ComputeMD5]
(@content VARBINARY (MAX))
RETURNS NVARCHAR (40)
AS
 EXTERNAL NAME [hashassembly].[UserDefinedFunctions].[ComputeMD5]

GO

CREATE FUNCTION [dbo].[ComputeSHA1]
(@content VARBINARY (MAX))
RETURNS NVARCHAR (40)
AS
 EXTERNAL NAME [hashassembly].[UserDefinedFunctions].[ComputeSHA1]

So far, we have finished deploying your assembly into you database, you can call the sql function to use it generate your hash value. For example:


UPDATE [dbo].[Picture]
   SET [HashKey] = dbo.ComputeSHA1([PictureBinary])

Monday, February 22, 2016

DateTime Formatting

DateTime Formatting


DateTime is a structureof value Type like int, double etc. It is available in System namespace and present in mscorlib.dll assembly. It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable.

Different users need different kind format date. For instance some users need date like "mm/dd/yyyy", some need "dd-mm-yyyy". So below specifiers will help you to get date in different formats. Let's say current Date Time is "12/8/2015 3:15:19 PM" and as per that you will get output based on specifier.



Specifier Description Output
d Short Date 12/8/2015
D Long Date Tuesday, December 08, 2015
t Short Time 3:15 PM
T Long Time 3:15:19 PM
f Full date and time Tuesday, December 08, 2015 3:15 PM
F Full date and time (long) Tuesday, December 08, 2015 3:15:19 PM
g Default date and time 12/8/2015 15:15
G Default date and time (long) 12/8/2015 15:15
M Day / Month 8-Dec
r RFC1123 date Tue, 08 Dec 2015 15:15:19 GMT
s Sortable date/time 2015-12-08T15:15:19
u Universal time, local timezone 2015-12-08 15:15:19Z
Y Month / Year December, 2015
dd Day 8
ddd Short Day Name Tue
dddd Full Day Name Tuesday
hh 2 digit hour 3
HH 2 digit hour (24 hour) 15
mm 2 digit minute 15
MM Month 12
MMM Short Month name Dec
MMMM Month name December
ss seconds 19
fff milliseconds 120
FFF milliseconds without trailing zero 12
tt AM/PM PM
yy 2 digit year 15
yyyy 4 digit year 2015
: Hours, minutes, seconds separator, e.g. {0:hh:mm:ss} 9:08:59
/ Year, month , day separator, e.g. {0:dd/MM/yyyy} 8/4/2007

Monday, February 15, 2016

Fiscal management far better this year than earlier: CGA

Fiscal management far better this year than earlier: CGA: he government’s fiscal management this financial year has been better than the previous years with expenditure being spread out as opposed to the usual bunching up toward the end of the year, accordin

Thursday, February 11, 2016

Diff Between factory an service in Angular js?

1). Factories are functions that return the object, while services are constructor functions of the object which are instantiated with the new keyword.


angular.module('app').factory('SomeService', function() { return { someFunction: function() {} }; });


angular.module('app').service('SomeService', function() { this.someFunction = function() {}; });