Not getting service result in Json Format? - c#

IService.cs
//it is working fine with Xml
[OperationContract]
[WebGet(UriTemplate = "/PrintProductCategory",RequestFormat=WebMessageFormat.Xml,ResponseFormat = WebMessageFormat.Xml)]
List<ProductCategory> GetProductCategory();
//it is not working with Json
[OperationContract]
[WebGet(UriTemplate = "/Print",RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
List<ProductCategory> GetProductCategory();
Service.cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
<buildProviders>
<add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />
</buildProviders>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="IService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="ARserviceEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=GOVINDA-PC;initial catalog=ARservice;persist security info=True;user id=sa;password=sa_12345;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Explanation :
Here my rest service working fine with XML.But when i am using ResponseFormat = WebMessageFormat.Json then i am getting error on webpage is that No data recived.
But it is workig fine with XML.so please help for this problem where i am doing mistake.

You could try using fiddler to actually see what is going on HTTP-traffic-wise. See http://fiddler2.com/.

I had this working on one of my recent projects, just checked my config and I can't see anything obviously different with yours. Only thing I can see that’s different (bit of a long shot) is that I’ve specified the [WebGet] attribute on the concrete class implementation, and used [WebInvoke]
So IService.cs would become..
[OperationContract]
List<ProductCategory> GetProductCategory();
and Service.cs would be..
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
[WebInvoke(UriTemplate = "/Print", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
Can't see why it would make a difference, but might be worth trying!

I could that what is problem in my case.
IService.cs
[OperationContract]
[WebGet(UriTemplate = "/Print",RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
List<ProductCategory> GetProductCategory();
Service.cs :
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
And my XML File was also right.
What was the problem :
problem was that i was using of .EDMX for database.
Solution
I Just use .dbml for database.And I Could solve my problem.
Remark :
Whenever you are making WCF Service in visual studio 2010 then use .dbml instead of .edmx. if you want to retrieve result in json or xmlformat.
If Someone is fencing like my problem so they can try this answer.
I hope it will help someone.

Related

Wcf System.ServiceModel.ProtocolException: 'The remote server returned an unexpected response: (400) Bad Request.'

I'm trying to test my WCF service ıt is include methods create,update,getlist to Sql Server vs. .It works GET method on browser but i want to test POST method on Console app.So i service reference its to console app.I get this error ;
System.ServiceModel.ProtocolException: 'The remote server returned an unexpected response: (400) Bad Request.'
Inner Exception
WebException: The remote server returned an error: (400) Bad Request
EDIT!!
ERROR:
System.ServiceModel.ProtocolException: The remote server returned an unexpected response: (405) Method Not Allowed. ---> System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WSTester.WorkWS.IService1.GetCustomerList()
at WSTester.WorkWS.Service1Client.GetCustomerList() in C:\Users\aykut\source\repos\Work\WSTester\Connected Services\WorkWS\Reference.cs:line 291
at WSTester.Program.Main(String[] args) in C:\Users\aykut\source\repos\Work\WSTester\Program.cs:line 47
Thanx for advice.
This is my App.config in Console APP
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
maxReceivedMessageSize="1048576"/>
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://192.168.0.XX:7767/Service1.svc"
binding="webHttpBinding"
contract="WorkWS.IService1" behaviorConfiguration="webhttp" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="webhttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
And here is my Web.config in WebService:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
<property name="connection.connection_string">Data Source=.\SQLEXPRESS;;Initial Catalog=FirstProject; User Id = aykut ; password= 1234</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="HBM_ASSEMBLY" value="BusinessEntities" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<identity impersonate="false" />
<authentication mode="Forms" />
</system.web>
<system.serviceModel>
<services>
<service name="WebService.Service1">
<endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="WebService.IService1" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- Meta veri bilgilerini açığa çıkarmaktan kaçınmak için, dağıtımdan önce aşağıdaki bilgileri false yapın -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- Hatalarda hata ayıklamak amacıyla özel durum ayrıntıları almak için aşağıdaki değeri true yapın. Özel durum bilgilerini açığa çıkarmaktan kaçınmak için dağıtımdan önce false yapın -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</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>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Iesi.Collections" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
And here is the my main method;
static void Main(string[] args)
{
Service1Client client = new Service1Client();
Customer c = new Customer();
c.Name = "dsfsfsdf";
c.SurName="asdass";
c.Age = 12;
client.CreateCustomer(c);
}
EDIT!!
This is my Service1.svc:
public class Service1 : IService1
{
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetCustomerList")]
public List<Customer> GetCustomerList()
{
CustomerFinder cm = new CustomerFinder();
List<Customer> customerlist = cm.GetAllCustomers();
return customerlist;
}
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetCustomerByID/{id}")]
public Customer GetCustomerByID(string id)
{
CustomerFinder cm = new CustomerFinder();
Customer customer = cm.FindByID(Int32.Parse(id));
return customer;
}
[WebInvoke(Method = "POST",
UriTemplate = "CreateCustomer",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public Customer CreateCustomer(Customer customer)
{
if (customer == null)
{
throw new ArgumentNullException("FAIL");
}
CustomerManager cm = new CustomerManager();
cm.CreateCustomer(customer);
return customer;
}
}
This is IService:
public interface IService1
{
[OperationContract]
List<Customer> GetCustomerList();
[OperationContract]
Customer GetCustomerByID(string id);
[OperationContract]
Customer CreateCustomer(Customer customer);
[OperationContract]
void DeleteCustomerByID(string id);
}
}
And this is my CreateCustomer method:
public class CustomerManager : BusinessComponentBase
{
public Customer CreateCustomer(Customer customer)
{
ISession session = this.GetSession();
using (var tx = session.BeginTransaction())
{
try
{
this.GetSession().Save(customer);
this.GetSession().Save(customer.Addresses);
tx.Commit();
}
catch
{
tx.Rollback();
}
}
return customer;
}
I find the solution..Problem is on CreateCustomer method. When i implement to my tables on sql server addresses can not be null and they already mapped so do not need for Save(customer.Addresses) this way;
public Customer CreateCustomer(Customer customer)
{
ISession session = this.GetSession();
using (var tx = session.BeginTransaction())
{
try
{
this.GetSession().Save(customer);
tx.Commit();
}
catch(Exception e)
{
tx.Rollback();
}
}
return customer;
}

WCF Service Method is not Working

I am currently working on wcf service and Service is running localhost.I have some methods in Wcf Service. I am facing some Errors when I want to access the method from localhost by typing for example http://localhost:50028/StudentService.svc/GetAllStudent/
its shows following errors.
**
Request Error
The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.
**
Here is my code form Wcf service....
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudent/")]
List<StudentDataContract> GetAllStudent();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetStudentDetails/{StudentId}")]
StudentDataContract GetStudentDetails(string StudentId);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/AddNewStudent")]
bool AddNewStudent(StudentDataContract student);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/UpdateStudent")]
void UpdateStudent(StudentDataContract contact);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteStudent/{StudentId}")]
void DeleteStudent(string StudentId);
}
}
Here is my code of Implementation ...
public class StudentService : IStudentService
{
StudentManagementEntities ctx;
public StudentService()
{
ctx = new StudentManagementEntities();
}
public List<StudentDataContract> GetAllStudent()
{
//if (HttpContext.Current.Request.HttpMethod == "GetAllStudent")
// return null;
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
public StudentDataContract GetStudentDetails(string StudentId)
{
StudentDataContract student = new StudentDataContract();
try
{
int Emp_ID = Convert.ToInt32(StudentId);
var query = (from a in ctx.Students
where a.StudentID.Equals(Emp_ID)
select a).Distinct().FirstOrDefault();
student.StudentID = Convert.ToString(query.StudentID);
student.Name = query.Name;
student.Email = query.Email;
student.EnrollYear = query.EnrollYear;
student.Class = query.Class;
student.City = query.City;
student.Country = query.Country;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return student;
}
public bool AddNewStudent(StudentDataContract student)
{
try
{
Student std = ctx.Students.Create();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.Students.Add(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return true;
}
public void UpdateStudent(StudentDataContract student)
{
try
{
int Stud_Id = Convert.ToInt32(student.StudentID);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
public void DeleteStudent(string StudentId)
{
try
{
int Stud_Id = Convert.ToInt32(StudentId);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
ctx.Students.Remove(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
}
}
Here is the web.config file ..
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
<endpointBehaviors>
<behavior>
<webHttp helpEnabled="True"/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</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>
<connectionStrings>
<add name="StudentManagementEntities" connectionString="metadata=res://*/SchoolManagement.csdl|res://*/SchoolManagement.ssdl|res://*/SchoolManagement.msl;provider=System.Data.SqlClient;provider connection string="data source=KHUNDOKARNIRJOR\KHUNDOKERNIRJOR;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I can not access the from localhost its is always shows this error
Request Error
The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.
Here is Screen shot
Please any help will be highly appreciated..
I don't see "services" element in your config file. Please take a look at the below link to configure your service.
Configuring Services
Another method is to create a wcf service using visual studio. Visual studio will generate appropriate config file for you. Then you can replace the methods, interface and configuration accordingly.
I see that you are trying to return a List. I don't think you can pass List as return parameter.
Please check all methods on "
http://localhost:50028/StudentService.svc" another suggestion, please
remove "/" from uriTemplate. Just write "GetAllStudent" instead of
"/GetAllStudent/".
> <services>
> <service name="" behaviorConfiguration="serviceBehavior">
> <endpoint address="" binding="webHttpBinding" contract="" behaviorConfiguration="web"/>
> </service>
> </services>
> <behaviors>
> <serviceBehaviors>
> <behavior name="serviceBehavior">
> <serviceMetadata httpGetEnabled="true"/>
> <serviceDebug includeExceptionDetailInFaults="false"/>
> </behavior>
> </serviceBehaviors>
> <endpointBehaviors>
> <behavior name="web">
> <webHttp/>
> </behavior>
> </endpointBehaviors>
> </behaviors>
As I look there is service and behaviors tags are missing from webconfig.

Unity: The type name or alias x could not be resolved. Please check your configuration file and verify this type name

Error code :
The type name or alias UnitOfWorkFactory could not be resolved.
Please check your configuration file and verify this type name.
I'm scraping google results / trying to debug for 2 days now, and I didn't find any solution yet.
Mention that "ApplicationService" is being resolved.
I verified the names of assemblies and namespaces many times
I already tried this concepts in the config file: https://stackoverflow.com/a/18671286/3264998 , and other concepts.
I verified the connection to the database.
I tried debugging mode in VS without any succes.
Probably some other stuff that I don't remember right now.
Bellow you have my code, hope it's enough. If there is any other file/info that I've omitted I apologies and I will edit the post immediately.
IApplicationService.cs
using System.Collections.Generic;
using Abc.Project.Domain.Model.DTO;
namespace Abc.Project.Application.Interfaces
{
public interface IApplicationService
{
void AddFile(FileDTO fileDTO);
}
}
ApplicationService.cs
using System.Collections.Generic;
using AutoMapper;
using Microsoft.Practices.Unity;
using Abc.Project.Application.Interfaces;
using Abc.Project.Domain.Model.DTO;
using Abc.Project.Domain.Model.Poco.Entities;
using Abc.Project.Domain.Repository.UnitOfWork;
using Abc.Project.Domain.Unity;
namespace Abc.Project.Application.Services.Global
{
public class ApplicationService : IApplicationService
{
public void AddFile(FileDTO fileDTO)
{
File file = new File
{
Id = fileDTO.ID,
FileObs = fileDTO.FileObs,
Ind = fileDTO.Ind,
Levels = fileDTO.Levels,
};
using (var uow = IoC.Container.Resolve<IUnitOfWorkFactory>().Create())
{
uow.Context.File.Add(file);
uow.Commit();
}
}
}
}
IUnitOfWorkFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Abc.Project.Domain.Repository.UnitOfWork
{
public interface IUnitOfWorkFactory
{
IUnitOfWork Create();
}
}
UnitOfWorkFactory.cs
using System.Data;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Abc.Project.Domain.Repository.UnitOfWork;
namespace Abc.Project.DataAccess.NHibernate.UnitOfWork
{
public class UnitOfWorkFactory : IUnitOfWorkFactory
{
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("FilesDB"))
)
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(false, false))
.BuildSessionFactory();
}
public IUnitOfWork Create()
{
UnitOfWork UnitOfWork = new UnitOfWork(CreateSessionFactory().OpenSession());
UnitOfWork.BeginTransaction(IsolationLevel.ReadCommitted);
return UnitOfWork;
}
}
}
App.config
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="FilesDB" providerName="System.Data.SqlClient" connectionString="server=SP2010;database=FilesDB;User ID=sa;Password=password;"/>
</connectionStrings>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<typeAliases>
<!-- Lifetime manager types -->
<typeAlias alias="singlecall" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity"/>
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
<typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity"/>
<typeAlias alias="percall" type="Abc.Project.Domain.Unity.StaticPerCallLifeTimeManager, Abc.Project.Domain.Model"/>
<!-- SERVICE APPLICATION INTERFACES-->
<typeAlias alias="IApplicationService" type="Abc.Project.Application.Interfaces.IApplicationService, Abc.Project.Application.Interfaces"/>
<!-- DOMAIN INTERFACES-->
<typeAlias alias="IUnitOfWorkFactory" type="Abc.Project.Domain.Repository.UnitOfWork.IUnitOfWorkFactory, Abc.Project.Domain.Repository"/>
<!-- CONCRETE CLASSES-->
<!-- SERVICE APPLICATION-->
<typeAlias alias="ApplicationService" type="Abc.Project.Application.Services.Global.ApplicationService, Abc.Project.Application.Services"/>
<!--DATA ACCESS-->
<typeAlias alias="UnitOfWorkFactory" type="Abc.Project.DataAccess.NHibernate.UnitOfWork.UnitOfWorkFactory, Abc.Project.DataAccess.NHibernate"/>
</typeAliases>
<containers>
<container>
<!--<extension type="Interception" />-->
<types>
<type type="IApplicationService" mapTo="ApplicationService">
<lifetime type="singlecall"/>
</type>
<type type="IUnitOfWorkFactory" mapTo="UnitOfWorkFactory">
<lifetime type="singleton"/>
</type>
</types>
</container>
</containers>
</unity>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="Abc.Project.WcfService.WcfServiceAspNetAjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="metadataAndDebug">
<serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
<service name="Abc.Project.WcfService.WcfService" behaviorConfiguration="metadataAndDebug">
<endpoint address="" behaviorConfiguration="Abc.Project.WcfService.WcfServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="Abc.Project.WcfService.WcfService"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
How can I solve this?
English is not my native language; please excuse typing errors.
Use the <alias>-element instead. Here´s a link to the Unity Configuration Schema
<unity>
<alias alias="IUnitOfWorkFactory" type="Abc.Project.Domain.Repository.UnitOfWork.IUnitOfWorkFactory, Abc.Project.Domain.Repository" />
<alias alias="UnitOfWorkFactory" type="Abc.Project.DataAccess.NHibernate.UnitOfWork.UnitOfWorkFactory, Abc.Project.DataAccess.NHibernate"/>
</unity>
<typeAlias>-Element is outdated and depending on your Unity version not supported anymore.
The assembly for UnitOfWorkFactory wasn't referenced

How to pass multiple parameter in wcf restful service?

IService.cs
[OperationContract]
[WebGet(UriTemplate = "/IsValidUser?userid={userid}&password={password}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string IsValidUser(string userid, string password);
Service.cs
public string IsValidUser(string userid, string password)
{
if (userid =="bob" && password =="bob")
{
return "True";
}
else
{
return "false";
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="IService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Problem:
Here my problem is that I want to pass multiple parameter while calling a WCF rest service, but I am not able to pass multiple parameters to that WCF rest service. I want to pass userid and password and check for in it. If it is bob then allow to go ahead.
And when I am calling this url:
http://localhost:48401/ARService/Service.svc/rest/IsValidUser?userid=bob&password=bob
then I am getting this error on my web page:
Endpoint not found. Please see the service help page for constructing valid requests to the service.
If somebody have idea how to call IsValidUser in my case with this function parameter. Please help me.
you can write this way:
Iservice.cs
[OperationContract]
[WebGet(UriTemplate = "IsValidUser/{userid}/{password}")]
string IsValidUser(string userid, string password);
service .cs
public string IsValidUser(string userid, string password)
{
if (userid== "root" && password== "root")
{
return "True";
}
else
{
return "false";
}
}
Run this Url in Browser,then you will get output
localhost/service.svc/rest/IsValidUser/root/root
try this
[OperationContract]
[WebGet(UriTemplate = "IsValidUser?userid={userid}&password={password}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string IsValidUser(string userid, string password);
Add BodyStyle on OperationContract
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]

How to get the response and request in JSON format?

I'm not getting the output in JSON Format. Here is the code
---- IService1.cs ----
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "currency")]
List<Employee> GetAllEmployeesMethod();
[OperationContract]
string TestMethod();
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "players")]
List<Person> GetPlayers();
}
---- Service1.svc.cs ----
public List<Employee> GetAllEmployeesMethod()
{
List<Employee> mylist = new List<Employee>();
using (SqlConnection conn = new SqlConnection("--connection string--"))
{
conn.Open();
string cmdStr = String.Format("Select customercode,CurrencyCode,CurrencyDesc from Currency");
SqlCommand cmd = new SqlCommand(cmdStr, conn);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
mylist.Add(new Employee(rd.GetInt32(0), rd.GetString(1), rd.GetString(2)));
}
conn.Close();
}
return mylist;
}
---- web.config ----
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
<system.serviceModel>
<services>
<service name="JSONSerialization.Service1" behaviorConfiguration="EmpServiceBehaviour">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding" contract="JSONSerialization.IService1" behaviorConfiguration="web" >
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EmpServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" helpEnabled="true" defaultBodyStyle="Bare"/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
and when I run this service, I get the data in
but I want the result to be in JSON format
Example: {"currencycode":"INR","DESCRIPTION":"Indian Rupees","customercode" : "1001"},....
add [Serialize] attribute to your methods

Categories