Creating WCF web service in C#.net using Visual studio 2012
===========================================================
Factor file: advance level- Get method -
-------------------------------------------------
Iservice1.cs --->Interface file
Service1.svc.cs --->service file
Web.Config .XML --->configuration file.
IService1.cs
---------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method="GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "logincheck/{pas}")]
string DoWork(string pas);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "userInfo/{UserName}/{Password}/{Country}/{Email}")]
string InsertUserDetails(string UserName,string Password,string Country,string Email);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "selectuserInfo/{username}")]
string getUser(string username);
// TODO: Add your service operations here
[OperationContract(Name = "postmethod")]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "postmethod/new")]
void CreateBooking(Booking booking);
}
[DataContract]
public class UserDetails
{
string username = string.Empty;
string password = string.Empty;
string country = string.Empty;
string email = string.Empty;
[DataMember]
public string UserName
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Country
{
get { return country; }
set { country = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class Booking
{
[DataMember]
public int BookingID { get; set; }
[DataMember]
public string BookingName { get; set; }
//[DataMember]
//public DateTime BookingStart { get; set; }
//[DataMember]
//public DateTime BookingEnd { get; set; }
[DataMember]
public int RoomID { get; set; }
}
}
===========================================================
Factor file: advance level- Get method -
-------------------------------------------------
Iservice1.cs --->Interface file
Service1.svc.cs --->service file
Web.Config .XML --->configuration file.
IService1.cs
---------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method="GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "logincheck/{pas}")]
string DoWork(string pas);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "userInfo/{UserName}/{Password}/{Country}/{Email}")]
string InsertUserDetails(string UserName,string Password,string Country,string Email);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "selectuserInfo/{username}")]
string getUser(string username);
// TODO: Add your service operations here
[OperationContract(Name = "postmethod")]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "postmethod/new")]
void CreateBooking(Booking booking);
}
[DataContract]
public class UserDetails
{
string username = string.Empty;
string password = string.Empty;
string country = string.Empty;
string email = string.Empty;
[DataMember]
public string UserName
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Country
{
get { return country; }
set { country = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class Booking
{
[DataMember]
public int BookingID { get; set; }
[DataMember]
public string BookingName { get; set; }
//[DataMember]
//public DateTime BookingStart { get; set; }
//[DataMember]
//public DateTime BookingEnd { get; set; }
[DataMember]
public int RoomID { get; set; }
}
}
----------------------------------------------------------------------------------------------------------
Service1.svc.cs
================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
Dictionary<string, string> dict = new Dictionary<string, string>();
public string DoWork(String msg)
{
return msg;
}
public void CreateBooking(Booking book)
{
//var newbooking = new Booking();
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString))
{
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText =
"insert into RegistrationTable(UserName, Password,Country,Email) values(@UserName, @Password,@Country,@Email)";
cmd.Parameters.AddWithValue("@UserName", book.UserName);
cmd.Parameters.AddWithValue("@Password",book.Password);
cmd.Parameters.AddWithValue("@Country", book.Country);
cmd.Parameters.AddWithValue("@Email", book.Email);
cmd.ExecuteNonQuery();
}
}
}
public string InsertUserDetails(string UserName, string Password, string Country, string Email)
{
string Message;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("webserviceinsert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", UserName);
cmd.Parameters.AddWithValue("@Password", Password);
cmd.Parameters.AddWithValue("@Country", Country);
cmd.Parameters.AddWithValue("@Email", Email);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message =UserName + " Details inserted successfully ";
}
else
{
Message = UserName + " Details not inserted successfully ";
}
con.Close();
return Message;
}
public string getUser(string username)
{
//string Message; string dd;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM RegistrationTable";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
try{
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
if (reader.HasRows)
{
while (reader.Read())
{
dict.Add("UserName", reader["UserName"].ToString().Trim());
dict.Add("Password", reader["Password"].ToString().Trim());
dict.Add("Country", reader["Country"].ToString().Trim());
dict.Add("Email", reader["Email"].ToString().Trim());
break;
}
}
}
catch (Exception ex)
{
dict.Add("cmnt", "my" + ex.Message.ToString());
// return new JavaScriptSerializer().Serialize(dict);
}
con.Close();
return new JavaScriptSerializer().Serialize(dict);
}
}
}
------------------------------------------------------------------------------------------------------
Web.Config XML file
----------------------
<?xml version="1.0"?>
<configuration>
<!--Connection string-->
<connectionStrings>
<add name="Dbcon" connectionString="Data Source=Test;User Id=sa;Password=Kaspon123;Integrated Security=true"></add>
<add name="Mycon" connectionString="Server=GANAPATHI-PC;Database=Test;User Id=sa; password=Kaspon123" providerName="System.Data.SqlClient"></add>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows" />
<httpRuntime requestValidationMode="2.0" />
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1">
<!-- Service Endpoints -->
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WcfService1.IService1"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<!--<endpoint address="" behaviorConfiguration="web" binding="customBinding" bindingConfiguration="CustomMapper" contract="Adpservice.IAdpService"/>-->
</service>
</services>
<!-- behaviors start -->
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WcfService1">
<!-- To avoid disclosing metadata information, set the values below to false 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="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!-- behaviors end -->
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
No comments:
Post a Comment