Convert String to Int in EF 4.0 - linq

Is there any way of doing this at all? I have a string field in the DB and I want to parse it into a int property in my LINQ query (yes, it must be at the IQueryable level, not in memory).
I know 2 years ago EF 1.0 couldn't do this (even though LINQ to SQL supported this basic functionality out of the box)...but I'm just wondering if anyone has come up with a way of doing this at this point?
Custom function mappings? Special syntax? Anything at all....
UPDATE:
I tried a model defined function as follows:
<Function Name="ConvertToInt32" ReturnType="Edm.Int32">
<Parameter Name="v" Type="Edm.String" />
<DefiningExpression>
CAST(v AS INT)
</DefiningExpression>
</Function>
[EdmFunction("Model.Repository", "ConvertToInt32")]
public static int ConvertToInt32(string value)
{
throw new InvalidOperationException("Only valid when used as part of a LINQ query.");
}
but it doesn't seem to work. I get the runtime exception:
ErrorDescription=Type 'INT' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly.
StackTrace:
at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertTypeName(Node typeName, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertTypeExprArgs(BuiltInExpr astBuiltInExpr, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.<CreateBuiltInExprConverter>b__73(BuiltInExpr bltInExpr, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertBuiltIn(Node astExpr, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.Convert(Node astExpr, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertValueExpression(Node astExpr, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.ConvertQueryStatementToDbExpression(Statement astStatement, SemanticResolver sr)
at System.Data.Common.EntitySql.SemanticAnalyzer.AnalyzeQueryCommand(Node astExpr)
at System.Data.Common.EntitySql.CqlQuery.<AnalyzeQueryExpressionSemantics>b__8(SemanticAnalyzer analyzer, Node astExpr)
at System.Data.Common.EntitySql.CqlQuery.AnalyzeSemanticsCommon[TResult](Node astExpr, Perspective perspective, ParserOptions parserOptions, IEnumerable`1 parameters, IEnumerable`1 variables, Func`3 analysisFunction)
at System.Data.Common.EntitySql.CqlQuery.AnalyzeQueryExpressionSemantics(Node astQueryCommand, Perspective perspective, ParserOptions parserOptions, IEnumerable`1 parameters, IEnumerable`1 variables)
at System.Data.Common.EntitySql.CqlQuery.<>c__DisplayClass4.<CompileQueryCommandLambda>b__3(Node astCommand, ParserOptions validatedParserOptions)
at System.Data.Common.EntitySql.CqlQuery.CompileCommon[TResult](String commandText, Perspective perspective, ParserOptions parserOptions, Func`3 compilationFunction)
at System.Data.Common.EntitySql.CqlQuery.CompileQueryCommandLambda(String queryCommandText, Perspective perspective, ParserOptions parserOptions, IEnumerable`1 parameters, IEnumerable`1 variables)
at System.Data.Mapping.ViewGeneration.Utils.ExternalCalls.CompileFunctionDefinition(String functionFullName, String functionDefinition, IList`1 functionParameters, EdmItemCollection edmItemCollection)
at System.Data.Metadata.Edm.EdmItemCollection.GenerateFunctionDefinition(EdmFunction function)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Metadata.Edm.EdmItemCollection.GetGeneratedFunctionDefinition(EdmFunction function)
at System.Data.Metadata.Edm.MetadataWorkspace.GetGeneratedFunctionDefinition(EdmFunction function)
at System.Data.Query.PlanCompiler.ITreeGenerator.Visit(DbFunctionExpression e)
InnerException:
UPDATE: I got it to work as follows
<Function Name="ConvertToInt32" ReturnType="Edm.Int32">
<Parameter Name="v" Type="Edm.String" />
<DefiningExpression>
CAST(v AS Edm.Int32)
</DefiningExpression>
</Function>

If you are using EFv4 + EDMX you can create custom model defined function which will do the CAST for you. You can then use that function in Linq-to-entities queries.

Related

SpecFlow Coded UI: Multiple public constructors with same maximum parameter count issue

I am using Coded UI & SpecFlow. I have used following template and earlier it was working fine from last 6 months.
https://github.com/aqdasiftekhar/SpecFlowCodedUI/
I am facing following issue from last two days when i try to regenerate feature file.
Exception in Feature.CS File:
We could not find a data exchange file at the path BoDi.ObjectContainerException: Multiple public constructors with same maximum parameter count are not supported! TechTalk.SpecFlow.Utils.CodeDomHelper (resolution path: TechTalk.SpecFlow.CodedUI.MsTest.SpecFlowCodedUITestGenerator)
Please open an issue at https://github.com/techtalk/SpecFlow/issues/
Complete output:
BoDi.ObjectContainerException: Multiple public constructors with same maximum parameter count are not supported! TechTalk.SpecFlow.Utils.CodeDomHelper (resolution path: TechTalk.SpecFlow.CodedUI.MsTest.SpecFlowCodedUITestGenerator)
at BoDi.ObjectContainer.CreateObject(Type type, IEnumerable1 resolutionPath, RegistrationKey keyToResolve) at BoDi.ObjectContainer.TypeRegistration.Resolve(ObjectContainer container, RegistrationKey keyToResolve, IEnumerable1 resolutionPath)
at BoDi.ObjectContainer.CreateObjectFor(RegistrationKey keyToResolve, IEnumerable1 resolutionPath) at BoDi.ObjectContainer.Resolve(Type typeToResolve, IEnumerable1 resolutionPath, String name)
at BoDi.ObjectContainer.<>c__DisplayClass6.b__5(ParameterInfo p)
at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
at BoDi.ObjectContainer.ResolveArguments(IEnumerable1 parameters, RegistrationKey keyToResolve, IEnumerable1 resolutionPath)
at BoDi.ObjectContainer.CreateObject(Type type, IEnumerable1 resolutionPath, RegistrationKey keyToResolve) at BoDi.ObjectContainer.TypeRegistration.Resolve(ObjectContainer container, RegistrationKey keyToResolve, IEnumerable1 resolutionPath)
at BoDi.ObjectContainer.CreateObjectFor(RegistrationKey keyToResolve, IEnumerable1 resolutionPath) at BoDi.ObjectContainer.Resolve(Type typeToResolve, IEnumerable1 resolutionPath, String name)
at BoDi.ObjectContainer.Resolve[T](String name)
at TechTalk.SpecFlow.Generator.GeneratorContainerBuilder.CreateContainer(SpecFlowConfigurationHolder configurationHolder, ProjectSettings projectSettings)
at TechTalk.SpecFlow.Generator.TestGeneratorFactory.CreateGenerator(ProjectSettings projectSettings)
at TechTalk.SpecFlow.VisualStudio.CodeBehindGenerator.Actions.GenerateTestFileAction.GenerateTestFile(GenerateTestFileParameters opts)
Command: C:\Users\aqdas\AppData\Local\Microsoft\VisualStudio\15.0_4d3f9930\Extensions\5yaz3tdw.3ra\TechTalk.SpecFlow.VisualStudio.CodeBehindGenerator.exe
Parameters: GenerateTestFile --featurefile C:\Users\aqdas\AppData\Local\Temp\2\tmpF07B.tmp --outputdirectory C:\Users\aqdas\AppData\Local\Temp\2 --projectsettingsfile C:\Users\aqdas\AppData\Local\Temp\2\tmpF07A.tmp
Working Directory: C:\Users\aqdas\ProjectName\ProjectFolder\Project.TestFolder\packages\SpecFlow.2.1.0\tools
My config File is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section
name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
</configSections>
<specFlow>
<unitTestProvider name="MsTest"
generatorProvider="TechTalk.SpecFlow.CodedUI.MsTest.SpecFlowCodedUITestGenerator, TechTalk.SpecFlow.CodedUI.MsTest"
runtimeProvider="TechTalk.SpecFlow.UnitTestProvider.MsTestRuntimeProvider, TechTalk.SpecFlow" />
</specFlow>
</configuration>
Specflow Generator Code:
namespace TechTalk.SpecFlow.CodedUI.MsTest
{
using System.CodeDom;
using TechTalk.SpecFlow.Generator.UnitTestProvider;
using TechTalk.SpecFlow.Utils;
public class SpecFlowCodedUITestGenerator : MsTestGeneratorProvider
{
public SpecFlowCodedUITestGenerator(CodeDomHelper codeDomHelper)
: base(codeDomHelper)
{
}
public override void SetTestClass(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
{
base.SetTestClass(generationContext, featureTitle, featureDescription);
foreach (CodeAttributeDeclaration customAttribute in generationContext.TestClass.CustomAttributes)
{
if (customAttribute.Name == "Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute")
{
generationContext.TestClass.CustomAttributes.Remove(customAttribute);
break;
}
}
generationContext.TestClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("Microsoft.VisualStudio.TestTools.UITesting.CodedUITestAttribute")));
}
}
}
I have posted issue on GitHub Link https://github.com/techtalk/SpecFlow/issues/1262
I am using
Visual Studio 2017 Version 15.6.7
Microsoft .NET Framework 4.6.1
SpecFlow 2017.2.7 Extension
Specflow 2.0.1 NuGet Package
I will be thankful to you if anyone can help me to fix this issue.
Regards.
I just updated my Specflow version from 2.1 to 1.9 and it worked. this means specflow 1.9+ do not support coded ui when it comes with custom generator provide.

Link all in Xamarin release,failed with Autofac Assembly

When setting the Linker behaviour to "Link all" I get the following error at runtime:
Autofac.Core.DependencyResolutionException.
I've tried adding ignore assembly Autofac but without success.
Setting the Linker behavior to "Link Framework SDKs only" does work but I want to enable "Link All" if possible.
Thanks in advance.
Update :
ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
Autofac.Core.DependencyResolutionException: No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.
No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.
An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)
1
ReflectionActivator.ActivateInstance (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)
An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = RestService (ReflectionActivator), Services = [Eela.Model.Xamarin.Interfaces.IRestService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> No constructors on type 'Eela.Taxi.Service.RestService' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.)
1
InstanceLookup.Activate (System.Collections.Generic.IEnumerable`1[T] parameters)
2
InstanceLookup.Execute ()
3
ResolveOperation.GetOrCreateInstance (Autofac.Core.ISharingLifetimeScope currentOperationScope, Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
4
ResolveOperation.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
5
ResolveOperation.Execute (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
6
LifetimeScope.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
7
Container.ResolveComponent (Autofac.Core.IComponentRegistration registration, System.Collections.Generic.IEnumerable`1[T] parameters)
8
ResolutionExtensions.TryResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters, System.Object& instance)
9
ResolutionExtensions.ResolveService (Autofac.IComponentContext context, Autofac.Core.Service service, System.Collections.Generic.IEnumerable`1[T] parameters)
10
ResolutionExtensions.Resolve (Autofac.IComponentContext context, System.Type serviceType, System.Collections.Generic.IEnumerable`1[T] parameters)
11
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context, System.Collections.Generic.IEnumerable`1[T] parameters)
12
ResolutionExtensions.Resolve[TService] (Autofac.IComponentContext context)
13
App+<OnStart>d__4.MoveNext ()
14
ExceptionDispatchInfo.Throw ()
15
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state)
16
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
17
Thread+RunnableImplementor.Run ()
18
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
19
(wrapper dynamic-method) System.Object:f9684b08-49ee-4f47-8b7c-c59b675c18f3 (intptr,intptr)
So as your Stack Trace indicates. Autofac is trying to instantiate an instance of Eela.Taxi.Service.RestService. However, it seems like the Mono Linker has removed the constructor because it is never directly invoked.
So you could do a couple of things. You could:
Add your assembly to be ignored from the linker
You could add a [Preserve] attribute on your RestService to tell the Linker not to touch it
You could similar to what MvvmCross does have a LinkerPleaseInclude.cs file which describes usage of each type that get stripped out. So for every one you discover you will need to add it here.
So 1. and 2. are fairly self explanatory. You have already used 1. for autofac, just do the same for your own assembly containing RestService. However, the downside here is that nothing in this assembly will be linked, potentially leaving you with a lot more code in it than actually needed.
For 2. you simply add [Preserve] right before declaring your class. So something like:
[Preserve]
public class RestService : IRestService { }
You may also consider using it with AllMembers = true: [Preserve(AllMembers = true)] to keep member fields too.
As for the last option. You basically create a LinkerPleaseInclude.cs in your App project. You let the linker do its job. You continue adding stuff to the class until the Linker does kill your App at runtime. So a start on LinkerPleaseInclude.cs could look like:
[Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
public void Include(IRestService service)
{
service = new RestService();
}
}
This class is never invoked, but it is enough for the linker to know that the constructor of RestService should not be linked out.

Telerik RadGrid.MasterTableView.ExportToExcel() Error: The query results enumerated more than once

I have a RadGrid which is populated with some data. I have a button which will Export to Excel via a serverside callback. The server side code is below. And the error below that. Any suggestions?
RadGrid1.Rebind();
RadGrid1.ExportSettings.IgnorePaging = true;
RadGrid1.MasterTableView.ExportToExcel();
The error is:
The query results cannot be enumerated more than once.
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 query results cannot be enumerated more than once.
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 query results cannot be enumerated more than once.]
System.Data.Linq.SqlClient.OneTimeEnumerable1.GetEnumerator() +884205
System.Data.Linq.SqlClient.SingleResult1.GetEnumerator() +76
System.Linq.Buffer1..ctor(IEnumerable1 source) +302
System.Linq.d__0.MoveNext() +164
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +163
Telerik.Web.UI.GridResolveEnumerable.GetCollectionItemType(Boolean noItemsInEnumerator, Type& collectionItemType, Object& collectionFirstObject) +330
Telerik.Web.UI.GridResolveEnumerable.ParseProperties() +120
Telerik.Web.UI.GridResolveEnumerable.Initialize() +16
Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
Telerik.Web.UI.GridTableView.PerformSelect() +9
Telerik.Web.UI.GridTableView.DataBind() +363
Telerik.Web.UI.RadGrid.DataBind() +73
Telerik.Web.UI.RadGrid.AutoDataBind(GridRebindReason rebindReason) +2488
Telerik.Web.UI.RadGrid.RebindForExport() +119
Telerik.Web.UI.Grid.Export.TableViewExporter.PrepareForExport() +315
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs e) +11056782
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394
You don't want to call Rebind() before the export. Is there a reason for that? Are you changing/manipulating the data right before the export?
If not, there is no need to call Rebind(), since that is really only meant to refresh the data source.

nHibernate second-level cache with memcached and random invalid casts

I have an MVC3 application using nHibernate and memcached as the second level cache provider. We've been intermittently (but much more frequently lately) getting weird casting issues. It happens randomly and invalidating the memcached cache will fix the problem for while.
It only happens in our Production environment because we don't run memcached in our other environments. However I run memcached locally and have tried to get this to occur locally with no luck.
We are using memcached 1.2.6 on Windows. Here's the stack trace. I know it's not going to be enough information to determine anything but if anyone has any ideas about how I could debug this that would be appreciated. I'm trying to get remote debugging on our Production machine but it's a busy time of year and risky.
Unable to cast object of type 'System.Int32' to type 'System.String'.
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.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
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:
[InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.]
(Object , Object[] , SetterCallback ) +4270
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +80
[PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of MyApplication.Business.Data.Program]
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +207
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValues(Object entity, Object[] values) +97
NHibernate.Cache.Entry.CacheEntry.Assemble(Object[] values, Object result, Object id, IEntityPersister persister, IInterceptor interceptor, ISessionImplementor session) +306
NHibernate.Cache.Entry.CacheEntry.Assemble(Object instance, Object id, IEntityPersister persister, IInterceptor interceptor, ISessionImplementor session) +147
NHibernate.Event.Default.DefaultLoadEventListener.AssembleCacheEntry(CacheEntry entry, Object id, IEntityPersister persister, LoadEvent event) +434
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromSecondLevelCache(LoadEvent event, IEntityPersister persister, LoadType options) +800
NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +560
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +229
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +438
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +943
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +99
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +117
NHibernate.Impl.SessionImpl.Get(Object id) +70
MyApplication.Business.Repositories.Repository`1.Get(Object id) +148
We've been encountering the same issue and we have pinpointed the problem to invalid cache entries in the second level cache. In our case the problem arises when we add or remove columns/properties from tables/entities that are cached in the second level cache and deploy the change. The code expects five columns (for argument's sake) whereas the cache stores six columns.
One strategy that we employed in our repository is to catch the exception and invalidate the cache. We then retry the get.
public override T Get(int id)
{
try
{
return base.Get(id);
}
catch (InvalidCastException)
{
_sessionFactory.EvictEntity(typeof (T).Name);
return Get(id);
}
}
Hope this helps!
Most probably this is caused by different dataset returned by the queries on the production environment and your local. The object mapper is getting different data than what its expecting. When trying to convert the data then you are getting these exceptions.

Why is HttpNotificationChannel.Open throwing ArgumentException() E_INVALIDARG?

Here is my code. Everything works fine the first time I run it, i.e. HttpNotificationChannel.Find() returns null.
But the second time I run it, Find() returns the proper thing, however when I get to the Open() call, it throws an exception. Which is really odd, since Open() doesn't take any arguments.
What am I doing wrong?
public string ChannelName = "MyAppChannel";
...
NotificationChannel = HttpNotificationChannel.Find(ChannelName);
if (NotificationChannel == null)
{
NotificationChannel = new HttpNotificationChannel(ChannelName);
}
NotificationChannel.ChannelUriUpdated += new EventHandler(Channel_ChannelUriUpdated);
NotificationChannel.HttpNotificationReceived += new EventHandler(NotificationChannel_HttpNotificationReceived);
NotificationChannel.ErrorOccurred += new EventHandler(Channel_ErrorOccurred);
NotificationChannel.Open(); // <-- Kaboom here, the 2nd time
Here's the full text and stack:
System.ArgumentException: E_INVALIDARG
at Microsoft.Phone.Notification.SafeNativeMethods.ThrowExceptionFromHResult(Int32 hr, Exception defaultException, NotificationType type)
at Microsoft.Phone.Notification.HttpNotificationChannel.Open()
at LiveShare.NotificationManager.Initialize()
at LiveShare.App..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
at MS.Internal.TypeProxy.<>c__DisplayClass30.b__2a()
at MS.Internal.TypeProxy.CreateInstance(UInt32 customTypeId)
at MS.Internal.FrameworkCallbacks.CreateKnownObject(IntPtr nativeRootPeer, UInt32 customTypeId, String initializationString, IntPtr& nativePeer, UInt32 isCreatedByParser)
at MS.Internal.FrameworkCallbacks.CreateUnknownObject(String assemblyName, String typeName, IntPtr nativeRootPeer, String initializationString, UInt32& customTypeId, UInt32& coreTypeId, UInt32& typeFlags, IntPtr& nativePeer)
The correct solution is not to call Open() if Find() succeeds.
This looks very similar to a documented problem with the CTP as described by Nick Harris last April.
Solution: If you try to Open a channel almost immediately after you hit Debug when emulator fires up this issue will occur. The solution is simple – Give the emulator two minutes before making the call.
In case that's not it, there's a good article on Silverlight Show that covers push notifications in a WP7 stock quote app.

Resources