Following Microsoft AZ-204 Learning Path, Encountered error "Unhandled exception. System.NotSupportedException: Stream does not support reading." - azure-blob-storage

I am following the AZ-204: Develop solutions that use Blob storage / Work with Azure Blob storage tutorial located here.
The code is copy/paste but I have encountered an error. I am not a .net developer and I have no idea how to resolve this. Microsoft offers no troubleshooting resources with this self-led material. I'm hoping to find help for resolving this error.
The file I am attempting to run:
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
Console.WriteLine("Azure Blob Storage exercise\n");
// Run the examples asynchronously, wait for the results before proceeding
ProcessAsync().GetAwaiter().GetResult();
Console.WriteLine("Press enter to exit the sample application.");
Console.ReadLine();
static async Task ProcessAsync()
{
// Copy the connection string from the portal in the variable below.
string storageConnectionString = "[redacted]";
// Create a client that can authenticate with a connection string
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnectionString);
// COPY EXAMPLE CODE BELOW HERE
// CREATE A CONTAINER
//Create a unique name for the container
string containerName = "wtblob" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
Console.WriteLine("A container named '" + containerName + "' has been created. " +
"\nTake a minute and verify in the portal." +
"\nNext a file will be created and uploaded to the container.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// UPLOAD BLOBS TO A CONTAINER
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "wtfile" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
Console.WriteLine("\nThe file was uploaded. We'll verify by listing" +
" the blobs next.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// LIST THE BLOBS IN A CONTAINER
// List blobs in the container
Console.WriteLine("Listing blobs...");
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
Console.WriteLine("\nYou can also verify by looking inside the " +
"container in the portal." +
"\nNext the blob will be downloaded with an altered file name.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DOWNLOAD BLOBS
// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();
using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
await download.Content.CopyToAsync(downloadFileStream);
}
Console.WriteLine("\nLocate the local file in the data directory created earlier to verify it was downloaded.");
Console.WriteLine("The next step is to delete the container and local files.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DELETE A CONTAINER
// Delete the container and clean up local files created
Console.WriteLine("\n\nDeleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Finished cleaning up.");
}
I am able to verify the container was created in the azure portal, then the code runs up to line 46 where "Uploading to Blob storage as blob:" is logged, then encounters the error.
The console output (including prior to the error):
Azure Blob Storage exercise
A container named 'wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386' has been created.
Take a minute and verify in the portal.
Next a file will be created and uploaded to the container.
Press 'Enter' to continue.
Uploading to Blob storage as blob:
https://[redacted].blob.core.windows.net/wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386/wtfilebfbd8b5e-d5b3-487c-885b-364db2fe126a.txt
Unhandled exception. System.NotSupportedException: Stream does not support reading.
at System.IO.Strategies.BufferedFileStreamStrategy.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at System.IO.FileStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Storage.NonDisposingStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Core.RequestContent.StreamContent.WriteToAsync(Stream stream, CancellationToken cancellation)
at Azure.Core.Pipeline.HttpClientTransport.PipelineRequest.PipelineContentAdapter.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
at System.Net.Http.HttpContent.<CopyToAsync>g__WaitAsync|56_0(ValueTask copyTask)
at System.Net.Http.HttpConnection.SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>g__ProcessAsyncInner|4_0(HttpMessage message, ReadOnlyMemory`1 pipeline)
onary`2 metadata, IDictionary`2 tags, BlobRequestConditions conditions, Nullable`1 accessTier, BlobImmutabilityPolicy immutabilityPolicy, Nullable`1 legalHold, IProgress`1 progressHandler, UploadTransferValidationOptions transferValidationOverride, String operationName, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.Specialized.BlockBlobClient.<>c__DisplayClass64_0.<<GetPartitionedUploaderBehaviors>b__0>d.MoveNext()
--- End of stack trace from previous location --- at Azure.Storage.PartitionedUploader`2.UploadInternal(Stream content, Nullable`1 expectedContentLength, TServiceSpecificData args, IProgress`1 progressHandler, Boolean async, CancellationToken cancellationToken) at Azure.Storage.Blobs.BlobClient.StagedUploadInternal(Stream content, BlobUploadOptions options, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.BlobClient.UploadAsync(Stream content) at Program.<<Main>$>g__ProcessAsync|0_0() in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 51
at Program.<Main>$(String[] args) in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 7
I copied the code from the tutorial and tried to run it following the given instructions. It starts out fine but throws an error when trying to upload the new file to the blob. I expected the new file to be written to the blob, and the remaining instructions to be executed.

I was able to repro the issue locally with the same code and after doing below changes I was able to upload it successfully:
Old Code:
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
// Modified Code
FileStream uploadFileStream = File.Open(localFilePath, FileMode.Open);
blobClient.Upload(uploadFileStream);
uploadFileStream.Close();
Let me know if that helps !

Related

File.Delete() throw "owner died" in Xamarin

Generally, file deletion can be performed correctly on most Android phones
However, when I run this line of code on "Huawei art-al00x (Android 10.0 - API 29)", the operation throws an exception "owner died"
I can create files and write data, but I can't delete files
I've never been in this situation before
After Google searched, there is still no result
After the second test, I found that if I checked the file in the file manager, I could delete it smoothly, while if I didn't check the file, it would throw an exception
The Code:
string path = "Want Save Path";
byte[] buffer = new uint8_t[73790];
using (BinaryWriter BW = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
BW.Write(buffer, 0, (int)exer.Size);
BW.Flush();
BW.Close();
Console.WriteLine("USM:Save Image Data Success");
}
StackTrace:
at System.IO.FileSystem.DeleteFile (System.String fullPath) [0x00065]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs:215
at System.IO.File.Delete (System.String path) [0x0000e]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:107
at DebugTest.MyView.MainPage_OperateView.TTTFrame_Click () [0x00014]
in G:\VS2019 Projects\DebugTest\DebugTest\DebugTest\MyView\MainPage_OperateView.xaml.cs:263

google drive Api not working in production "Failed to launch browser with"

i'm facing an issue with google drive API, it is working on my local machine, but once i deploy the project to the server, the google drive API service stops working,
it is throwing an oauth2 exception, i think i need to do something on the google drive api console but i don't know what it is or where to start
the credentiels i'm currently using are OAuth 2.0 Client IDs and client Secret, type Desktop.
please any help is appreciated
here is the exception i get.
An unhandled exception occurred while processing the request.
AggregateException: One or more errors occurred. (Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=813040219774-atf2l4751d1tkjeegoeb7d4lituel9ev.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A42257%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details.)
System.Threading.Tasks.Task<TResult>.GetResultCore(bool waitCompletionNotification)
NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=813040219774-atf2l4751d1tkjeegoeb7d4lituel9ev.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A42257%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details.
Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
Stack Query Cookies Headers Routing
AggregateException: One or more errors occurred. (Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=813040219774-atf2l4751d1tkjeegoeb7d4lituel9ev.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A42257%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details.)
System.Threading.Tasks.Task<TResult>.GetResultCore(bool waitCompletionNotification)
ElseForty.FileServices.Files+GoogleDrive.GetService() in Files.cs
ElseForty.FileServices.Files+GoogleDrive.UploadFileAsync(IFormFile file) in Files.cs
ElseForty.Controllers.BugReportController.Send(User_BugReportViewModel model) in BugReportController.cs
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Show raw exception details
NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=813040219774-atf2l4751d1tkjeegoeb7d4lituel9ev.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A42257%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details.
Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.AuthorizeAsync(string userId, CancellationToken taskCancellationToken)
Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(Initializer initializer, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken, IDataStore dataStore, ICodeReceiver codeReceiver)
Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken, IDataStore dataStore, ICodeReceiver codeReceiver)
Show raw exception details
UPDATE
i'm using the google drive api for my web application for visitor to upload images,
public static DriveService GetService()
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "elsefortydisk",
});
}
public static async Task<string> UploadFileAsync(IFormFile file)
{
var fileName = GetUniqueFileName(file.FileName);
var service = GetService();
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = Path.GetFileName(fileName);
fileMetadata.MimeType = file.ContentType;
fileMetadata.Parents = new List<string>() { "14kECd48VL6xhS9ArQL3Lh7oLT6npAVg-" };
FilesResource.CreateMediaUpload request;
using (var stream = file.OpenReadStream())
{
request = service.Files.Create(fileMetadata, stream, file.ContentType);
request.Fields = "id";
await request.UploadAsync();
}
var responce = request.ResponseBody;
var pemission = new Permission();
pemission.Type = "anyone";
pemission.Role = "reader";
try
{
service.Permissions.Create(pemission, responce.Id).Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return responce.Id;
}
Issues You Have your question tagged asp.net core and you state that you are uploading it to a server. Yet you have also stated that you have created a desktop client on google developer console
am currently using are OAuth 2.0 Client IDs and client Secret, type Desktop.
If you are using asp .net core then you are creating a web application and should there for have created web browsers credentials.
The code you are using was desngied for an installed / desktop application where the code is run on the machine the user is using. Example You are using GoogleWebAuthorizationBroker.AuthorizeAsync which is intended for use with installed applications. The way it is designed it opens the browser window on the machine that its running on which is why you are seeing the following error message.
NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=813040219774-atf2l4751d1tkjeegoeb7d4lituel9ev.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A42257%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details.
Your code works locally because it is able to open the browser window on the machine its running when run on a web server it will attempt to open the web browser consent window on the web server which is not what you want it to be doing you want it to be opening the browser consent on the users client machine.
If you are trying to create a web application using Asp .net core then you need to create web application credentials, and configure the web application as follows.
Configuring an asp.net core application to access the google apis is quite different i have a tutorial on it here which will walk you though the configuration of the setup however Asp .net core 3 and Google login
// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = ClientId;
options.ClientSecret = ClientSecret;
});
Calling the api itself which will request authorization is mainly done with an attribute.
[GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)]
public async Task<IActionResult> DriveFileList([FromServices] IGoogleAuthProvider auth)
{
GoogleCredential cred = await auth.GetCredentialAsync();
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
var files = await service.Files.List().ExecuteAsync();
var fileNames = files.Files.Select(x => x.Name).ToList();
return View(fileNames);
}
Tip
Desktop / installed applications are designed to run on a single machine that the user is in front of and using.
Web applications are run from web servers and the user contacts them though a web browser.
These are two different types of applications and the clients created on google developer console are different as is the code to use each of these clients they cant be mixed.

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

Use of undefined keyword value 1 for event TaskScheduled

When debugging my universal Windows (8.1) app i encounter the following error from time to time:
System.ArgumentException was unhandled
_HResult=-2147024809
_message=Use of undefined keyword value 1 for event TaskScheduled.
HResult=-2147024809
IsTransient=false
Message=Use of undefined keyword value 1 for event TaskScheduled.
Source=mscorlib
StackTrace:
at System.Diagnostics.Tracing.ManifestBuilder.GetKeywords(UInt64 keywords, String eventName)
at System.Diagnostics.Tracing.ManifestBuilder.StartEvent(String eventName, EventAttribute eventAttribute)
at System.Diagnostics.Tracing.EventSource.CreateManifestAndDescriptors(Type eventSourceType, String eventSourceDllName, EventSource source)
at System.Diagnostics.Tracing.EventSource.EnsureInitialized()
at System.Diagnostics.Tracing.EventSource.SendCommand(EventListener listener, Int32 perEventSourceSessionId, Int32 etwSessionId, EventCommand command, Boolean enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary`2 commandArguments)
at System.Diagnostics.Tracing.EventSource.OverideEventProvider.OnControllerCommand(ControllerCommand command, IDictionary`2 arguments, Int32 perEventSourceSessionId, Int32 etwSessionId)
at System.Diagnostics.Tracing.EventProvider.EtwEnableCallBack(Guid& sourceId, Int32 controlCode, Byte setLevel, Int64 anyKeyword, Int64 allKeyword, EVENT_FILTER_DESCRIPTOR* filterData, Void* callbackContext)
I can then skip this error and am able to proceed using the app in debug mode but when installed on a device the app will crash.
I have searched for an answer for some time now but the only answer i have come across here is to disable breaking on these kind of exceptions which is of course not a very good answer.
Thanks in advance.
EDIT 1:
Ok, i have a very simple sample project with which this error is easily reproduced. I created a Universal App Blank app in Visual Studio 2013 Ultimate and added the following code to the App.xaml.cs.
The exception posted above is raised on the line with await.
Can anybody help because this is plagueing me for months now.
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
callService();
}
async public Task callService()
{
string url = "http://eu.battle.net/api/d3/profile/bunnynut-2128/";
HttpClient client = new HttpClient();
string data = await client.GetStringAsync(url);
client.Dispose();
}

Having a issue processing multiple files at once in a Windows Service with a FileSystemWatcher

When I try and process more than a couple of files at the same time (they are created and dumped in a folder at the same time), my service dies.
When I wasn't trying to use a thread and had all the processing (where the code in the ProcessFiles method now is) in the Watcher_Created event, at least one file gets through successfully.
When I added the threading (which I'm pretty sure I have to do for this, but am totally unsure of the exact flow and syntax using the threading), I get the following msg in my ProcessFiles method:
System.ArgumentException: Empty path name is not legal.
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
The above msg occurs on the using line:
private static void ProcessFiles()
{
try
{
Thread.Sleep(500);
GetCruiseLineShipName(fullFileName, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
which is obvious, because the "fullFileName" is an empty string. However, it does get set in the Watcher_Created event:
private static void Watcher_Created(object sender, FileSystemEventArgs e)
{
fullFileName = e.FullPath;
}
So, I don't understand why the fullFileName variable is an empty string. I know it must have something to do with the threading I'm trying.
My OnStart event looks like this:
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\DropOff_FTP\MIS");
Watcher.EnableRaisingEvents = true;
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Filter = "*.txt";
Watcher.IncludeSubdirectories = false;
Watcher.InternalBufferSize = 64;
Thread t = new Thread(new ThreadStart(ProcessFiles));
t.Start();
}
Can someone PLEASE inform me how I can use the FileSystemWatcher to process multiple files that are dumped in there at the same time. If I need to use threading, could you please supply how I would use the thread based on the code above?
btw, I'm using the 4.0 framework.
Conceptually something is wrong here. If I understand you correctly, you have two files created in the same folder with short time difference. Then you receive the first event and set the name of ONE file in the global variable fullFileName and you expect that the running thread process this file using the global variable, but in the same time another event Created happens and you change the global variable that the separate thread is processing
I will try to change you code in this way:
the OnStart method loose the code that starts the Thread
the Watcher_Created event will start the thread passing the name of the file that raised the event
.....
Thread t = new Thread(ProcessFiles);
t.Start(e.FullPath);
.....
the ProcessFiles receive the argument with the name of the file to process...
public void ProcessFiles(object argument)
{
string fullFileName = (string)argument;
GetCruiseLineShipName(fullFileName, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(fullFileName, ....))
.....
}

Resources