c# wcf hosted in windows service goes idle after 5 minutes - c#

I have a WCF service hosted inside a Windows Service. (SO its not hosted in IIS, it is selfhosted)
The application makes it possible to receive measurements through HTTP. These are currently being written to a txt file.
I also have a Task configured that runs everyday at a specific time.
The problem i have is that when i dont receive a measurement through HTTP for atleast 5 minutes the service seems to go idle.
I noticed that after 5 minutes it takes 30 seconds for the service to respond. After 30 seconds if i send measurements through http i get a fast response.
What could be the problem?
app.config
<?xml version="1.0"?>
<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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Applicatie.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
</connectionStrings>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="LargeWeb" maxBufferSize="1500000" maxBufferPoolSize="1500000"
maxReceivedMessageSize="2000000000" transferMode="Streamed">
<readerQuotas maxDepth="32" maxStringContentLength="656000" maxArrayLength="656000"
maxBytesPerRead="656000" maxNameTableCharCount="656000" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="Applicatie.Applicatie" behaviorConfiguration="Proxy">
<host>
<baseAddresses>
<add baseAddress="http://localhost:5001/Applicatie"/>
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" bindingConfiguration="LargeWeb" behaviorConfiguration="webBehavior" contract="Applicatie.IApplicatie"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp/>
<CorsSupport />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Proxy">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<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>

It seems like the issue we also had. we have many self hosted services. If for some time (~1 min) service receives no requests it becomes idle, and next call is really slow.
So the reasons and solution described here
I also confirm this fix helped in our case.
Quote from there:
I have confirmed with our developers that this is a known issue. The cause is indeed related to ThreadPool and thread timeout.
One possible workaround is call ThreadPool.UnsafeQueueNativeOverlapped method in short time interval to keep thread available.
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(Service1)))
{
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate
{
while (true)
{
Thread.Sleep(TimeSpan.FromSeconds(100));
QueueDummyIOCPWork();
}
}));
host.Open();
Console.WriteLine("Service running...");
Console.ReadKey(false);
}
}
private static unsafe void QueueDummyIOCPWork()
{
Overlapped ovl = new Overlapped();
NativeOverlapped* pOvl = null;
pOvl = ovl.Pack((a, b, c) => { Overlapped.Unpack(pOvl); Overlapped.Free(pOvl); }, null);
ThreadPool.UnsafeQueueNativeOverlapped(pOvl);
}
}

Related

WCF Client works with Visual Studio Host but not with custom Host program

I have a wcf project, very standard in first place.
The problem is when i Host it with Visual Studio, it works just fine
But when i host it with my custom made program, im getting errors.
System.Exception: Couldn't create ActiveX Component.
at Microsoft.VisualBasic.Interaction.GetObject(String PathName, String Class)
System.Runtime.Serialization.SerializationException: The type "DiskViewBox.DiskViewItem" in assembly "DiskViewBox, Version=1.0.3401.18107, Culture=neutral, PublicKeyToken=null" is not marked as serialisable.
I want to run it as a Windows Service later on.
I assume the problem is not in the client, because it works, and unfortunately i dont know how Visual Studio is hosting it, so i cant compare it to the custom Host.
using System.ServiceModel;
using System.ServiceModel.Description;
using WcfService1;
namespace WcfServiceHost
{
class Program
{
static void Main(string[] args)
{
// Step 1: Create a URI to serve as the base address.
Uri baseAddress = new Uri("net.tcp://localhost:7891/Test/WcfService1/Service1/");
// Step 2: Create a ServiceHost instance.
using (ServiceHost selfHost = new ServiceHost(typeof(Service1), baseAddress))
{
try
{
// Step 3: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(), "IService1");
// Step 4: Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
//smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5: Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
// Close the ServiceHost to stop the service.
Console.WriteLine("Press <Enter> to terminate the service.");
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
}
The App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.web>
<compilation debug="true" />
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<!-- Bei der Bereitstellung des Dienstbibliothekprojekts muss der Inhalt der Konfigurationsdatei der
app.config-Datei des Hosts hinzugefügt werden. System.Configuration unterstützt keine Konfigurationsdateien für Bibliotheken. -->
<system.serviceModel>
<services>
<service name="WcfService1.Service1">
<endpoint address="" binding="netTcpBinding" bindingConfiguration="" contract="WcfService1.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:7891/Test/WcfService1/Service1/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The client is written in VB because the access is from a VB environment and its easier to Debug in VS.
Module Module1
Sub Main()
Dim addr As String
addr = "service:mexAddress=""net.tcp://localhost:7891/Test/WcfService1/Service1/Mex"","
addr = addr + "address=""net.tcp://localhost:7891/Test/WcfService1/Service1/"","
addr = addr + "contract=""IService1"", contractNamespace=""http://tempuri.org/"","
addr = addr + "binding=""NetTcpBinding_IService1"", bindingNamespace=""http://tempuri.org/"""
Dim service1 As Object
MsgBox(addr)
Dim path As String
path = "C:\\tmp\\test1.docm"
service1 = GetObject(addr)
MsgBox(service1.GetData(112))
'Dim result As Variant
'result = service1.GetString
End Sub
End Module
Thank you in advance

could not establish secure channel for ssl/tls with authority wcf C# wcf rest service

I create a client application that get data from my rest wcf service as you can see :
Uri reqUri = new Uri("https://localhost/paymentservice.svc/listpayment");
WebRequest req = WebRequest.Create(reqUri);
req.PreAuthenticate = true;
NetworkCredential credential = new NetworkCredential("test", "test123");
req.Credentials = credential;
WebResponse resp = req.GetResponse();
DataContractSerializer data = new DataContractSerializer(typeof(string));
var res = data.ReadObject(resp.GetResponseStream());
Console.WriteLine(res);
Console.ReadLine();
I create a certificate in iis as you can se :
And upload my published file on it .
But when i call my client i get this error :
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
Here is my service webconfig
<?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=6.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.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<authentication mode="None" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Payment.Application.ServiceImplement.PaymentService" behaviorConfiguration="customBehaviour">
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Service.IPaymentService"
behaviorConfiguration="web"/>
</service>
<service name="Payment.Infrustructure.RepositoryImplement.PaymentRepository" behaviorConfiguration="customBehaviour" >
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Repository.IPaymentRepository"
behaviorConfiguration="web"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="customBehaviour">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="Payment.Service.UserAuthentication,Payment.Service"/>
</serviceCredentials>
<!-- 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 name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="GET, POST,PUT,DELETE" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<!--
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" />
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<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>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;initial catalog=SymfaDB;user id= sa ;password=12345;" providerName="System.Data.SqlClient" />
<!--<add name="DefaultConnection" connectionString="Data Source=92.50.12.222,1433;initial catalog=ParkingDB;user id= sa ;password=123qweQWE#;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
</configuration>
When irun the project in visual studio and call this url http://localhost:4428/PaymentService.svc/listpayment I get the data as you can see :
But when i upload the publish file into iis and call this url https://localhost/PaymentService.svc/listpayment as you can see i get this error :
As you can see when i call this https://localhost/PaymentService.svc my service is available .
You need to install the certificate as trusted source.
Open a command prompt with admin rights, type "mmc" and press enter which will open Microsoft Management Console.
From Menu go to File > Add/Remove Snap-In, select Certificates and Click Add
Select Computer Account and click Next, select Local Computer and click Finish.
Go to Certificates (Local Computer) > Personal > Certificates
From the Menu go to Action > All Tasks > Import
Click Next in the Certificate Import Wizard, Provide the path to the certificate file, enter the password if any then click Next, Next and Finish.
Now you will be back to Microsoft Management Console, click on Trusted Root Certification Authorities, select Certificates, Action > All Tasks > Import and follow the step 6.
Also the hostname used in the URL should match the name that's on certificate. Make sure the URL you're using and the URL on the 'Issued to' field of the certificate are the same.
To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. For example, if you open your certificate then you’ll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like .. etc, so if you open it in your browser will fully qualified name of your machine then you won’t be getting that error.
So i just call my service by domain like https://union-pc58.union.com/Service1.svc
Just follow this link
http://www.c-sharpcorner.com/UploadFile/vendettamit/create-secure-wcf-rest-api-with-custom-basic-authentication/

Queue showing empty

So this is pretty new to me and I'm making progress. I currently have a wcf service using netmsmqbinding to send a simple message to a queue. Everything runs smooth and the event view even says that the message was put in the queue. Although when I goto the actual queue there is nothing in there. I have a service, service host, and asp web app. Note in the web app I have a service reference to the service. Also in the msmq log in the event viewer I get 3 events. Any assistance would be appreciated. Thanks.
Here's my setup.
Service Interface:
[ServiceContract]
public interface IMSMQService
{
[OperationContract(IsOneWay = true)]
void ShowMessage(string msg);
}
Service:
public class MSMQService : IMSMQService
{
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void ShowMessage(string msg)
{
Debug.WriteLine(msg + " Received at: " + System.DateTime.Now.ToString());
}
}
App.Config of Service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\TestQueue"/>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.serviceModel>
<services>
<service name="MSMQNoSecurityService.MSMQService" behaviorConfiguration="MyBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9001/msmq"/>
</baseAddresses>
</host>
<endpoint address="net.msmq://localhost/private/TestQueue" binding="netMsmqBinding" bindingConfiguration="MyBinding" contract="MyService.IMSMQService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netMsmqBinding>
<binding name="MyBinding">
<security mode="None"/>
</binding>
</netMsmqBinding>
</bindings>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>
Service Host
static void Main(string[] args)
{
ServiceHost svcHost = null;
try
{
// Get MSMQ queue name from appsettings in configuration.
string queueName = ConfigurationManager.AppSettings["queueName"];
// Create the transacted MSMQ queue if necessary.
if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName, true);
svcHost = new ServiceHost(typeof(MyService.MSMQService));
svcHost.Open();
Console.WriteLine("\n\nService is Running at following address");
Console.WriteLine("\nhttp://localhost:9001/MSMQService");
}
catch (Exception eX)
{
svcHost = null;
Console.WriteLine("Service can not be started \n\nError Message [" + eX.Message + "]");
}
if (svcHost != null)
{
Console.WriteLine("\nPress any key to close the Service");
Console.ReadKey();
svcHost.Close();
svcHost = null;
}
}
App.Config of Service Host:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<appSettings>
<add key="queueName" value=".\private$\TestQueue"/>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<services>
<service name="MyService.MSMQService" behaviorConfiguration="MyBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9001/msmq"/>
</baseAddresses>
</host>
<endpoint address="net.msmq://localhost/private/TestQueue" binding="netMsmqBinding" bindingConfiguration="MyBinding" contract="MyService.IMSMQService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netMsmqBinding>
<binding name="MyBinding" >
<security mode="None"/>
</binding>
</netMsmqBinding>
</bindings>
</system.serviceModel>
</configuration>
MVC Controller
public class WcfMsmqController : Controller
{
public ActionResult Index()
{
MSMQServiceClient proxy = new MSMQServiceClient();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
proxy.ShowMessage("test");
scope.Complete();
}
proxy.Close();
return View();
}
}
Service model in Web.config (autogenerated):
<system.serviceModel>
<bindings>
<netMsmqBinding>
<binding name="NetMsmqBinding_IMSMQService">
<security mode="None" />
</binding>
</netMsmqBinding>
</bindings>
<client>
<endpoint address="net.msmq://localhost/private/TestQueue" binding="netMsmqBinding"
bindingConfiguration="NetMsmqBinding_IMSMQService" contract="ServiceReference1.IMSMQService"
name="NetMsmqBinding_IMSMQService" />
</client>
</system.serviceModel>
Events from MSMQ Log: Modified some of it for viewing on here
Message with ID CN=msmq,CN=blah,OU=blah,OU=blah,DC=blah,DC=local\8280 was sent to queue PRIVATE=blah
Message with ID CN=msmq,CN=blah,OU=blah,OU=blah,DC=blah,DC=local\8280 was put into queue PRIVATE=blah
Message received
It seems to be related to your transaction.
You should try to place [TransactionFlow(TransactionFlowOption.Allowed)] on the operation in the service contract. Something like:
[ServiceContract]
public interface IMSMQService
{
[OperationContract(IsOneWay = true)]
[TransactionFlow(TransactionFlowOption.Allowed)]
void ShowMessage(string msg);
}
Anyway, you should be aware of local transactions if you decide to deploy this on web farm or something that involves multiple computers.
Figured it out. I had to add a namespace to the servicecontract. Prior it would default to some kind of tempuri.
[ServiceContract(Namespace = "http://MyService")]
public interface IMSMQService
{
[OperationContract(IsOneWay = true)]
[TransactionFlow(TransactionFlowOption.Allowed)]
void ShowMessage(string msg);
}

typeinitializationexception was unhandled .The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I have created a Entity Framework DLL EMPDAL which points to Employees Table of Northwnd database. Below is the code for Entity framework
namespace EmpDAL{
public class EmplooyeeData
{
public static List<Employee> GetEmployees( int EmployeeId)
{
using (DbEntities dbContext = new DbEntities())
{
return dbContext.Employees.Where(x => x.EmployeeID == EmployeeId).ToList();
}
}
public static void SaveEmployee(Employee emp)
{
DbEntities dbContext = new DbEntities();
dbContext.Employees.Add(emp);
dbContext.SaveChanges();
}
}}
Below is the Appconfig file of EMPDAL
<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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
Below is the code for the WCF service
namespace EmployeeService{
public class EmployeeService : IEmployeeService
{
public List<EmpDAL.Employee> GetEmployees(int Empid)
{
return EmpDAL.EmplooyeeData.GetEmployees(Empid);
}
public void SaveChanges(EmpDAL.Employee emp)
{
EmpDAL.EmplooyeeData.SaveEmployee(emp);
}
}}
Below is the AppConfig for WCF EmployeeService
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="EmployeeService.EmployeeService">
<endpoint address="" binding="basicHttpBinding" contract="EmployeeService.IEmployeeService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/EmployeeService/EmployeeService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel> <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings>
<add name="DbEntities"connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,EntityFramework" /> </entityFramework></configuration>
When client uses the WCF service it and when it tries to execute "using (DbEntities dbContext = new DbEntities())" it goes to
public partial class DbEntities : DbContext {
public DbEntities()
: base("name=DbEntities")
and throws exception
typeinitializationexception was unhandled .The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
It is very generic exception so in your editor try reading the whole details of the exception and then resolve it.
For me, it was due to the entity framework version written in webconfig file and actual file included ,there was difference and also i had to remove providers tag in web config file of my project

Failing to get MSMQ WCF Window Service to function

I'm trying to create a MSMQ WCF service, although I'm having troubles running the code. It fails when trying to create an instance of the service. I have MSMQ installed, and can confirm there is a private created called 'servicemodelsamples'
When running the service, I received the following error;
Service cannot be started. System.InvalidOperationException: There was
an error opening the queue. Ensure that MSMQ is installed and running,
the queue exists and has proper authorization to be read from. The
inner exception may contain additional information. --->
System.ServiceModel.MsmqException: An error occurred while opening the
queue:Unrecognized error -1072824283 (0xc00e0025). The message cannot
be sent or received from the queue. Ensure that MSMQ is installed and
running. Also ensure that the queue is available to open with the
required access mode and authorization.
Control Service Interface and Implementation.
[ServiceContract()]
public interface IControlService
{
[OperationContract(IsOneWay = true)]
void PricingAlert(int eventid, int marketid);
}
public class ControlService : IControlService
{
public ControlService()
{ }
public void PricingAlert(int eventid, int marketid)
{
Console.WriteLine("Acknowledged");
}
}
Service1.cs Service starting code.
protected override void OnStart(string[] args)
{
Thread.Sleep(10000);
string queueName = Settings.Default["queueName"].ToString();
if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName, true);
if (myServiceHost != null)
{
myServiceHost.Close();
}
myServiceHost = new ServiceHost(typeof(ControlService));
myServiceHost.Open(); // *** Code Fails Here
}
The application config;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ControlService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<bindings>
<netMsmqBinding>
<binding name="netMsmqBindingConfig">
<security mode="None">
</security>
</binding>
</netMsmqBinding>
</bindings>
<services>
<service name="TheControlService.ControlService" behaviorConfiguration="MSMQBindingBehaviour">
<endpoint address="net.msmq://172.26.2.11/private/ServiceModelSamples"
binding="netMsmqBinding" bindingConfiguration="netMsmqBindingConfig"
contract="TheControlService.IControlService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MSMQBindingBehaviour">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8000/Hello/" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="sdt"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="controlserviceerrors.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<applicationSettings>
<ControlService.Properties.Settings>
<setting name="queueName" serializeAs="String">
<value>.\private$\ServiceModelSamples</value>
</setting>
</ControlService.Properties.Settings>
</applicationSettings>
</configuration>
Any ideas? I suspect it might because I've based the code on an example which was a winforms application.
Check the user under which the Service is running. Add permission to the queues manually.
If the queues have broken permissions you should reset the permissions manually in C:\Windows\System32\msmq\storage\lqs using a notepad.

Categories

Resources