Puppeteer sharp in Blazor page Failed to create connection - blazor-server-side

I created a project in blazor using Visual Studio 2022 and dot net 6.0.
He added the PuppeteerSharp package and created a small test function:
try
{
using (var myBr = new BrowserFetcher())
{
await myBr.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var launchOptions = new LaunchOptions { Headless = true };
_browserPuppeter = await Puppeteer.LaunchAsync(launchOptions);
_pagePuppeteer = await _browserPuppeter.NewPageAsync();
await _pagePuppeteer.GoToAsync(url);
}
}
catch (Exception exc)
{
errore = exc.Message + DateTime.Now.ToString(" HH:MM:ss.zzz");
}
When I run it from visual studio locally it loads the page correctly. When I publish on a website in Web Hosting (https://www.webwiz.net) two things happen:
fails to download chromium.
If I upload the directory .local-chromium via ftp, it gives me the error:
"Failed to create connection"
Any idea?

Related

How to access a file server share from an ASP.NET Core web API application published in IIS within the same domain?

I need access to files that are in a files server in my LAN from my Angular app.
I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN
Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I donĀ“t know how to do it.
When I try this
[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
string[] files = Directory.GetFiles(#"\\192.168.100.7\ofertashistorico");
return files;
}
I get this error
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'
It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.
I also do not know how to manage the issue of the credentials necessary to access said resource
Any idea, please?
Thanks
I am using below code and it works for me. Please check it.
Steps:
Navigate to the path like : \\192.168.2.50\ftp
Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.
You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.
Test Result
Sample code
[HttpGet("directorio")]
public IActionResult GetDirectoryContents()
{
string networkPath = #"ftp:\\192.168.2.50";
string userName = #"Administrator";
string password = "Yy16";
#region FtpWebRequest
var networkCredential = new NetworkCredential(userName, password);
var uri = new Uri(networkPath);
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = networkCredential;
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
}
#endregion
return Ok();
}

ASP Core .NET 6 works when I run it manually, but it fails when I install as windows service

I have an ASP Core .NET 6 application that I want to install as windows services.
I am using minimal API and this is the code:
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices;
using System.IO.Compression;
using System.Security.Cryptography.X509Certificates;
using GestorOrdenadores.Service.Server.Grpc;
using Serilog;
using Microsoft.Extensions.Configuration;
using Serilog.Events;
File.AppendAllText("LogManual.txt", DateTime.Now + ": Iniciado");
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
Log.Information("Starting up");
try
{
WebApplicationOptions options = new WebApplicationOptions
{
Args = args,
ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};
WebApplicationBuilder builder = WebApplication.CreateBuilder(options);
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.ReadFrom.Configuration(ctx.Configuration));
builder.WebHost.ConfigureKestrel((context, options) =>
{
string miStrCertificado = File.ReadAllText("certificados/server.crt");
string miStrKey = File.ReadAllText("certificados/server.key");
X509Certificate2 miCertficadoX509 = X509Certificate2.CreateFromPem(miStrCertificado, miStrKey);
X509Certificate2 miCertificado2 = new X509Certificate2(miCertficadoX509.Export(X509ContentType.Pkcs12));
miCertficadoX509.Dispose();
options.ListenAnyIP(5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps(miCertificado2);
});
});
builder.Services.AddGrpc();
builder.Host.UseWindowsService();
WebApplication app = builder.Build();
app.UseSerilogRequestLogging();
app.MapGrpcService<GestorOrdenadoresService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
await app.RunAsync();
}
catch(Exception ex)
{
File.AppendAllText("LogManual.txt", DateTime.Now + ": EXCEPTION: " + ex.Message);
Log.Fatal(ex, "Unhandled exception");
}
finally
{
File.AppendAllText("LogManual.txt", DateTime.Now + ": Finally");
Log.Information("Shut down complete");
Log.CloseAndFlush();
}
When I debug or run the application manually, it creates the log, but when I install the service and try to run it, in the service manager of windows, when I click to start, I get the error 1067.
If I go to the event viewer of windows, I get the error with ID 7034.
And in this case no log files are created.
How the application can run when I run it manually, I guess the problem is how I try to set the service part of the code, but I don't know how could be the problem.
Win32 services run in %WinDir%\System32 by default (as I describe on my blog), and I'd be surprised if you could just write out a LogManual.txt in that folder. So, you're probably getting an exception, which is causing your service to fail to start.
A lot of services find this inconvenient, and change their working directory on startup:
Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Get AD Users Visual Studio Web App versus Console

