This sample show that how to create a WCF Application which produces a JSON string which is used by IPhone device.
For this Create a WCF Service Application in Visual Studio.
Here you will find IService1.cs and Service1.svc Files.
In IService1.cs define ServiceContract and DataContract.
ServiceContract is used for write WebGet Attribute contain Uri Template which is used for getting the service Url.
DataContract is used for a formal agreement between a service and a client that abstractly describes the data to be exchanged. In this we will define DataMember.
In Service1.cs is used for defining methods and functions.
This is the Code for IService1.cs Interface:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Collections.ObjectModel;
namespace GlobalGem
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/GetCalendarioCorsi?pageIndex={pageIndex}&limit={limit}")]
string GetCalendarioCorsi(int pageIndex,int limit);
}
[DataContract]
public class CalendarioCorsiData
{
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public String Year { get; set; }
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public List<string> Months { get; set; }
}
}
This is the Code for Service1.cs Service:-
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Data;
using System.Web;
namespace GlobalGem
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public void ErrorLog(string sErrMsg)
{
StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("Log.txt"), true);
sw.WriteLine(sErrMsg + DateTime.Now.ToString());
sw.Flush();
sw.Close();
}
public String GetCalendarioCorsi(int pageIndex, int limit)
{
StringBuilder json = new StringBuilder();
try
{
List<CalendarioCorsiData> list = Common.GetCalendarioCorsi(pageIndex, limit);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<CalendarioCorsiData>));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, list);
json.Append(Encoding.UTF8.GetString(ms.ToArray()));
ms.Close();
}
catch (Exception ex)
{
ErrorLog(ex.Message);
}
return json.ToString();
}
}
}
This is the Code for Business logic Class:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Configuration;
namespace GlobalGem
{
public class Common
{
public static List<CalendarioCorsiData> GetCalendarioCorsi(int pageIndex, int limit)
{
List<CalendarioCorsiData> lstCalendario = new List<CalendarioCorsiData>();
DataTable dt = new DataTable();
string query = "Select * from Table1";
OleDbConnection conn = new OleDbConnection();
conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
da.Fill(dt);
int index = 0;
List<String> months = new List<String>(); ;
for (index = 0; index < dt.Rows.Count; index++)
{
string upComingYear = "";
string presentYear = dt.Rows[index]["Year"].ToString();
if (index + 1 < dt.Rows.Count)
{
upComingYear = dt.Rows[index + 1]["Year"].ToString();
if (upComingYear != presentYear)
{
months.Add(dt.Rows[index]["Month"].ToString());
Common.AddCourseCalendarData(lstCalendario, months, presentYear);
months = new List<String>();
}
else
{
months.Add(dt.Rows[index]["Month"].ToString());
}
}
else
{
months.Add(dt.Rows[index]["Month"].ToString());
Common.AddCourseCalendarData(lstCalendario, months, presentYear);
}
}
return lstCalendario;
}
public static List<CalendarioCorsiData> GetCourseInformation(int courseId)
{
List<CalendarioCorsiData> lstCalendario = new List<CalendarioCorsiData>();
OleDbConnection conn = null;
DataTable dt = new DataTable();
string query = "Select * from Table1 where CourseId=" + courseId + "";
conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
CalendarioCorsiData data = new CalendarioCorsiData();
data.CourseId = Convert.ToInt32(dr["CourseId"]);
data.StartingDate = dr["StartDate"].ToString();
data.EndingDate = dr["EndDate"].ToString();
data.Cost = dr["Price"].ToString();
data.Prepares = dr["Prepares"].ToString();
data.Facing = dr["Facing"].ToString();
data.Prerequisites = dr["Prerequisites"].ToString();
data.Scheduled = dr["Scheduled"].ToString();
data.Home = dr["Home"].ToString();
data.AdditionalDetails = dr["AdditionalDetails"].ToString();
data.Description = dr["Description"].ToString();
lstCalendario.Add(data);
}
return lstCalendario;
}
}
}
Make these changes in Web.Config file:-
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="GlobalGem.Service1" behaviorConfiguration="GlobalGem.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding" contract="GlobalGem.IService1" behaviorConfiguration="WebHttpBehavior">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="GlobalGem.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebHttpBehavior">
<!--<enableWebScript />-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
After all of this stuff run the application and paste your UriTemplate path after your service path. In this example after running the application we get this path "http://localhost:2990/Service1.svc" and then we paste the UriTemplate after that "http://localhost:2990/Service1.svc/GetCalendarioCorsi?pageIndex=10&limit=10 " and then we get the JSON string from it.
If you want any suggestions please send us comments as feedback.
No comments:
Post a Comment