Visual Studio Express 2012 - Silverlight-Enabled WCF Service? - wcf

I just started a new Silverlight project with Visual Studio Express 2012 for Web.
I created a Silverlight-enabled WCF service to access a SQL Server database, with EF 5.
The problem I'm having is that the service doesn't seem to be able to return any entity retrieved from the database. A new entity or any old object is returned just fine, but when I try to return an entity from the context I get the following exception:
{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.DataServiceClientChannel.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.NewProj.DataSvcRef.DataService.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.OnEndGetAgency(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}
The service method code couldn't be simpler:
[OperationContract]
public Contact GetContact(int aID)
{
Contact res = null;
using (var db = new OFBEntities())
{
try
{
res = db.Contacts.Find(aID);
}
catch (Exception ex)
{
res = null;
}
return res;
}
}
As I mentioned, if I return a newly created object (return new Contact(){ name="test contact};), or return a type that is not in context (say an integer for example), everything works fine.
Is this a limitation of the express version, or am I forgetting some settings? In the past I have created some Silverlight apps that consumed data services with VS 2010, Silverlight 4, and I don't remember having to set anything special, but maybe I just forgot that I did?
Any help is appreciated!
EDIT:
Could it have anything to do with DbContext and the way it is serialized? I've never used DbContext before, I always used the default ObjectContext in EF 4...
EDIT2: SOLUTION
It's been a while, but I had other things to work :o)
In case anybody is in the same boat, the problem was in the serialization by the service. DbContext by default creates proxies, which don't agree with serialization. I am not sure why yet - indeed, I need to educate myself about those proxies - but disabling them solves my serialization issue.
Thanks for the comment Pawel, I mistakenly thought my serialization was going OK, rechecking the server-side error put me back on the right track.

The problem was with automatic proxy creation by the DBContext, which interfered with the serialization.
Proxies are on by default in DBContext, you can disable them in the class constructor
this.Configuration.ProxyCreationEnabled = false;
or after creating an instance of your DBContext
using (var db = new myDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
...
}
Not sure why yet, but it works. Time to go read up on that!

Related

Invalid Token when confirming email address - Asp.Net Core

I'm occasionally getting an "Invalid Token" error from my call to
userManager.ConfirmEmailAsync(user, token) . I've narrowed down the problem to the fact that my 2 web servers are sitting behind a load balancer, and the web server that generated the token isn't always the web server that is attempting to confirm the token. I had a similar problem with anti-forgery tokens in a different web site, which I fixed by persisting the data protection key to disk and sharing it between the web servers, so I tried a similar approach here.
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"c:\temp\API"));
I then copied the key to the same folder in my other web server but still wasn't successful. Debugging through the AspNetCore.Identity code I can see an exception thrown on the call to
var unprotectedData = Protector.Unprotect(Convert.FromBase64String(token))
in the DataProtectorTokenProvider class. the catch block for the exception in Microsoft's code is simply
catch
{
// Do not leak exception
}
so I decided to inject an IDataProtector into my own Controller and try making that call myself.
public UserController(Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager, Microsoft.AspNetCore.Identity.RoleManager<IdentityRole> roleManager,
ILoggerFactory loggerFactory,
IDataProtectionProvider dataProtectionProvider)
{
Protector = dataProtectionProvider.CreateProtector("DataProtectorTokenProvider");
}
try
{
var unconverted = Convert.FromBase64String(request.EmailConfirmationToken);
var unprotectedData = Protector.Unprotect(unconverted);
}
catch (Exception e)
{
}
I can now catch the exception thrown on the Unprotect call and it's:
The payload was invalid
Microsoft.AspNetCore.DataProtection.Cng.CbcAuthenticatedEncryptor.DecryptImpl(Byte* pbCiphertext, UInt32 cbCiphertext, Byte* pbAdditionalAuthenticatedData, UInt32 cbAdditionalAuthenticatedData)\r\n at Microsoft.AspNetCore.DataProtection.Cng.Internal.CngAuthenticatedEncryptorBase.Decrypt(ArraySegment1 ciphertext, ArraySegment1 additionalAuthenticatedData)\r\n at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)\r\n at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)\r\n at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)\r\n at VTR.API.Controllers.UserController.d__16.MoveNext() in C:\Projects\Brewster.Travel\src\cres\trunk\VTR.API\src\VTR.API\Controllers\UserController.cs:line 409
If I make that call with a token generated on the same server then it gets unprotected successfully. I obviously have some problem with how I'm attempting to share my data protection keys, if anyone could shed some light on my problem I would appreciate it.
I managed to get this working thanks to the documentation here: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview
I needed to add a call to SetApplicationName() in ConfigureServices:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"c:\someDirectory"))
.SetApplicationName("myApplicationName");

WCF RIA Service with Unity 3.5.1.0

I'm trying to Use this Blog for WCF RIA Applcation . So I Create a Silverlight Nevigation Applciation which gave me 2 projects abs & abs.Web
More I create 3 project in solution :
abs.Data (c#), DbContext Implemeantion of Repository Interfaces +Factory to provide What user want.
abs.Data.Contarct (c#) Interfaces for Operations Repository
abs.Data.Model (c#) - Contains POCO - EF 6
Now I created A wcf Service in abs.Web project which have constructor injection of a Repository to get my job done in operation contracts.
So I tried using Unity here under the guidence with below blog
http://jamesheppinstall.wordpress.com/2012/06/20/windows-communication-foundation-resolving-wcf-service-dependencies-with-unity/
Now I'm getting
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
**Stack Trace: **
[InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.]
System.ServiceModel.Dispatcher.InstanceBehavior..ctor(DispatchRuntime dispatch, ImmutableDispatchRuntime immutableRuntime) +12761206
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime..ctor(DispatchRuntime dispatch) +173
System.ServiceModel.Dispatcher.DispatchRuntime.GetRuntimeCore() +85
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpened() +148
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +321
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +139
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +310
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +91
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +598
[ServiceActivationException: The service '/DomainServices/UserWcfService.svc' cannot be activated due to an exception during compilation. The exception message is: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host..]
System.Runtime.AsyncResult.End(IAsyncResult result) +499812
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +178
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446
My all classes are same as like Blog.
WCF Ria has its own factory.
Simply put
public class MyDomainServiceFactory : IDomainServiceFactory
{
#region IDomainServiceFactory Members
public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
{
try
{
if (!typeof (DomainService).IsAssignableFrom(domainServiceType))
{
throw new ArgumentException(String.Format("Cannot create an instance of {0} since it does not inherit from DomainService", domainServiceType), "domainServiceType");
}
if (IoC.IsRegistered(domainServiceType))
{
var dmnService = (DomainService) IoC.Resolve(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
else
{
//if the IoC container doesn't know the service, simply try to call its default constructor
//could throw proper exception as well
var dmnService = (DomainService) Activator.CreateInstance(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
}
catch (Exception ex)
{
ExceptionHandler.HandleException(ex);
return null;
}
}
public void ReleaseDomainService(DomainService domainService)
{
domainService.Dispose();
}
#endregion
}
and somewhere on your bootstrapping code add
DomainService.Factory = new MyDomainServiceFactory();
of course, the word IoC in the factory identify the unityContainer (is actually a static façade against it)

RavenDB Embedded on Azure Websites - Access Denied

I get an Access denied message when I try to deploy my MVC4 site with an Embedded instance of RavenDB to the new Azure Websites preview feature. The site works fine locally.
Here is how I configure Raven:
//Initialize the RavenDB Data Store
Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8887);
var documentStore = new EmbeddableDocumentStore()
{
DataDirectory = "~\\App_Data",
UseEmbeddedHttpServer = true,
Configuration = { Port = 8887 }
};
documentStore.Initialize();
And here is the stack trace when I browse to the site:
Access is denied
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.NetworkInformation.NetworkInformationException: Access is denied
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NetworkInformationException (0x5): Access is denied]
System.Net.NetworkInformation.SystemIPGlobalProperties.GetAllTcpConnections() +1570717
System.Net.NetworkInformation.SystemIPGlobalProperties.GetActiveTcpListeners() +74
Raven.Database.Util.PortUtil.FindPort() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Util\PortUtil.cs:110
Raven.Database.Util.PortUtil.GetPort(String portStr) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Util\PortUtil.cs:44
Raven.Database.Config.InMemoryRavenConfiguration.Initialize() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\InMemoryRavenConfiguration.cs:170
Raven.Database.Config.RavenConfiguration.LoadConfigurationAndInitialize(IEnumerable`1 values) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\RavenConfiguration.cs:28
Raven.Database.Config.RavenConfiguration..ctor() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Config\RavenConfiguration.cs:17
Raven.Client.Embedded.EmbeddableDocumentStore.get_Configuration() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Embedded\EmbeddableDocumentStore.cs:63
Raven.Client.Embedded.EmbeddableDocumentStore.set_DataDirectory(String value) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Embedded\EmbeddableDocumentStore.cs:90
Solarity.DesignSearch.Website.Bootstrapper.BuildUnityContainer() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Bootstrapper.cs:35
Solarity.DesignSearch.Website.Bootstrapper.Initialise() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Bootstrapper.cs:20
Solarity.DesignSearch.Website.MvcApplication.Application_Start() in c:\a\src\Solarity.DesignSearch\Solarity.DesignSearch.Website\Global.asax.cs:23
[HttpException (0x80004005): Access is denied]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9859725
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Access is denied]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I managed to get it to work, although it is not ideal. You may notice in my original post that I am setting the UseEmbeddedHttpServer = true. This is so that I can browse to http:[MyUrl]:8081 and get the RavendDB Management Studio so that I can browse my data. For some reason, RavenDB wants to do the same kind of port check when this property is set as it does when you set the Port setting to automatic (Port=*).
I believe that RavenDB may need a fix so that it honors the Port setting when UseEmbeddedHttpServer is True and also let you set the Configuration property of the EmbeddedDocumentStore upon creation.
But in the meantime, you can truly get your MVC4 site to work with an EmbeddedDocumentStore on Azure Websites simply by specifying a port. Also, you do indeed have to use the AppSettings configuration rather than setting the Configuration property of the EmbeddedDocumentStore upon creation (like I tried to do above). This post (stackoverflow.com/questions/11529159/) shows how to do it.
Unfortunately, I still haven't found a way to run the EmbeddedHttpServer so I can use the Raven Management Studio. If I figure out how, I will post a solution here.
Hi this was answered on RavenDb on Azure Websites - Access Denied
Basically you need to configure the port in Web.config

The type initializer for 'NHibernate.Cfg.Configuration' threw an exception

After upgrading from nhibernate 1.0.4.0 to nhibernate 3.3 im encountering the following error when I try to run "Configuration cfg = new Configuration();"
System.TypeInitializationException was caught
Message="The type initializer for 'NHibernate.Cfg.Configuration' threw an exception."
Source="NHibernate"
TypeName="NHibernate.Cfg.Configuration"
StackTrace:
at NHibernate.Cfg.Configuration..ctor()
at KEH.Web.Data.NHibernateUtil..cctor() in F:\Projects\KEH nHibernate\KEHWeb\Data\Data\NHibernateUtil.cs:line 24
InnerException: System.NotSupportedException
Message="The invoked member is not supported in a dynamic assembly."
Source="mscorlib"
StackTrace:
at System.Reflection.Emit.AssemblyBuilder.get_Location()
at log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly)
at log4net.Core.DefaultRepositorySelector.GetInfoForAssembly(Assembly assembly, String& repositoryName, Type& repositoryType)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType)
at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly)
at log4net.Core.LoggerManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Type type)
at lambda_method(ExecutionScope , Type )
at NHibernate.Log4NetLoggerFactory.LoggerFor(Type type)
at NHibernate.LoggerProvider.LoggerFor(Type type)
at NHibernate.Cfg.Configuration..cctor()
InnerException:
Any help would be greatly appreciated.
The NHibernateUtil class code is as follows :
public class NHibernateUtil
{
private static readonly Configuration cfg;
private static readonly ISessionFactory sessionFactory;
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static NHibernateUtil()
{
try
{
logger.Debug("Before Initializing NHibernate");
cfg = new Configuration();
cfg.AddAssembly("KEH.Web.Data");
sessionFactory = cfg.BuildSessionFactory();
logger.Debug("Initialized NHibernate");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static ISession OpenSession()
{
logger.Debug("Before Getting Connection");
return sessionFactory.OpenSession();
}
}
I had the same problem.
The actual reason was i used a library that used old version of log4net.
NHibernate tries to use it if find.
So i had to force it to use (or actually not use) other logger by adding such line:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
Not sure why it's not working, but I'd just replace
cfg.AddAssembly("KEH.Web.Data");
with
cfg.AddAssembly(typeof(Entity).Assembly);
where Entity is some class that exists in the assembly of your mapping files.
For the benefit of others who might find this question via Google:
For us, this error was a red-herring. Our app ran fine until we deployed a new component AND it would fail (in an unknown way) AND IIS would recycle the app pool. The problem was an HTML to JPG component we were using was erroring somehow and causing all of our w3wp.exe worker processes to consume maximum CPU. When the app pool was recycled via IIS, the entire site would go down and NHibernate would throw this error continuously until an iisreset. Before the recycle, the site would still be very responsive even with the CPU load.
While we still don't know how the component was failing or why it was cascading to problems with NHibernate initializing, the point is it was a red-herring. Be sure to watch for this error "suddenly" occurring shortly after a new deployment, and keep logs of your CPU utilization so it can help spot when trouble is brewing. Finally, if the downtime is happening near the same time every day, it's probably an automatic IIS app pool recycle, and that should be another clue that something is bugging out your application and surfacing during the recycle.
Ultimately, we disabled the HTML to JPG component until a workaround can be found and our up-time sprung back to 100%.
Hope this helps someone.

Wcf Data Service Service operations

Getting error when I run the wcf data service with the code following the error message:
"The server encountered an error processing the request. See server logs for more details."
Code:
public class WcfDataService1 : DataService<Entities1>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("GetData", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet()]
public IQueryable GetData(int Id)
{
if (assayId > 0)
{
var query = from a in this.CurrentDataSource.Entity
where a.ID == Id
select a;
return query;
}
else
throw new DataServiceException(400, "ID is not valid");
}
}
The same code works when I dont return anything from the operation.
UPDATE: The server logs say:
"WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/44530215
Exception: System.ServiceModel.ServiceActivationException: The service '/MyWcfDataService.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.. ---> System.InvalidOperationException: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.
at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: WebDev.WebServer40
Process ID: 1124
For more information, see Help and Support Center at
Can anyone please help me with the solution.
Also, if I want to expose my own entity and not the one created by EF, how to go about doing that.. any ideas??
Just modified the return type to
IQueryable<Entity> and it worked.