NewPageAsync(): WebSocketException: The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived' - asp.net-mvc

I'm trying to write a simple HTML to PDF converter with puppeteer-sharp. It is going to be part of MVC.NET project.
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
ExecutablePath = #"C:\Dev\NewPdfLib\chrome-win\chrome.exe",
Args = new string[] { "--disable-gpu" },
Timeout = 0,
UserDataDir = workingFolder
})
var page = await browser.NewPageAsync();
//await page.GoToAsync("http://www.google.com");
//await page.PdfAsync(output);
When I run this code an exception "WebSocketException: The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived'" is thrown at browser.NewPageAsync() line.
The system is Windows 10 and the project is in .NET Framework 4.8

Related

Report Server authentication in .net core 2.1 linux container

I am migrating a .net core 2.1 app from windows server to linux container. It uses SQL Server 2008 report server.
The old app version is running on IIS (windows server), application pool with identity configured (active directory user).
The new app version is running on an alpine container using kestrel .net core server standalone, no identity configured.
When the app tries to reach SQL Server 2008 report server there is an error:
LoadReport error: One or more errors occured. (NTLM authentication is not possible with default credentials on this platform.)
How can I configure credentials (username and password)(same one set in my old application pool) in my new app based on linux container?
Part of my appsettings.json:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/"
},
Part of the source code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"]
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}
protected FileContentResult CarregarRelatorio(
string nomeRelatorio,
string extensao,
Dictionary<string,string> parametros)
{
var renderType = this.ObterTipoRenderizacao(extensao);
if (ReportRenderType.Null.Equals(renderType))
{
throw new BusinessException("Erro ao definir o tipo do arquivo a ser exportado.");
}
ServerReport serverReport = this.PrepararRelatorio();
ReportRequest request = new ReportRequest
{
RenderType = renderType,
Path = this.configuration["Reporting:ReportPath"] + nomeRelatorio,
Name = nomeRelatorio,
ExecuteType = ReportExecuteType.Export,
Parameters = parametros
};
ReportResponse response = serverReport.Execute(request);
if (response.Status != 0)
{
throw new BusinessException(response.Message);
}
return File(response.Data.Stream, response.Data.MimeType, nomeRelatorio + "." + extensao);
}
Microsoft don't provide support for .NET Core/.NET 5, since the SSRS
library is intricately linked with WebForms, which are no longer
supported.
Refer this link
Usually, we use NetworkCredential option to pass username and password while in ASP.NET MVC.
You can able to supply report server's username and password to ReportSettings.Credential as shown in below.
Configuration:
"Reporting": {
"ServerUrl": "http://myserver/ReportServer",
"ReportPath": "/Folder/Reports/",
"UserName": "xxxxxx",
"Password": "yyyyyy"
},
Source Code:
private ServerReport PrepararRelatorio()
{
ReportSettings settings = new ReportSettings
{
ReportServer = this.configuration["Reporting:ServerUrl"],
Credential = NetworkCredential(this.configuration["Reporting:UserName"], this.configuration["Reporting:Password"])
};
ServerReport serverReport = new ServerReport(settings);
return serverReport;
}

"The audience claim value is invalid for current resource" when using ChunkedUploadProvider for Attachment in Microsoft Graph Client API

I am trying to use the following code, but am getting "Message: The audience claim value is invalid for current resource. Audience claim is 'https://graph.microsoft.com', request url is 'https://outlook.office.com/api/beta/Users..."
I get it on the provider.GetUploadChunkRequests(); call below:
AttachmentItem attachmentItem= new AttachmentItem
{
Name = [Name],
AttachmentType = AttachmentType.File,
Size = [Size]
};
var session = graphClient.Users[USEREMAIL].Messages[MESSAGEID].Attachments.CreateUploadSession(attachmentItem).Request().PostAsync().Result;
var stream = new MemoryStream(BYTEARRAY);
var maxSizeChunk = DEFAULT_CHUNK_SIZE;
var provider = new ChunkedUploadProvider(session, graphClient, stream, maxSizeChunk);
var chunkRequests = provider.GetUploadChunkRequests();
(I am using the graphClient to send emails successfully, and have also used it to upload large files using the uploadSession method)
From Andrue Eastman on GitHub:
You are most likely getting the error because of using the ChunkedUploadPorvider instead of using the FileUploadTask to upload the attachment which is setting the Auth header to cause the error you are receiving.
To use the file upload task, follow the following steps
First create an upload session and handing it over to the task as illustrated.
// Create task
var maxSliceSize = 320 * 1024; // 320 KB - Change this to your chunk size. 4MB is the default.
LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxSliceSize);
Create an upload monitor (optional)
// Setup the progress monitoring
IProgress<long> progress = new Progress<long>(progress =>
{
Console.WriteLine($"Uploaded {progress} bytes of {stream.Length} bytes");
});
The service only returns location URI which can be read off from the result object as follows.
UploadResult<FileAttachment> uploadResult = null;
try
{
uploadResult = await largeFileUploadTask.UploadAsync(progress);
if (uploadResult.UploadSucceeded)
{
Console.WriteLine(uploadResult.Location);//the location of the object
}
}
catch (ServiceException e)
{
Console.WriteLine(e.Message);
}

