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.
Related
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.
I'm attempting to create a Windows Runtime Component for use in a Windows 8 app.
This is essentially a helloworld level application and so has nothing complex. The only thing that I need to do to replicate the issue is to include a pair of methods such as the following:
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new List<string>().ToArray();
}
Whenever I compile the project, the Windows Metadata Exporter crashes.
I've dug into the errors generated in the output window by increasing the build verbosity and I've found that the error occurs after "Exporting 'obj\Debug\HelloWorld.Logic.winmdobj'."
By attempting to run winmdexp.exe from command line with the same parameters, it seems that it's having trouble finding metadata for the System.Xml files. (warning WME0004 : Could not find referenced metadata 'C:\Program Files(x86)\ReferenceAssemblies\Microoft\Framework.NETCore\v4.5.1\System.Xml.Serialization.dll'.)
The full stack trace of the error is:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Tools.WinMDExp.AssemblyReferenceExtensionMethods.IsWindowsRuntimeMetadata(IAssemblyReference assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.IsWindowsRuntimeType(ITypeReference type, Boolean allowGenericParam)
at Microsoft.Tools.WinMDExp.ExportValidator.<>c__DisplayClasse.<GetAlternativeTypes>b__8(<>f__AnonymousType0`2 <>h__TransparentIdentifier5)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativeTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& isTask, Boolean allowGenericTypeParam)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativesTypesForGenericTypes(IGenericTypeInstanceReference parameterType, IMethodDefinition containingMethod, String& errorMsg)
at Microsoft.Tools.WinMDExp.ExportValidator.CheckAlternateTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportParameterType(IMethodDefinition containingMethod, ITypeReference parameterType, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportMethod(IMethodDefinition method)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IEnumerable`1 methods)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(INamedTypeDefinition namedTypeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Traverse(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Dispatcher.Visit(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataReader.ObjectModelImplementation.NamespaceType.Dispatch(IMetadataVisitor visitor)
at Microsoft.Tools.WinMDExp.ExportValidator.Validate(ITypeDefinition type)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IModule module)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IAssembly assembly)
at Microsoft.Cci.MetadataTraverser.Traverse(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.Export(IAssembly assembly)
at Microsoft.Tools.WinMDExp.Exporter.Export()
at Microsoft.Tools.WinMDExp.Program.Main(String[] args)
If anyone has any idea what's going on and how I can get my component compiling I'd be grateful.
James
P.S. I transferred the project to a colleague's PC and they had the same issue so I doubt if it's anything to do with my setup (Windows 8.1 x64, Visual Studio 2013 Ultimate).
I've managed to figure this out myself.
It seems as though there is a bug when using string[] (or other arrays) as the generic type for IAsyncOperation.
I have managed to work around this because actually I will want to return IDictionary objects and ILists, which work fine:
/* //Won't Work - crashes Windows Metadata Exporter
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new [] {"I am a string"};
}
*/
//This Works
public IAsyncOperation<IList<string>> GetThingsList()
{
return GetThingsListAsync().AsAsyncOperation();
}
private async Task<IList<string>> GetThingsListAsync()
{
return new[] { "I am a string" };
}
Hopefully this will be of use to anyone else who comes across this weird behaviour.
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);
I'm building this WP7 app that uses a video game API to get the statistics of someone's character (just to help learn silverlight). It grabs the players details from the web service and stores them on isolated storage on the phone to relieve strain from the server.
Originally I had a class which had both the cache writing and reading function, but now i've had to seperate it out into two seperate classes. The cache writing class doesn't matter at the moment, just the cache reading class.
On line 7, it throws an exception saying "Operation not permitted on IsolatedStorageFileStream.", but only during the second time it instantiates the class. I've done some checking with debug and it says the file definately exists, but it stops after the second using clause.
Can anyone help me with this please? I feel like I'm missing something really obvious.
public class CacheReader
{
public PlayerData GetPlayerData(string gamertagIn)
{
using (IsolatedStorageFile CachedReachData = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = CachedReachData.OpenFile(gamertagIn + ".xml", FileMode.Open))
{
Debug.WriteLine("Data Retrieved from cache");
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
PlayerData loadedPlayer = (PlayerData)serializer.Deserialize(stream);
return loadedPlayer;
}
}
}
}
[EDIT 1]
This is the stack trace i get:
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFile.OpenFile(String path, FileMode mode, FileAccess access)
at ReachPhoneApp.CacheReader.GetPlayerFromCache(String gamertagIn)
at ReachPhoneApp.Page2.GetPlayerData()
at ReachPhoneApp.Page2.cacheWriter_UpdateComplete()
at ReachPhoneApp.CacheWriter.WritePlayerDataToCache(String fileNameIn, Object objectIn)
at ReachPhoneApp.CacheWriter.client_GetGameHistoryCompleted(Object sender, GetGameHistoryCompletedEventArgs e)
at ReachPhoneApp.ReachAPI.ReachApiSoapClient.OnGetGameHistoryCompleted(Object state)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Check that you don't somehow have two threads accessing IsolatedStorage at the same time (ie. in VS Debug.View.Threads and verify that at the time of the exception you don't have multiple paths through the same IsoStore code).
This happened in my WP7 code once every few days and was tricky to find, as it seemed to occur only when not connectected to the debugger.
You need to call:
stream.Close();
before
return loadedPlayer;
I think the problem is that you didn't specify that multiple threads could read/write at the same time by specifying a System.IO.FileShare.ReadWrite or whatever access you need as the last parameter of OpenFile.
See the discussion here on the Microsoft Forums.
I ran into this issue as well, but for completely different reasons as mentioned above. I hadn't created the directory that I was saving into.
private void SaveStringDataToStorage(string sDirectory, string sFileName, string sFileContent)
{
string sPath;
//
using (IsolatedStorageFile oFile = solatedStorageFile.GetUserStoreForApplication())
{
if (!oFile.DirectoryExists(sDirectory))
oFile.CreateDirectory(sDirectory);
//
sPath = Path.Combine(sDirectory, sFileName);
//
using (var oWriter = new StreamWriter(new IsolatedStorageFileStream(sPath, FileMode.Create, oFile)))
oWriter.Write(sFileContent);
}
}
Using this code will work if you had the same problem as me, plus it's pretty simple so you can adapt it to whatever you need. I was using this code before I had issues, but I'd forgotten the ! so the directory was never created haha. Just typical. Hope this helps :)
EDIT
Looking closer at the original question, it may be that the file didn't exist. I think it's always best to do IsolatedStorageFile.DirectoryExists() and IsolatedStorageFile.FileExists() before trying to access either location, whether you are reading or writing.
By default when you use IsolatedStorageFile.OpenFile("filename", FileMode.Open) your file gets locked by this thread and no other thread would be able to access this file until 1st thread close it. But if you like to share your file in multiple threads for read purpose only then I would recommend you to use following override
IsolatedStorageFile.OpenFile("filename", FileMode.Open, FileAccess.Read, FileShare.Read)
see details here
We are getting a SecurityException when using Entity framework on godaddy. The entity has been configured against a MySQL store. (v. 6.1.2) A bit of weirdness with the exception though... Looking at the exception stack it seems to imply that if we open up a connection to MySQL anywhere in the site, then we should get the same exception; however, opening up a MySQL connection directly seems to be working in another part of the site...
Here's the verification:
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
connection.Open();
...
}
Anyone run across a similar issue?
The complete error stack trace is as follows:
[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags) +0
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +470
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1051
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111
System.Resources.ResourceManager.CreateResourceSet(Stream store, Assembly assembly) +357
System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +471
System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +583
System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +583
System.Resources.ResourceManager.GetString(String name, CultureInfo culture) +74
MySql.Data.MySqlClient.Resources.get_PerfMonCategoryName() +40
MySql.Data.MySqlClient.PerformanceMonitor..ctor(MySqlConnection connection) +43
MySql.Data.MySqlClient.MySqlConnection.Open() +434
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +173
System.Data.EntityClient.EntityConnection.Open() +96
System.Data.Objects.ObjectContext.EnsureConnection() +81
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +46
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
jet.Controllers.WorkOrder.WorkOrderView..ctor() +219
jet.Controllers.WorkOrder.WorkOrderView.get_Instance() +29
jet.Controllers.WorkItemController.Index() +11
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Weird one. GoDaddy shared-hosting ASP.NET apps execute under Medium Trust, and perf counter creation probably requires full trust, but perf counter creation is not what's failing here. (and if it failed, it wouldn't propagate out since perf coutner creation exceptions are swallowed by mySQL client code).
Instead, it's failing trying to access a string resource, before perf counter creation. The failure is with this line of code in Resources.Designer.cs of the MySQL client:
return ResourceManager.GetString("PerfMonCategoryName", resourceCulture)
A few things to try, in increasing order of difficulty:
ensure you have the MySQL client DLLs in your app's BIN directory and you're not trying to load the client DLL out of GoDaddy's GAC. Never depend on GoDaddy-supplied binaries if you can avoid it!
switch to EN-US culture so the client doesn't have to go hunting for another resource DLL, and see if the problem goes away.
Build the .NET client from source code, instead of copying DLLs from a binary distribution into your app's BIN directory. This will make problems like this easier to debug since the mySQL code won't be a black box. And, in a pinch, will let you change the problematic resource-fetching calls (or hard-code the locale)! :-)
BTW, in case you're tempted to set "Use Performance Monitor=false" in your connection string to try to evade the problem, don't bother. The problematic code gets executed regardless of that setting:
public PerformanceMonitor(MySqlConnection connection)
{
this.connection = connection;
//// this line is where it bombs
string categoryName = Resources.PerfMonCategoryName;
//// this line is affected by connection string setting
if (connection.Settings.UsePerformanceMonitor && procedureHardQueries == null)
{
try
{
procedureHardQueries = new PerformanceCounter(categoryName,
"HardProcedureQueries", false);
procedureSoftQueries = new PerformanceCounter(categoryName,
"SoftProcedureQueries", false);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
}
Justin was spot on. Problem was godaddy has an older version of the MySql dll in their gac and the entity framework was picking it up!
Here's the fix. (Apply this to web.config)
<configuration>
...
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d"/>
<bindingRedirect oldVersion="5.0.7.0" newVersion="6.1.2.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
...
</configuration>
I simply added trust level="Full" to my Web config file, and it worked