Deserializing JSON TweetSharp TwitterStatus - json

I'm using Daniel Crenna's TweetSharp http://github.com/danielcrenna/tweetsharp
To serialise a TwitterStatus to file I use the code
sw.WriteLine(JsonConvert.SerializeObject(twitterStatus));
which produces the text
{"Id":288653019971727360,"InReplyToUserId":null,"InReplyToStatusId":null,"InReplyToScreenName":null,"truncated":false,"favorited":false,"Text":"Found the bug, dear old regular expressions","Source":"web","User":{"Id":1148081,"FollowersCount":793,"Name":"Tim Regan","Description": [...]
(N.B. I won't include it all, unless that'll help diagnosis?)
My line of code to deserialize the TwitterStatus is
var tweet = (TwitterStatus)JsonConvert.DeserializeObject(line);
But that gives the error
System.InvalidCastException was unhandled
HResult=-2147467262
Message=Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'TweetSharp.TwitterStatus'.
Source=TweetColorMVVM
StackTrace:
at TweetColorMVVM.Model.Tweets.LoadSavedTweets(String screenName) in c:\TFSCML\Users\Tim\MSR.Makefest\TwitterColor\TweetColorMVVM\Model\Tweets.cs:line 132
at TweetColorMVVM.Model.Tweets.LoadTweets(Object state) in c:\TFSCML\Users\Tim\MSR.Makefest\TwitterColor\TweetColorMVVM\Model\Tweets.cs:line 78
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Can anyone see what I've got wrong?

I should have written:
var tweet = (TwitterStatus)JsonConvert.DeserializeObject(line, typeof(TwitterStatus));
It works now.

Related

after upgrade to .net core 2.2, inserts via EF were failing with error

This code has been working fine prior to the upgrade to core 2.2
I can not understand what the parameter name: key is. I have also taken the code generated via the SQL profiler and run it directly in sql management studio and the code executes without any error
This error is generated on the await _context.SaveChangesAsync();
Aslo note that when i downgraded the app back to .net core 2.1 again it worked without any issues
Exception generated is
An exception occurred in the database while saving changes for context type 'RtasWebApp.Data.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.FindIdentityMap(IKey key)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetDependents(InternalEntityEntry principalEntry, IForeignKey foreignKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 containingPrincipalKeys, IReadOnlyList`1 containingForeignKeys, Object oldValue, Object newValue)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 keys, IReadOnlyList`1 foreignKeys, Object oldValue, Object newValue)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectKeyChange(InternalEntityEntry entry, IProperty property)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.PropertyChanged(InternalEntityEntry entry, IPropertyBase propertyBase, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.PropertyChanged(InternalEntityEntry entry, IPropertyBase property, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetCurrentValue(IPropertyBase propertyBase, Object value)
at Microsoft.EntityFrameworkCore.Update.ColumnModification.set_Value(Object value)
at Microsoft.EntityFrameworkCore.Update.ModificationCommand.PropagateResults(ValueBuffer valueBuffer)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagationAsync(Int32 commandIndex, RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.FindIdentityMap(IKey key)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetDependents(InternalEntityEntry principalEntry, IForeignKey foreignKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 containingPrincipalKeys, IReadOnlyList`1 containingForeignKeys, Object oldValue, Object newValue)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 keys, IReadOnlyList`1 foreignKeys, Object oldValue, Object newValue)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectKeyChange(InternalEntityEntry entry, IProperty property)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.PropertyChanged(InternalEntityEntry entry, IPropertyBase propertyBase, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.PropertyChanged(InternalEntityEntry entry, IPropertyBase property, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean setModified)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetCurrentValue(IPropertyBase propertyBase, Object value)
at Microsoft.EntityFrameworkCore.Update.ColumnModification.set_Value(Object value)
at Microsoft.EntityFrameworkCore.Update.ModificationCommand.PropagateResults(ValueBuffer valueBuffer)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagationAsync(Int32 commandIndex, RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Any ideas greatly appreciated
That was a bug in .net core 2.2.2 (see this). In my case, I installed .net core 2.2.3 and the issue was solved. You can download it from here.
I had the same issue and created this on their GitHub: https://github.com/aspnet/EntityFrameworkCore/issues/14419
The issue for me was that I was using services.AddDbContextPool<ApplicationDbContext>(options => in my Startup.cs. Looks like there might be a bug when using the Connection Pool version EF. Try reverting to the plain version of DbContext by removing the word Pool (services.AddDbContext<ApplicationDbContext>(options =>) and see if your issue goes away
I got this issue trying to update lot of records at the same time and call SaveChanges(). This might happen when the update query takes more time to update the records there might be a timeout. You can update the CommandTimeout as a solution. In your data context class Add this to the constructor.
Database.SetCommandTimeout(10000);
So your code will look something like this.
public DataContext(DbContextOptions<DataContext> options, UserContext userContext)
{
_userContext = userContext;
_tenantDbInfo = tenantDbInfo;
Database.SetCommandTimeout(10000);
}

How to Include a reference to a table in Invantive Excel add-in

I'm making a financial report in Excel using the data from Exact Online using the Invantive Control Excel Add-in. In Exact Online I have a classification for the General Ledgers. In my Excel file, I would like to match these classifications on my reporting schedule. Therefore, I made a table with a mapping of the Exact Online classifications and the reporting classifications.
Using the Invantive Control Excel add-in, I entered the following SQL query:
select periods_year_reportingyear_attr
, reportingperiod_attr
, division_code
, division_hid
, division_name
, periods_year_years_balance_code_attr
, periods_year_years_balance_description
, '=I_EOL_GL_ACTCLN_CODE($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})' verdichting_code
, '=I_EOL_GL_ACTCLN_DESCRIPTION($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})' verdichting_naam
, '=i_eol_bal_year_open($C{E,.,.,^+2,.} , $C{E,.,.,^,.}, $C{E,.,.,^+5,.}) + if($C{E,.,.,^+1,.} = 1, 0, i_eol_bal_pder($C{E,.,.,^+2,.},$C{E,.,.,^,.},1,$C{E,.,.,^+1,.}-1,$C{E,.,.,^+5,.}))' startsaldo
, balance
, '=i_eol_bal_year_open($C{E,.,.,^+2,.} , $C{E,.,.,^,.}, $C{E,.,.,^+5,.}) + i_eol_bal_pder($C{E,.,.,^+2,.},$C{E,.,.,^,.},1,$C{E,.,.,^+1,.},$C{E,.,.,^+5,.})' eindsaldo
, periods_year_years_balance_balancetype_attr
, '=INDEX(tab_reporting[Reporting],MATCH(NUMBERVALUE(I_EOL_GL_ACTCLN_CODE($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})),tab_reporting[GL Class - Code],0))' reporting
from balancelinesperperiod
order
by periods_year_reportingyear_attr
, reportingperiod_attr
, division_hid
, periods_year_years_balance_code_attr
In which tab_reporting is the name of a table with de mapping of the reporting classifications and the Exact Online. This table is on a different tab within Excel. When I review the data I will see these results:
Which, to me looks oke.
One thing that I don't understand is that it looks like there are 4 fields on position 14. The one formula appears to create 4 different data fields in stead of one.
I could send the Excel file upon request.
The problem is that I end up with this error message:
itgensdf031: Kan velden van blok 'Balans (bal)' niet verversen. Can
not refresh fields completely. The field '});TAB_REPORTING[GL CLASS -
CODE];0))'' has a Formule which will get lost when the field is
deleted since it no longer occurs in the SQL.
Migrate all relevant field settings that you need to keep and would
get lost when this field is removed. Hire a consultant if you don't
know how to do this.
Type: Invantive.Data.ValidationException at
Invantive.Data.ValidationException..ctor(String messageCode, String
messageText, String kindRequest, String localStackTrace, String nk,
Exception innerException) at
Invantive.Producer.Control.Utility.RefreshFields(ModelCache
modelCache, iea_blocks_v block, Boolean allowLoadFromCache) at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) at
System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object
argument) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() at
Invantive.Producer.Control.Utility.RefreshFields(ModelCache
modelCache, iea_blocks_v block, Boolean allowLoadFromCache) in
File173:line 4362 at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) in File174:line 299 Type:
Invantive.Data.ValidationException at
Invantive.Data.ValidationException..ctor(String messageCode, String
messageText, String kindRequest, String localStackTrace, String nk,
Exception innerException) at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) at
System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object
argument) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Invantive Control for Excel (stable-20161021-2025-ge3e5e61 Prod,
L162135034)
It seems that you have managed through a bug somewhere to create multiple fields at position 14. This is a corruption of the repository.
I recommend to first remove the fields at position 14 by:
unchecking their properties
remove the part from the SQL that defines the fields at position 14 (save it somewhere),
and then pressing Refresh in the fields tab.
Check that the fields at position 14 are gone.
The re-add the part from the SQL that defines the fields at position 14.
It should work again.

BackgroundUploadAsync Error object not set to an instance

I tried to upload a file to OneDrive. I'm successfully connecting and authenticating to OneDrive but when attempting to upload, I get the error: Object reference not set to an instance of an object.
The code is:
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Release all resources from DB
App.AppViewModel.DisposeCurrentDB();
IsolatedStorageFileStream toUploadStream = iso.OpenFile(AppResources.DatabaseName + ".sdf", FileMode.Open);
LiveConnectClient liveClient = new LiveConnectClient(oneDriveAuthClient.Session);
try
{
LiveOperationResult uploadResult = await liveClient.BackgroundUploadAsync(
oneDriveFolderId,
DatabaseBackupname,
toUploadStream.AsInputStream(),
OverwriteOption.Overwrite);
dynamic result = uploadResult.Result;
MessageBox.Show("Upload successful. Uploaded to " + result.source);
}
catch (LiveConnectException ex)
{
MessageBox.Show("Error uploading backup: " + ex.Message);
}
App.AppViewModel.RefreshCurrentDB();
The BackgroundUploadAysnc method throws the exception. The oneDriveFolderId is set and exists in OneDrive. DatabaseBackupname is a correct new filename which doesn't exist in OneDrive. I checked the stream in debugger and this object was not empty and had a size.
Stacktrace
at Microsoft.Live.Operations.TailoredUploadOperation.<OnGetUploadLinkCompleted>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__4(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
I changed the upload code to this:
LiveUploadOperation operation = await liveClient.CreateBackgroundUploadAsync(
oneDriveFolderId,
DatabaseBackupname,
toUploadStream,
OverwriteOption.DoNotOverwrite);
await operation.StartAsync();
and the CreateBackgroundUploadAsync method throws the following exception:
Message = "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
at Windows.Networking.BackgroundTransfer.BackgroundUploader.CreateUploadFromStreamAsync(Uri uri, IInputStream sourceStream)
at Microsoft.Live.Operations.CreateBackgroundUploadOperation.<OnGetUploadLinkCompleted>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__4(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
It is not really a solution for the error message, but I changed the Live.SDK reference to the Windows Phone dll and now I can use the BackgroundUploadAsync(path, uri, overwrite) method and it works.
I also had to change the Auth method.
I wasted a few hours on this exact problem. For me it was happening on a Windows Phone 8.0 app that I was migrating to Windows Phone 8.1 Silverlight. What finally resolved things for me was updating to the latest Microsoft Advertising SDK for Windows Phone. I went from version 6.2.960.0 to 8.1.50112.0. As soon as I rebuilt after that, my uploads to OneDrive started to work perfectly. Not at all sure what the root cause was but figured I'd share it here in case it helps anyone.
To be clear, my project file went from this:
<Reference Include="Microsoft.Advertising.Mobile, Version=6.2.960.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.Advertising.Mobile.UI, Version=6.2.960.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
to this:
<Reference Include="Microsoft.Advertising.Mobile, Version=8.1.50112.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.Advertising.Mobile.Common, Version=8.1.50112.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.Advertising.Mobile.UI, Version=8.1.50112.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
I had to "associate" my app "with the Store."
Right-click on the project line in the Solution Explorer in Visual Studio.
Left-click on Store -> Associate App with the Store
I had to sign up as a Microsoft developer (and pay for it), but once I did that, my calls to BackgroundUploadAsync returned reasonable values.
Since it was taking me in the direction I would eventually be going anyway, I figured, What the Heck.

htmlagilitypack invalid cast exception when grabbing nodes with certain classes

I'm wanting to grab div items from an HTML page that contains certain class types.
I'm using this:
HtmlNode authorNode =(HtmlNode) doc.DocumentNode.Descendants("div").Where(d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Split(' ').Any(b => b.Equals("byline") && b.Equals("list-pipes")));
and I get this exception
System.InvalidCastException was unhandled
HResult=-2147467262
Message=Unable to cast object of type 'WhereEnumerableIterator`1[HtmlAgilityPack.HtmlNode]' to type 'HtmlAgilityPack.HtmlNode'.
Source=Project1
StackTrace:
at Project1.Scraper.processBI_Article(String uri) in C:\Users\jgarber\Documents\Visual Studio 2010\Projects\Project1\Project1\Scraper.cs:line 233
at Project1.Scraper.processNode(String uri, HtmlNode parentNode) in C:\Users\jgarber\Documents\Visual Studio 2010\Projects\Project1\Project1\Scraper.cs:line 194
at Project1.Scraper.ExecuteScraping() in C:\Users\jgarber\Documents\Visual Studio 2010\Projects\Project1\Project1\Scraper.cs:line 107
at Project1.WebscrapingMain.Main() in C:\Users\jgarber\Documents\Visual Studio 2010\Projects\Project1\Project1\WebscrapingMain.cs:line 64
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I'm confused as to what I need to do now in order to get this to work. Any help would be greatly appreciated.
The code returns an Enumerable of HtmlNode, not just one node (you're using .Where, which returns a all items matching). If you're only interested in the first item, use First or FirstOrDefault or if you know there to be only one item, use Single or SingleOrDefault instead of just Where.
So:
HtmlNode authorNode = doc.DocumentNode.Descendants("div")
.Where(d => d.Attributes.Contains("class")
&& d.Attributes["class"].Value.Split(' ')
.Any(b => b.Equals("byline") && b.Equals("list-pipes")))
.FirstOrDefault();
Or assign it to a Enumerable of HtmlNode:
IEnumerable<HtmlNode> authorNodes = doc.DocumentNode.Descendants("div")
.Where(d => d.Attributes.Contains("class")
&& d.Attributes["class"].Value.Split(' ')
.Any(b => b.Equals("byline") && b.Equals("list-pipes")));

InvalidOperation Exception, Background Audio Agent, Windows Phone 8

I'm trying to add a background AudioPlayer to a windows phone 8 application.
I've created the main project and the background audio agent. I've added a reference to the background audio player to the main project, and added the following into the app manifest file.
<ExtendedTask Name="BackgroundTask">
<BackgroundServiceAgent Name="myCastsbackgroundaudio" Type="myCastsbackgroundaudio.AudioPlayer" Source="myCastsbackgroundaudio" Specifier="AudioPlayerAgent"/>
</ExtendedTask>
I've double and triple checked the references and I'm sure they point to the right things.
I'm sharing information between the two applications using IsolatedStorage and the following code
private AudioTrack GetNextTrack()
{
string myTrack = settingsHelper.Read("track", string.Empty);
AudioTrack track = new AudioTrack()
{
Title = "Generic Title",
Source = new Uri("isostore://"+ myTrack, UriKind.Relative)
};
return track;
}
This would appear to pick up the track name fine, and then attempt to create the Audiotrack for playback. At this point, the application will throw the following error.
System.InvalidOperationException was unhandled
_HResult=-2146233079
_message=Operation is not valid due to the current state of the object.
HResult=-2146233079
Message=Operation is not valid due to the current state of the object.
Source=Microsoft.Phone
StackTrace:
at Microsoft.Phone.BackgroundAudio.AudioTrack.set_Title(String value)
at myCastsbackgroundaudio.AudioPlayer.GetNextTrack()
at myCastsbackgroundaudio.AudioPlayer.OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
at Microsoft.Phone.BackgroundAudio.AudioPlayerAgent.CallOnPlayStateChanged(ParameterPropertyBag parameters)
at Microsoft.Phone.BackgroundAudio.AudioPlayerAgent.Invoke(Uri uri, ParameterPropertyBag parameters)
at Microsoft.Phone.BackgroundAgentDispatcher.AgentRequest.Invoke()
at Microsoft.Phone.BackgroundAgentDispatcher.InvocationThread()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
For the life of me, I can't figure what's causing the error. Nothing jumps out as the root cause, and I've done this a couple of times for other apps with no issue.
Any advice or insight is appreciated.
edit: As requested, I have pasted the OnPLayStateChanged code below
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
switch (playState)
{
case PlayState.TrackEnded:
player.Track = GetNextTrack();
break;
case PlayState.TrackReady:
player.Play();
break;
case PlayState.Shutdown:
// TODO: Handle the shutdown state here (e.g. save state)
break;
case PlayState.Unknown:
break;
case PlayState.Stopped:
break;
case PlayState.Paused:
break;
case PlayState.Playing:
break;
case PlayState.BufferingStarted:
break;
case PlayState.BufferingStopped:
break;
case PlayState.Rewinding:
break;
case PlayState.FastForwarding:
break;
}
NotifyComplete();
}
Also to add some additional info, the error is thrown at the creation of the audio track in GetNextTrack, so this code block
AudioTrack track = new AudioTrack()
{
Title = "Generic Title",
Source = new Uri("isostore://"+ myTrack, UriKind.Relative)
};
AudioTrack is very sensitive to edits on the track properties. You should use the constructor to set these values, or else use AudioTrack.BeginEdit/EndEdit.
So try:
var track =
new AudioTrack(
new Uri("isostore://"+ myTrack, UriKind.Relative),
myTrack,
string.Empty,
string.Empty,
null);