Search This Blog

Tuesday, November 14, 2017

Difference between WCF and ASP.NET Web Service

Here is the list that enlists and demystifies what’s the difference between these two services:

1. Web services use XMLSerializer which does not specify which fields or properties of the type are serialized into XML, while WCF uses DataContratSerializer that shows which fields or properties are serialized into XML. That’s why WCF is preferred over web services, as DataContratSerializer performs better than XMLSerializer.

2. Web services support only one protocol- HTTP and HTTPS during communication, but WCF supports more protocols like- HTTP, TCP and MSMQ that can be extended for comprehensive solution, reliable session and transactions. It signifies WCF is more adaptable to work together for variety of software
.
3. WCF offers much flexibility as web services can only be hosted in IIS, while WCF can be hosted in IIS, windows activation services, self hosting and Windows services.

4. WCF is excellent for building real-time applications because it’s more reliable, fast and robust as compared to the web services.

5. Web services perform far better than WCF services even when they both execute same actions.

6. ASP.NET web services don’t support duplex operations but WCF does.

7. When WCF development services are used, the hash table can be serialized, but not when using web services. Web services serialize only those collections that incorporate IEnumerable and ICollection.

8. Using service behavior classes, WCF supports multi-threading, but web services doesn’t.

9. In ASP.NET web services, SOAP messages are exchanged over HTTP, but WCF services can exchange the message using any format over any transport protocol. Though, SOAP is default format that WCF uses.

10. WCF services have timeouts by default that can be configured. In WCF services, if communication channel cannot be opened/ closed and there is no response within the time span, then WCF services get timed-out. Web services don’t have any such property.

WCF
ASP.NET Web Service
ServiceContract and OperationContract attributes are used for defining WCF service.
WebService and WebMethod attributes are used for defining web service.
Supports various protocols like HTTP, HTTPS, TCP, Named Pipes and MSMQ.
Supports only HTTP, HTTPS protocols.
Hosted in IIS, WAS (Windows Activation Service), Self-hosting, Windows Service.
Hosted only in IIS.
Supports security, reliable messaging, transaction and AJAX and REST supports.
Support security but is less secure as compared to WCF.
Supports DataContract serializer by using System.Runtime.Serialization.
Supports XML serializer by using System.Xml.Serialization.
Supports One-Way, Request-Response and Duplex service operations.
Supports One-Way and Request-Response service operations.
WCF are faster than Web Services.
Web Services are slower than WCF
Hash Table can be serialized.
Hash Table cannot be serialized. It can serializes only those collections which implement IEnumerable and ICollection.
Unhandled Exceptions does not return to the client as SOAP faults. WCF supports better exception handling by using FaultContract.
Unhandled Exceptions returns to the client as SOAP faults.
Supports XML, MTOM, Binary message encoding.
Supports XML and MTOM (Message Transmission Optimization Mechanism) message encoding.
Supports multi-threading by using ServiceBehaviour class.
Doesn’t support multi-threading.

Tuesday, November 7, 2017

Save List-item with Attachment- AngularJs/Sharepoint 2013

<input id="fileinput" type="file">
<input ng-click="saveAttachments($event)">
------------------------------------------------- 
 var maxFileSize = 5000000; //Set maximum file size value into a variable. 5 MB in bytes
    var fileName = []; // To keep track of uploaded file names
    var fileData = []; // Create an array to hold all the files
    var fileCount = 0; // To keep track on number of files uploaded into an array
    $scope.saveAttachments = function ($event) {
        //if (document.getElementById("fileinput").files.length === 0) {
        //    alert("Select a file!");
        //    return;
        //}
     
        //Getting the Target file
        var files = document.getElementById("fileinput").files;
        var file = files[0];
        if (files && file) {
            //Creating FileReader obj to read the uploaded file
            var reader = new FileReader();

            //Getting the File name
            fileName[fileCount] = file.name;
            reader.filename = file.name;

            //Getting the extention of the file
            var ext = file.name.match(/\.([^\.]+)$/)[1];

            //Getting the file size
            var fileSize = file.size;

            if (fileSize > maxFileSize)
                ext = 'sizeExceed';
            //var fileID = $(this).attr('id');

            //This is where the uploaded file will be read by
            reader.onload = function () {
                //Validating the uploaded file Format
                switch (ext) {
                    case 'jpg':
                    case 'png':
                    case 'pdf':
                    case 'jpeg':
                    case 'docx':
                    case 'doc':
                    case 'excel':
                    case 'xlsm':
                    case 'xls':
                    case 'xlsx':
                    case 'ods':
                    case 'zip':
                    case 'rar':
                        //Put the file data into an array
                        fileData[fileCount] = this.result;
                        var n = fileData[fileCount].indexOf(";base64,") + 8;

                        //To Get the base64 bytes, remove the first part of the dataurl and //this we need to feed to SharePoint
                        fileData[fileCount] = fileData[fileCount].substring(n);
                        fileCount++;
                        break;
                    case 'sizeExceed':
                        fileData[fileCount] = '';
                        fileName[fileCount] = '';
                        alert('File size exceeded');
                        break;
                    default:
                        fileData[fileCount] = '';
                        fileName[fileCount] = '';
                        alert('Invalid format');
                }
                var site = _spPageContextInfo.webAbsoluteUrl;
                $().SPServices({
                    operation: 'UpdateListItems',
                    async: false,
                    listName: 'ListName',
                    batchCmd: 'New',
                    webURL: site,
                    valuepairs: [[Column1, $scope.val], ["Column2", $scope.val1], ["Column3", $scope.val2],["Column4",$scope.val4]], 
                    completefunc: function (xData, Status) {
                        if (Status == 'success' && $(xData.responseXML).find('ErrorCode').text() == '0x00000000') {
                            currentitem = $(xData.responseXML).SPFilterNode("z:row").attr("ows_ID");
                             if (file) {
                                getFileBuffer(file).then(function (buffer) {
                                    var bytes = new Uint8Array(buffer);
                                    var content = new SP.Base64EncodedByteArray(); //base64 encoding
                                    for (var b = 0; b < bytes.length; b++) {
                                        content.append(bytes[b]);
                                    }

                                    $().SPServices({
                                        operation: "AddAttachment",
                                        listName: "'ListName'",
                                        listItemID: currentitem,
                                        fileName: file.name,
                                        webURL:site,
                                        attachment: content.toBase64String(),
                                        async: false,
                                        completefunc: function (xData, Status) {
                                            alert('file uploaded')
                                        }
                                    });

                                });

                             }
                            //alert('List item created with ID ' + currentitem);                          
                        } else alert('List item creation failed');
                    }
                });
           
            };

            reader.onabort = function () {
                alert("The upload was aborted.");
            };

            reader.onerror = function () {
                alert("An error occured while reading the file.");
            };
            reader.readAsDataURL(file);
        }
    }
    var getFileBuffer = function (file) {

        var deferred = $.Deferred();
        var reader = new FileReader();

        reader.onload = function (e) {
            deferred.resolve(e.target.result);
        }

        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }

        reader.readAsArrayBuffer(file);

        return deferred.promise();

    };

Friday, November 3, 2017

Sharepoint Accordin view in customList

<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="panel-group" id="accordion" style="padding-top:15px">
</div>
<script>

$(function () {
    setdata();
    $("#accordion-1").accordion({
        heightStyle: "Content",
        collapsible: true
    });
});

function setdata() {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', loadAccordianData);
}
   
 
function loadAccordianData() 
{
    var clientcontext = new SP.ClientContext();
    var web = clientcontext.get_web();
    var list = web.get_lists().getByTitle('AccordionList');
    listitems = list.getItems(SP.CamlQuery.createAllItemsQuery());
    clientcontext.load(listitems);
    clientcontext.executeQueryAsync(success, onQueryFailed);
   
}
function success() {
    //Get the  values     
    var c = 0;
    var listitemenumerator = listitems.getEnumerator();
    while (listitemenumerator.moveNext()) {
        var oItem = listitemenumerator.get_current();
        var headerContent = oItem.get_item('Title');
        var bodyContent = oItem.get_item('Description')
        c = c + 1;
        var stringVal = "<div class='panel panel-default'><div class='panel-heading'><h4 class='panel-title'><a data-toggle='collapse' data-parent='#accordion' href='#collapse" + c + "'>" + headerContent + "</a></h4></div><div id='collapse" + c + "' class='panel-collapse collapse in'><div class='panel-body'>" + bodyContent + "</div></div></div>";
        $('#accordion').append(stringVal);
    }
}
 
function onQueryFailed(sender, args) 
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); 
 </script>