Connecting to Neo4j Aura with .NET Core 2.2 web api

I am trying to connect a to Neo4j Aura instance from a .NET core 2.2 web api. I understand I need the Neo4j .Net Driver v4.0.0-alpha01, but I do not seem to be able to connect. There aren't very many examples out there as this driver is new and so is Aura.
I keep getting:
Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again.
I configure the driver as such
public void ConfigureServices(IServiceCollection services)
{
string uri = "neo4j://1234567.databases.neo4j.io:7687";//not actual subdomain
string username = "neo4j";
string password = "seeeeeeecret";//not actual password
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password)));
}
and in my test controller i run this
private async Task<string> Neo4JTestAsync()
{
string db = "MyDb";
string message = "TESTMESSAGE";
IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(db));
try
{
var greeting = session.WriteTransactionAsync(async tx =>
{
var result = tx.RunAsync("CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
new { message });
var res = await result;
return "return something eventually";
});
return await greeting;
}
catch (Exception e)
{
return e.Message; // throws "Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again"
}
finally
{
await session.CloseAsync();
}
}
I can't get the exact error message you do - but I'm pretty sure this is due to encryption - one of the big differences between the 1.x and 4.x drivers is the default position on Encryption - which is now off by default.
So you'll want to change your initialisation to:
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password), config => config.WithEncryptionLevel(EncryptionLevel.Encrypted)));
That should get you going. Also - make sure you stick with the neo4j:// protocol, as that'll route you properly.
Have you tried bolt:// in the connection string?
string uri = "bolt://1234567.databases.neo4j.io:7687";//not actual subdomain

Missing Configuration File For Tests - Aqueduct

When implementing OAuth with aqueduct I mistakenly didn't follow the test driven development ideology, and I am paying for it now...
When I run my tests, I get the error:
"No configuration file found. See README.md."
Which is thrown from the initializeApplication method in my AppSink class.
As I understand it, tests make use of the config.src.yaml file so I have configured my test harness accordingly:
application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";
Since I was able to run the tests before I implemented the AuthServer etc, I suspect it happened along the way.
My test setUp is as follows:
var app = new Application<OdexSink>();
TestClient client;
setUp(() async {
await app.start(runOnMainIsolate: true);
client = new TestClient(app);
var ctx = ManagedContext.defaultContext;
var builder = new SchemaBuilder.toSchema(ctx.persistentStore, new Schema.fromDataModel(ctx.dataModel), isTemporary: true);
for (var cmd in builder.commands) {
await ctx.persistentStore.execute(cmd);
}
});
And my Test harness start() method is:
Future start() async {
RequestController.letUncaughtExceptionsEscape = true;
application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";
await application.start(runOnMainIsolate: true);
await createDatabaseSchema(ManagedContext.defaultContext, sink.logger);
await addClientRecord();
await addClientRecord(clientID: DefaultClientID, clientSecret: DefaultClientSecret);
client = new TestClient(application)
..clientID = DefaultClientID
..clientSecret = DefaultClientSecret;
}
My config.src.yaml file exits, and contains DB information.
Ah, just one small thing - in your setUp method, you are creating and starting an Application instead of that TestApplication harness. It should look like this
var app = new TestApplication();
setUp(() async {
await app.start();
});
All of the other stuff in setUp is already done in your test harness and you can use the TestClient as app.client:
expect(await app.client.request("/endpoint"), hasStatus(200));

Upload file on Google drive

I am trying to upload an image on google drive using webapi. I copied the following chunk from Google drive doc but I am getting an error.
Here is the code:
var clientSecret = ConfigurationManager.AppSettings["GoogleDriveClientSecret"];
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
scopes, Environment.UserName, CancellationToken.None).Result;
var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential });
var folderId = "0B2bBiMQICgHCMlp6OUxuSHNaZFU";
var fileMetadata = new File()
{
Name = "photo.jpg",
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Now I am getting 2 errors in this code. First "Cannot resolve symbol Upload" at request.Upload() and second "Cannot resolve symbol ResponseBody" at request.ResponseBody
Any help?
You may refer with this related thread. The adding the attribute Inherits="Library.Account.RootVerifyUsers". Based from this reference, Visual Studio can often get confused about things like this. It is recommended to close Visual Studio and reopen it. Also, closing all open instances of VS may be required.

Resources