Send (Pass) Array as parameter to WCF Service using C# and VB.Net in ASP.Net

seriverma
 
on May 21, 2021 11:12 PM
1478 Views

hi,

how to pass array in wcf service

I have to create a wcf service, which i have to provide a client to use it here he/she need to pass one array as well as some parameter in body to.

I am not able to understant how to pass both in method.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 22, 2021 05:18 AM

Hi seriverma,

Using the below article i have created the example.

Call (Consume) WCF Service (SVC) in ASP.Net Web Application using C# and VB.Net

HTML

Ids: <asp:TextBox runat="server" ID="txtIds" />
<br />
Country : <asp:TextBox runat="server" ID="txtCountry" />
<br />
<asp:Button Text="Search" runat="server" OnClick="OnSearch" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
        GridView1.DataSource = client.GetCustomers(new string[0], "").CustomersTable;
        GridView1.DataBind();
    }
}

protected void OnSearch(object sender, EventArgs e)
{
    ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
    GridView1.DataSource = client.GetCustomers(txtIds.Text.Trim().Split(','), txtCountry.Text.Trim()).CustomersTable;
    GridView1.DataBind();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim client As ServiceReference1.ServiceClient = New ServiceReference1.ServiceClient()
        GridView1.DataSource = client.GetCustomers(New String(-1) { }, "").CustomersTable
        GridView1.DataBind()
    End If
End Sub

Protected Sub OnSearch(ByVal sender As Object, ByVal e As EventArgs)
    Dim client As ServiceReference1.ServiceClient = New ServiceReference1.ServiceClient()
    GridView1.DataSource = client.GetCustomers(txtIds.Text.Trim().Split(","c), txtCountry.Text.Trim()).CustomersTable
    GridView1.DataBind()
End Sub

WCF Service

IService

C#

using System;
using System.Data;
using System.ServiceModel;
using System.Runtime.Serialization;

[ServiceContract]
public interface IService
{
    [OperationContract]
    CustomerData GetCustomers(string[] ids, string country);
}

[DataContract]
public class CustomerData
{
    public CustomerData()
    {
        this.CustomersTable = new DataTable("CustomersData");
    }

    [DataMember]
    public DataTable CustomersTable { get; set; }
}

VB.Net

Imports System
Imports System.Data
Imports System.ServiceModel
Imports System.Runtime.Serialization

<ServiceContract>
Interface IService
    <OperationContract>
    Function GetCustomers(ByVal ids As String(), ByVal country As String) As CustomerData
End Interface

<DataContract>
Public Class CustomerData
    Public Sub New()
        Me.CustomersTable = New DataTable("CustomersData")
    End Sub

    <DataMember>
    Public Property CustomersTable As DataTable
End Class

Service

C#

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.ServiceModel;
using System.Runtime.Serialization;

public class Service : IService
{
    public CustomerData GetCustomers(string[] ids, string country)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                string query = "SELECT CustomerId, Name, Country FROM Customers";
                if (ids.Length > 0)
                {
                    query += string.Format(" WHERE CustomerId IN ({0})", string.Join(",", ids));                    
                }
                if (!string.IsNullOrEmpty(country))
                {
                    query += string.Format(" OR Country LIKE '%{0}%'", country);
                }
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    CustomerData customers = new CustomerData();
                    sda.Fill(customers.CustomersTable);
                    return customers;
                }
            }
        }
    }
}

VB.Net

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.ServiceModel
Imports System.Runtime.Serialization

Public Class Service
    Inherits IService

    Public Function GetCustomers(ByVal ids As String(), ByVal country As String) As CustomerData
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As SqlConnection = New SqlConnection(constr)
            Using cmd As SqlCommand = New SqlCommand()
                Dim query As String = "SELECT CustomerId, Name, Country FROM Customers"
                If ids.Length > 0 Then
                    query += String.Format(" WHERE CustomerId IN ({0})", String.Join(",", ids))
                End If

                If Not String.IsNullOrEmpty(country) Then
                    query += String.Format(" OR Country LIKE '%{0}%'", country)
                End If

                cmd.CommandText = query
                Using sda As SqlDataAdapter = New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Dim customers As CustomerData = New CustomerData()
                    sda.Fill(customers.CustomersTable)
                    Return customers
                End Using
            End Using
        End Using
    End Function
End Class

Screenshot

seriverma
 
on May 25, 2021 12:01 AM

In class file

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "{ClientCode}/TTAddUKDividend?SAPersonCode={SAPersonCode}&SATaxYearCode={SATaxYearCode}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
SARestResponseInfo<SARestResponseBaseInfo> TTAddUKDividend(string ClientCode, int SAPersonCode, int SATaxYearCode, List<SADividendTranInfo> SADividendTranInfo);

in service file

public SARestResponseInfo<SARestResponseBaseInfo> TTAddUKDividend(string ClientCode, int SAPersonCode, int SATaxYearCode, List<SADividendTranInfo> SADividendTranInfo)
{
    Logger.EnterFunction();
    string AuthToken = string.Empty;
    SARestResponseInfo<SARestResponseBaseInfo> response = new SARestResponseInfo<SARestResponseBaseInfo>();
    try
    {
        IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
        AuthToken = woc.Headers["authtoken"];
        RestNomismaSAManager manager = new RestNomismaSAManager(ClientCode);
        response = manager.TTAddDividend(SAPersonCode, AuthToken, SATaxYearCode, SADividendTranInfo);
        return response;
    }
    catch (RestException ex)
    {
        Logger.Error(ex);
    }
    catch (Exception ex)
    {
        Logger.Error(ex);
    }
    Logger.LeaveFunction();
    return response;
}