Wednesday, February 27, 2019

Post Request With XML Data To Web Server Using C#

This is how we post a request with XML Data to Web Server

public string PostServerRequest(string dataXML)
        {
            // Prepare web request to POST to server.
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(dataXML);
            HttpWebRequest myRequest =  (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServerURL"]);
            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data to server
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            WebResponse response = myRequest.GetResponse();
            var status = ((HttpWebResponse)response).StatusDescription;

            // Get the stream containing content returned by the server 
            newStream = response.GetResponseStream();// Open the stream using a StreamReader for easy access  
            StreamReader reader = new StreamReader(newStream);
            // Return the content  
            return reader.ReadToEnd();
        }

Optional Arguments in WHERE Clause

In the below SQL Query, we can see that how only not null arguments will be included in the Where Clause.


DECLARE @SOURCESYSTEM VARCHAR(50)=NULL;
DECLARE @ORDERID VARCHAR(50)='O1001';

SELECT * FROM TRANSACTIONS
WHERE
(@SOURCESYSTEM IS NULL OR SOURCESYSTEM = @SOURCESYSTEM) AND 
(@ORDERID IS NULL OR ORDERID = @ORDERID) 

Pagination In SQL and Equivalent LINQ Statement

Common paging approach on SQL Server 2012 is OFFSET / FETCH

declare @PageSize int = 10          --Number of rows per page
declare @PageNumber int = 2    --Which page we want to read

select * from Employee order by ID
OFFSET @PageSize * (@PageNumber - 1) ROWS
FETCH NEXT @PageSize ROWS ONLY;

Equivalent LINQ Query:

int PageSize=10;
int PageNumber = 2;

var selectedEmployeeList = Employees.skip( PageSize*(PageNumber -1) )
                                                                      .take(PageSize).ToList();

Saturday, February 23, 2019

Simple REST WCF Service.

Hi Everyone,
    Last week I was working on a requirement to build a Restful WCF service. The service will be consumed by any user over web. For communication the service will accept the XML data and return XML data as output.

    Here are the below steps I have performed to achieve the requirement. First we will build Restful WCF service and then we will pass the XML data to the WCF Service

Step 1: Create a WCF Service application in Visual Studio. Give a suitable name(for example WCFRESTAPI). The Service will have a interface called Contract and a class called Service. The interface will contain the declaration of methods, which will be exposed by the service. The Service class will implement the methods of the Contract.

Step 2: Decorate the method of Contract Class with the following attribute:

1. [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, Method = "POST",
UriTemplate = "InvokeRestApi", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
Student InvokeRestApi(Student data); [This is the method declaration, Student is a class defined by the programmer.]
2. [OperationContract]

Step 3:  Implement the method in your service class.

Step 4: Modify your Web Config File as below:
Add a endpoint with webHttpBinding binding and define the behavior of it. The XML is given below.

<system.serviceModel> 
    <services>
      <service name="WCFRESTAPI.Service1">
        <endpoint behaviorConfiguration="web" address="" binding="webHttpBinding" contract="WCFRESTAPI.IService1"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:60140/Service1"/>         
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">       
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors> 
  </system.serviceModel>

[Service1: Name of service class, IService1: Name of the contract interface]

Now run the service and test it using Postman application.

Below the code snippet is given.

Contract Interface: 

[ServiceContract]
    public interface IService1
    {
        [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", UriTemplate = "InvokeRestApi", 
            RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
        [OperationContract]
        Student InvokeRestApi(Student data);
    }

Service Class:

public class Service1 : IService1
    {
        public Student InvokeRestApi(Student data)
        {
            data.Description = "Data has been successfully saved. ";
            return data;
        }
    }

WebConfig File Changes:

<system.serviceModel>    
    <services>
      <service name="WCFRESTAPI.Service1">
        <endpoint behaviorConfiguration="web" address="" binding="webHttpBinding" contract="WCFRESTAPI.IService1">
</endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:60140/Service1"/>            
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">          
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>    
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

Postman Request:




Postman Response: