Monday, August 18, 2014

Working with AngularJS with Get/Post calls

Here is some code which will show how can we use get/post calls when working with AngularJS. For these code i assume that you are aware of some basic knowledge of AngularJS code and syntaxes. Also, for this examples i used WCF service as data source which returns expected results as i want for my use so you can change code or source of service as per your need.

(1) Get With Single Value : This function returns single string value.
HTML :  





AngularJS : 

var sample = function ($scope, $http) {
        $http({
            url: '/MyService.svc/DoWorkWithString'
        }).success(function (data) {
            $scope.stringResult = data.DoWorkWithStringResult;
        });
    };

(2) Get With List of values : This function returns list of Name & Count which are processed at UI and displayed to view.
HTML : 







AngularJS : 
var ListController = function($scope, $http) {
        var resultPromise = $http.get("MyService.svc/ListItems");
        resultPromise.success(function(data) {
            $scope.ListItems = data.ListItemsResult;
        });
    };

For the post operation, both function simply returns string value which could be any success/error message that we can pass to UI after completion of any
operation on posting.
(3) Post with single parameter : posts one valueHTML : 




Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTest', data: JSON.stringify($scope.idTest) }).success(function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

(4) Post with two parameter
HTML : 

Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTestTwo', data: JSON.stringify({"param1":"value1","param2":"value2"}) }).success (function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

So, That's it for AngularJS with Get/Post calls.

Thursday, August 14, 2014

Error : Operation 'Operation' of contract 'Contract' specifies multiple request body parameters to be serialized without any wrapper elements.

During working with WCF Service, multiple scenarios were there for me. I completed POST scenario with one argument which works fine for me. But, POST scenario with more than one argument leads me to following error 


"Operation 'Operation' of contract 'Contract'
specifies multiple request body parameters to be serialized without any wrapper
elements. 
At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped."

after some googling i got to know, "WCF doesn't support more than one parameter with bare body, if you need pass several parameters in one post method operation, then we need set the BodyStyle to Wrapped."

I added BodyStyle attribute to my contract to Wrapped help me out to working condition for my method.
Following are some links which i find useful for me for this error.
(1) Why cant I use two arguments in a WCF REST POST method?

(2) WCF Service Proxy throws exception when more than one parameter is used in [OperationContract] method

(3) WebInvokeAttribute.BodyStyle Property

(4) WebMessageBodyStyle Enumeration

Tuesday, August 12, 2014

Error : Cannot have two operations in the same contract with the same name.

Working with WCF Service implementation i came across error "Cannot have two operations in the same contract with the same name.". Following is some links that will demonstrate what is the reason behind this.

(1) Function Overloading in WCF

(2) Cannot have two operations in the same contract with the same name

(3) 2 methods with the same name

Friday, August 8, 2014

Simple WCF Application Call From Client End

Today, i am going to create simple WCF Web Service and consume same web service from client side.
(A) Steps to create new WCF Service
(1) Right Click on your solution --> Add --> New Project --> Select ASP.NET Web Application --> Give appropriate name like "REST"
(2) Above step will create new Web Application, you can remove master page and other pages included from newly created project
(3) Right Click on newly created project --> Add --> New Item --> Select "WCF Service" --> Give appropriate name like "MyService"
(4) Above step will add an interface named "IMyService" already implemented and one service with extension "MyService.svc"
(5) Remove existing code implemented in interface as well as in service.
(6) Add following line of code in interface
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
string DoWorkWithString();
- This is simple method we have declare which will return string on execute.
- WebInvoke requires "System.ServiceModel.Web" name space to be added as reference in your project
(7) Implement above method with following code in MyService.cs
public string DoWorkWithString()
{
    return "This is one test";
}

(8) After completion of above code, create virtual directory named "REST" and bind it with above project.

(9) To run with existing code from client end, you need to change serviceModel tag with following line of code in your Web.Config file. To do that, replace following line of code of serviceModel with your Web.Config tag.



(B) Steps to call WCF Service from client end
Now, you are done with your simple service implementation, you can now call above service from client end using following line of code to your html and it will prompt "This is one test".
$.ajax({
    url: 'http://localhost/REST/MyService.svc/DoWorkWithString',
    dataType: 'json',
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('Error occurred during operation');
    },
    success: function (data1) {
        alert(data1.DoWorkWithStringResult);
    }
});

(C) You can also following navigate to following links to do same.


(1) An Introduction to WCF

(2) Four Steps to Create First WCF Service For Beginners

(3) Consuming WCF / ASMX / REST service using JQuery
       

Monday, August 4, 2014

Error : Service data not get refresh in IE8 from Client Side

I face problem of Data not refresh from client side when we are working with IE. I found this problem while i am working with IE8 and above.

Problem is like, in my MVC Single Page Application, when we are fetching any data from client side for first time it will get data perfectly but subsequent call for same data or some back and forth to some other location give me previous unchanged data which are cached. But, after a bit of googling following line of code works for me and resolved my problem.



This line of code i put in "_layout.cshtml" header section and it works for me and then after it gives me refreshed data view.


The above line of code works fine for me and resolved my problem.