I have the following code below.
When I run Debug in Visual Studio with this code in an ASP.NET Core App (so running as IIS Express) this works
When I run Debug in Visual Studio with this code in a ASP.NET hosted process in a Windows Service this return nothing, but also no error messages
I connect from my home laptop via RDP to another laptop where VPN is running, so I think that is probably it. I tried running visual studio as admin, running the compiled exe as admin, /runas with the domain specified, etc but the commandline app will show nothing while the asp.net core app shows the list. So it must be the user it runs under.
But when i run WindowsIdentity.GetCurrent().Name in both cases it gives the same domain and name (me). In task manager the devenv and iis process is me.
public List<AdSecurityGroupDTO> GetAllDomainSecurityGroups(string domain)
{
List<AdSecurityGroupDTO> result = new List<AdSecurityGroupDTO>();
using (var ctx = new PrincipalContext(ContextType.Domain, domain))
{
GroupPrincipal findAllGroups = new GroupPrincipal(ctx, " * ");
PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
foreach (Principal group in ps.FindAll())
{
AdSecurityGroupDTO adSecurityGroupDTO = new();
adSecurityGroupDTO.Name = group.Name;
adSecurityGroupDTO.Description = group.Description;
adSecurityGroupDTO.DisplayName = group.DisplayName;
adSecurityGroupDTO.DistinguishedName = group.DistinguishedName;
adSecurityGroupDTO.SamAccountName = group.SamAccountName;
result.Add(adSecurityGroupDTO);
}
return result;
}
}

WebSockets not working when application is built

I have got to ASP.NET-Core 2.0 apps communicating via WebSockets.
App A is Server.
Application A is running on a remote server with Ubuntu.
App B is Client
Application B is running on a PC setup in my office.
When I test my applications locally in Debug everything works fine. Client connects to the server and they can exchange information.
However, when I build my Server app, Client can connect to it but when server tries to send a message to the client the message is not received by the client.
public async Task<RecievedResult> RecieveAsync(CancellationToken cancellationToken)
{
RecievedResult endResult;
var buffer = new byte[Connection.ReceiveChunkSize];
WebSocketReceiveResult result;
MemoryStream memoryStream = new MemoryStream();
do
{
if (cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException();
}
Console.WriteLine("Server Invoke");
// result never finishes when application is build. On debug it finishes and method returns the correct result
result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
if (result.MessageType == WebSocketMessageType.Close)
{
await CloseAsync(cancellationToken);
endResult = new RecievedResult(null, true);
return endResult;
}
memoryStream.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);
endResult = new RecievedResult(memoryStream, false);
return endResult;
}
This is the part of code where everything hangs.
What I tried was:
Build Server - Build Client => not working
Build Server - Debug Client => not working
Debug Server - Debug Client => working
I need any advice what might be wrong here and where I should look for issues.
Console if free of errors. Everything hangs on:
result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);

Call Azure API from WebJob/ Shared code between WebJob and web api

I have a web api in an ASE and an associated web job. I am trying to call this web api from the web job but it always fails with winhttpexception: a security error has occurred. I have put in all the tls related settings but still getting the error.
Any suggestions on the error?
Also is there a way to share code between WebJob and web api?
I was able to resolve the issue by setting the below in my code.This resolved the Security Error.
using(var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender,certificate,chain,sslPolicyErrors) => true
})
You could create a console app and publish it as Azure WebJobs. For username and password you could click Get Publish Profile in your Azure webapp overview to get them.
Then you could use the following code in Console App to call your Azure Webapi.
string userName = "$xxxxxx";
string userPassword = "xxxxxxxxxxxxx";
string webAppName = "xxxxxx";
var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{userName}:{userPassword}"));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64Auth);
var baseUrl = new Uri($"https://{webAppName}.azurewebsites.net/api/values");
var result = client.GetAsync(baseUrl).Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
var value = readTask.Result;
Console.WriteLine(value.ToString());
}
}
Console.WriteLine("run successfully");
Output as below: