WPF unity Activation error occured while trying to get instance of type - wpf

I am getting the following error when trying to Initialise the Module using Unity and Prism. The DLL is found by
return new DirectoryModuleCatalog() { ModulePath = #".\Modules" };
The dll is found and the Name is Found
#region Constructors
public AdminModule(
IUnityContainer container,
IScreenFactoryRegistry screenFactoryRegistry,
IEventAggregator eventAggregator,
IBusyService busyService
)
: base(container, screenFactoryRegistry)
{
this.EventAggregator = eventAggregator;
this.BusyService = busyService;
}
#endregion
#region Properties
protected IEventAggregator EventAggregator { get; set; }
protected IBusyService BusyService { get; set; }
#endregion
public override void Initialize()
{
base.Initialize();
}
#region Register Screen Factories
protected override void RegisterScreenFactories()
{
this.ScreenFactoryRegistry.Register(ScreenKeyType.ApplicationAdmin, typeof(AdminScreenFactory));
}
#endregion
#region Register Views and Various Services
protected override void RegisterViewsAndServices()
{
//View Models
this.Container.RegisterType<IAdminViewModel, AdminViewModel>();
}
#endregion
the code that produces the error is:
namespace Microsoft.Practices.Composite.Modularity
protected virtual IModule CreateModule(string typeName)
{
Type moduleType = Type.GetType(typeName);
if (moduleType == null)
{
throw new ModuleInitializeException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.FailedToGetType, typeName));
}
return (IModule)this.serviceLocator.GetInstance(moduleType); <-- Error Here
}
Can Anyone Help Me
Error Log Below:
General Information
Additional Info:
ExceptionManager.MachineName: xxxxx
ExceptionManager.TimeStamp: 22/02/2010 10:16:55 AM
ExceptionManager.FullName: Microsoft.ApplicationBlocks.ExceptionManagement, Version=1.0.3591.32238, Culture=neutral, PublicKeyToken=null
ExceptionManager.AppDomainName: Infinity.vshost.exe
ExceptionManager.ThreadIdentity:
ExceptionManager.WindowsIdentity: xxxxx
1) Exception Information
Exception Type: Microsoft.Practices.Composite.Modularity.ModuleInitializeException
ModuleName: AdminModule
Message: An exception occurred while initializing module 'AdminModule'.
- The exception message was: Activation error occured while trying to get instance of type AdminModule, key ""
Check the InnerException property of the exception for more information. If the exception occurred
while creating an object in a DI container, you can exception.GetRootException() to help locate the
root cause of the problem.
Data: System.Collections.ListDictionaryInternal
TargetSite: Void HandleModuleInitializationError(Microsoft.Practices.Composite.Modularity.ModuleInfo, System.String, System.Exception)
HelpLink: NULL
Source: Microsoft.Practices.Composite
StackTrace Information
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.HandleModuleInitializationError(ModuleInfo moduleInfo, String assemblyName, Exception exception)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.InitializeModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModulesThatAreReadyForLoad()
at Microsoft.Practices.Composite.Modularity.ModuleManager.OnModuleTypeLoaded(ModuleInfo typeLoadedModuleInfo, Exception error)
at Microsoft.Practices.Composite.Modularity.FileModuleTypeLoader.BeginLoadModuleType(ModuleInfo moduleInfo, ModuleTypeLoadedCallback callback)
at Microsoft.Practices.Composite.Modularity.ModuleManager.BeginRetrievingModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModuleTypes(IEnumerable`1 moduleInfos)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModulesWhenAvailable()
at Microsoft.Practices.Composite.Modularity.ModuleManager.Run()
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.InitializeModules()
at Infinity.Bootstrapper.InitializeModules() in D:\Projects\dotNet\Infinity\source\Inifinty\Infinity\Application Modules\BootStrapper.cs:line 75
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run(Boolean runWithDefaultConfiguration)
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run()
at Infinity.App.Application_Startup(Object sender, StartupEventArgs e) in D:\Projects\dotNet\Infinity\source\Inifinty\Infinity\App.xaml.cs:line 37
at System.Windows.Application.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__0(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
2) Exception Information
Exception Type: Microsoft.Practices.ServiceLocation.ActivationException
Message: Activation error occured while trying to get instance of type AdminModule, key ""
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object GetInstance(System.Type, System.String)
HelpLink: NULL
Source: Microsoft.Practices.ServiceLocation
StackTrace Information
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.CreateModule(String typeName)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
3) Exception Information
Exception Type: Microsoft.Practices.Unity.ResolutionFailedException
TypeRequested: AdminModule
NameRequested: NULL
Message: Resolution of the dependency failed, type = "Infinity.Modules.Admin.AdminModule", name = "". Exception message is: The current build operation (build key Build Key[Infinity.Modules.Admin.AdminModule, null]) failed: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService). (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object DoBuildUp(System.Type, System.Object, System.String)
HelpLink: NULL
Source: Microsoft.Practices.Unity
StackTrace Information
*********************************************
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name)
at Microsoft.Practices.Composite.UnityExtensions.UnityServiceLocatorAdapter.DoGetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
4) Exception Information
Exception Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException
ExecutingStrategyTypeName: BuildPlanStrategy
ExecutingStrategyIndex: 3
BuildKey: Build Key[Infinity.Modules.Admin.AdminModule, null]
Message: The current build operation (build key Build Key[Infinity.Modules.Admin.AdminModule, null]) failed: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService). (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object ExecuteBuildUp(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
5) Exception Information
Exception Type: System.InvalidOperationException
Message: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService).
Data: System.Collections.ListDictionaryInternal
TargetSite: Void ThrowForResolutionFailed(System.Exception, System.String, System.String, Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForResolutionFailed(Exception inner, String parameterName, String constructorSignature, IBuilderContext context)
at BuildUp_Infinity.Modules.Admin.AdminModule(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
6) Exception Information
Exception Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException
ExecutingStrategyTypeName: BuildPlanStrategy
ExecutingStrategyIndex: 3
BuildKey: Build Key[PhoenixIT.IScreenFactoryRegistry, null]
Message: The current build operation (build key Build Key[PhoenixIT.IScreenFactoryRegistry, null]) failed: The current type, PhoenixIT.IScreenFactoryRegistry, is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object ExecuteBuildUp(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at BuildUp_Infinity.Modules.Admin.AdminModule(IBuilderContext )
7) Exception Information
Exception Type: System.InvalidOperationException
Message: The current type, PhoenixIT.IScreenFactoryRegistry, is an interface and cannot be constructed. Are you missing a type mapping?
Data: System.Collections.ListDictionaryInternal
TargetSite: Void ThrowForAttemptingToConstructInterface(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
at BuildUp_PhoenixIT.IScreenFactoryRegistry(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

The innermost exception is the issue.
Your Module type needs a parameter called "screenFactoryRegistry" of type IScreenFactoryRegistry. Since IScreenFactoryRegistry is an interface and you apparently have not done a Register in the container to map that interface to a concrete type, the Unity container throws an exception.
To resolve this, you'd need to map that type in Unity, probably in the ConfigureContainer method of your bootstrapper:
Container.RegisterType<IScreenFactoryRegistry, MyScreenFactoryRegistryImplementation>();

Related

Receiving "xxxx is not a valid GraphQL type name. (Parameter 'value')" when brackets are present in SetPath for ErrorBuilder in HotChocolate 12

This is necessary as I need to show which array element is causing the issue.
This was working fine before in HotChocolate 10, but after upgrading to 12 this is breaking. I am running the following line and it is breaking with the error below it:
IErrorBuilder errorBuilder = new ErrorBuilder()
.SetPath(new List<string>() { "Users[0]"})
"extensions": {
"message": "`Users[0]` is not a valid GraphQL type name. (Parameter 'value')",
"stackTrace": " at HotChocolate.NameString..ctor(String value)
at HotChocolate.NameString.ConvertFromString(String s)
at HotChocolate.Path.FromList(IReadOnlyList`1 path)
at HotChocolate.ErrorBuilder.SetPath(IReadOnlyList`1 path)
at AppAPI.Common.AppServicesExceptionHandler.ConstructQueryError(String type, String path, String idCode, String description, Dictionary`2 parameters) in \\Project.AppAPI HOT CHOCOLATE 12\\AppAPI WebAPI\\Common\\Exceptions\\AppServicesExceptionHandler.cs:line 268
at AppAPI.Common.AppServicesExceptionHandler.ProcessException(Exception e, IConfiguration configuration) in \\Project.AppAPI HOT CHOCOLATE 12\\AppAPI WebAPI\\Common\\Exceptions\\AppServicesExceptionHandler.cs:line 97
at AppAPI.Queries.TestByPeriodQuery.GetTestByPeriod(Int32 accountId, DateTime startUtcDate, DateTime endUtcDate, String aggregatePeriodIdCode, Int32[] Users, Int32[] monitorGroupIds, String[] groupByIdCodes, IMediator mediator, IMapper mapper, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) in \\Project.AppAPI HOT CHOCOLATE 12\\AppAPI WebAPI\\Queries\\TestByPeriodQuery.cs:line 43
at HotChocolate.Resolvers.Expressions.ExpressionHelper.AwaitTaskHelper[T](Task`1 task)
at HotChocolate.Types.Helpers.FieldMiddlewareCompiler.<>c__DisplayClass9_0.<<CreateResolverMiddleware>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at HotChocolate.AspNetCore.Authorization.AuthorizeMiddleware.InvokeAsync(IDirectiveContext context)
at HotChocolate.Utilities.MiddlewareCompiler`1.ExpressionHelper.AwaitTaskHelper(Task task)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.ExecuteResolverPipelineAsync(CancellationToken cancellationToken)
at HotChocolate.Execution.Processing.Tasks.ResolverTask.TryExecuteAsync(CancellationToken cancellationToken)"
}
The error is exactly correct. The ErrorBuilder wants either a Path object or a List<object> which consists of the elements of the path.
ErrorBuilder.New()
.SetMessage("foo")
.SetPath(new List<object> { "Users", 0 })
.Build()
OR
You can use the path object:
ErrorBuilder.New()
.SetMessage("foo")
.SetPath(Path.New("Users").Append(0))
.Build()

