Collection in WCF Sevices in VB.NET
In this article, you will learn how to do collection in WCF Services.
Introduction: Collection in WCF. Collections is a way to store any objects in a structured fashion.
Collection class has following properties:
- Collections are defined in System.Collections Namespace.
- Most collection classes derive from the interfaces IEnumerable, IList,IDictionary and their generic equivalents.
In this article, I will explain:
- Collection in WCF]
- Concrete collection List<T>
- Interface IEnumerable<T>
- Convert Array at client side to collection.
Step 1: Open visual studio and click on file menu.
- Go to new -> project.
- New project dialog box will appear.
- Select WCF -> WCF Service Application.
- Give the name as you desire.
- Press ok as shown below on figure:
- Service1.svc.vb will be open.
Step 2: Go to solution explorer.
- open the Iservice1.vb.
- write a code like:
Code:
' Use a data contract as illustrated in the sample below to add composite types to service operations.
<DataContract()> _
Public Class Employee
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property Empid() As String
Get
Return m_Empid
End Get
Set(value As String)
m_Empid = Value
End Set
End Property
Private m_Empid As String
End Class
Step 3: Now, open the Service1.svc.vb.
Code:
' NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
List<Employee> lstEmployee = new List<Employee>();
public List<Employee> GetEmployees(string filter)
{
List<Employee> lstEmployee = null;
using (SqlConnection conn = new SqlConnection("server=.;database="vinit";uid="sa",pwd="wintellect"));
}
public void Add(Employee e)
{
lstEmployee.Add(e);
}
}
Step 4: Start Debugging by pressing F5.
Step 5: Open the visual studio and go to the file menu.
Step 6: Go to Solution Explorer.
-
Right click on 'References' and select 'Add Service Reference...'
-
'Add Service Reference' dialog box will appear.
-
Paste the address which is copied in step 4.
-
Press OK button.
Step 7: Write the code on 'Program.vb' as:
Code:
Private Shared Sub Main(args As String())
Dim obj As New ServiceReference1.Service1Client()
obj.Add(New ServiceReference1.Employee() With { _
Key .Name = "vinit", _
Key .Empid = "1" _
})
Dim lstEmployee As ServiceReference1.Employee() = obj.GetEmployees()
Console.Read()
End Sub