Retrieving XML from database with Dapper

I am using Dapper to query a table that includes an XML field:
CREATE TABLE Workflow
(
Guid uniqueidentifier not null,
State xml not null
)
which is then mapped to a property of type XDocument:
public class Workflow
{
public Guid InstanceId { get;set; }
public XDocument State { get;set; }
}
but when I try to query the table, I get the following error:
Error parsing column 1 (State= - String)
at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 4045
at Deserialize038b29f4-d97d-4b62-b45b-786bd7d50e7a(IDataReader )
at Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 1572
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 1443
at MyProject.DapperBase.Query[TResult](String command, DynamicParameters parameters, IDbTransaction transaction, Boolean buffered, Int32 commandTimeout) in d:\\MyProject\\DapperBase.cs:line 122
at MyProject.WorkflowData.Get(Guid identifier) in d:\\MyProject\\WorkflowData.cs:line 41
at MyProject.WorkflowLogic.Save(Workflow workflow) in d:\\MyProject\\WorkflowLogic.cs:line 34
at MyProject.WorkflowsController.Save(Guid id, WorkflowRequest request) in d:\\MyProject\\WorkflowsController.cs:line 97
InnerException: Invalid cast from 'System.String' to 'System.Xml.Linq.XDocument'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at Deserialize038b29f4-d97d-4b62-b45b-786bd7d50e7a(IDataReader )
Other than modifying my POCO to use a string datatype and then convert the string into an XDocument elsewhere, is there a way of getting Dapper to correctly deserialise the XML from the database?
In the end, I just brute-forced it:
public class Workflow
{
public Guid InstanceId { get;set; }
public XDocument StateIn { set { State = value.ToString(); } }
public string State { get;set; }
public XDocument StateOut { get { return XDocument.Parse(State); } }
}
Dapper plays with the State value, and I just set the value on StateIn and read it off StateOut. I feel a little bit dirty coming up with a solution like this, but hey, it works.
Perhaps creating a custom type handler can help? Something like:
public class XDocumentTypeHandler : SqlMapper.TypeHandler<XDocument>
{
public override void SetValue(IDbDataParameter parameter, XDocument value)
{
// set value in db parameter.
}
public XDocument Parse(object value)
{
// parse value from db to an XDocument.
}
}
You have to add the type handler with SqlMapper.AddTypeHandler().
See a sample implementation.

Specified Cast is not Invalid (Enum with int value, Dapper)

I have a class with a (simple, first cut) implementation of user roles:
class User {
public Role Role { get; set; }
// ...
public User() { this.Role = Role.Normal; }
public void Save() { Membership.CreateUser(...) } // System.Web.Security.Membership
}
enum Role : int {
Invalid = 0,
Normal = 1,
SuperUser = 4096
}
Before adding the role, everything worked fine (if that matters).
Now, when I try to fetch users, this line fails:
toReturn = conn.Query<User>("SELECT TOP 1 * FROM dbo.UserProfile WHERE 1=1");
The stack trace (from ELMAH):
System.Data.DataException: Error parsing column 2 (Role=1 - Int16) ---> System.InvalidCastException: Specified cast is not valid.
at Deserialize06df745b-4fad-4d55-aada-632ce72e3607(IDataReader )
--- End of inner exception stack trace ---
at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 2126
at Deserialize06df745b-4fad-4d55-aada-632ce72e3607(IDataReader )
at Dapper.SqlMapper.<QueryInternal>d__d`1.MoveNext() in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 827
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 770
In the database, the column type for Role is smallint.
I'm using Dapper 1.12.1 from NuGet.
Gah. The answer was to make the database and class definitions match.
For smallint (which is what MigratorDotNet generated for me), I needed the enum to derive from short, not int. Everything works now.
Possibly useful Google Code issue: https://code.google.com/p/dapper-dot-net/issues/detail?id=32

NancyFx using embedded views

I'm trying to utilize embedded views feature of NancyFX, but could not manage to make it happen. I've used that example. But still, it looks like Nancy does not use ResourceViewLocationProvider to locate my view.
My bootstrapp configuration,
protected override void ConfigureApplicationContainer(IKernel existingContainer)
{
base.ConfigureApplicationContainer(existingContainer);
var currentAssembly = GetType().Assembly;
ResourceViewLocationProvider.RootNamespaces.Add(currentAssembly, "Candidate.Nancy.SelfHosted.Views");
}
protected override NancyInternalConfiguration InternalConfiguration
{
get { return NancyInternalConfiguration.WithOverrides(x => x.ViewLocationProvider = typeof(ResourceViewLocationProvider)); }
}
My module,
public class AccountModule : NancyModule
{
private readonly IUserManagement _userManagement;
public AccountModule(IUserManagement userManagement) : base("/account")
{
_userManagement = userManagement;
Get["/login"] = p => View["Login.cshtml"];
}
}
Login.cshtml is placed under /Views/Account/Login.cshtml and marked as embedded resource.
If I run application, I got HTTP 500. Seems to me, it tries to find it on filesystem instead of assembly resources.
Nancy.RequestExecutionException: Oh noes! --->
Nancy.ViewEngines.ViewNotFoundException: Unable to locate view
'Login.cshtml' Currently available view engine extensions:
sshtml,html,htm,cshtml,vbhtml Locations inspected:
Login.cshtml,views/Login.cshtml,views/account/Login.cshtml,account/Login.cshtml,views/Account/Login.cshtml,Account/Login.cshtml
Root path:
D:\Development\Projects\candidate.net\src\Candidate.Nancy.Selfhosted\bin\Debug
at Nancy.ViewEngines.DefaultViewFactory.GetRenderedView(String
viewName, Object model, ViewLocationContext viewLocationContext) at
System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite
site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) at
Nancy.ViewEngines.DefaultViewFactory.RenderView(String viewName,
Object model, ViewLocationContext viewLocationContext) at
Nancy.NancyModule.ViewRenderer.get_Item(String viewName) at
Candidate.Nancy.Selfhosted.Modules.AccountModule.<.ctor>b__0(Object p)
in
D:\Development\Projects\candidate.net\src\Candidate.Nancy.Selfhosted\Modules\AccountModule.cs:line
17 at Nancy.Routing.Route.Invoke(DynamicDictionary parameters)
at Nancy.NancyEngine.ResolveAndInvokeRoute(NancyContext context) at
Nancy.NancyEngine.InvokeRequestLifeCycle(NancyContext context,
IPipelines pipelines) --- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context,
ErrorPipeline pipeline, Exception ex)
UPDATE: This issue has been resolved in Nancy 0.12.1.0.

Error in SQL Server to WCF development

I am testing a DB that have two tables (Satellite and Channel) to be exposed as I need using WCF. fortunately, I tried everything I know and online for more that I week now and I can't solve the problem.
This is the service contract IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
List<Satalite> SelectSatalite(int satNum);
[OperationContract]
List<Satalite> SataliteList();
[OperationContract]
List<Channel> ChannelList(int satNum);
[OperationContract]
String Sat(int satNum);
}
And this is the Service.svc.cs file
public class Service : IService
{
DataDbDataContext DbObj = new DataDbDataContext();
public List<Satalite> SataliteList()
{
var satList = from r in DbObj.Satalites
select r;
return satList.ToList();
}
public List<Satalite> SelectSatalite(int satNum)
{
var satList = from r in DbObj.Satalites
where r.SateliteID == satNum
select r;
return satList.ToList();
}
public List<Channel> ChannelList(int satNum)
{
var channels = from r in DbObj.Channels
where r.SateliteID == satNum
select r;
return channels.ToList();
}
public String Sat(int satNum)
{
Satalite satObj = new Satalite();
satObj = DbObj.Satalites.Single(p => p.SateliteID == satNum);
return satObj.Name;
}
}
Whenever I try to run the first three I got an error when testing them using wcftestclient.exe, the last one works with no issues.
The underlying connection was closed: The connection was closed
unexpectedly.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.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 IService.SelectSatalite(Int32 satNum)
at ServiceClient.SelectSatalite(Int32 satNum)
Inner Exception: The underlying connection was closed: The connection
was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout)
What I understand is that the error happens for the custom classes which are the DB tables, if I used a known type by the .net compiler (ex. int or string) it will work with no problems. Fortunately, I didn't find a solution.
The error appears to be one of two reasons:
a timeout since you're returning too much data, e.g. the selection of the data from the database takes too long for the service method to complete in time
or:
the message size is too large, because you're selecting too much data, and thus the WCF communication aborts before the whole data has been returned
My solution:
don't select all data from the tables! Return only as much data as you can really handle / display, e.g. 10 rows, 20 rows or a maximum of 100 rows....
Try this - if you change your method to:
public List<Satalite> SataliteList(int count)
{
var satList = (from r in DbObj.Satalites
select r).Take(count);
return satList.ToList();
}
Can you call this from the WCF Test Client with e.g. count = 10 or count = 50 ??
Adjusting timeout settings on server and client side will help you.
Server Side adjust the SendTimeout attribute of binding element and on client side adjust the RecieveTimeout attribute of binding element.
Thanks,

Resources