uselessxp
uselessxp
CC#
Created by uselessxp on 3/22/2024 in #help
Selenium wait for the page to load completely
Even if I followed documentation sample, I'm still getting:
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"css selector","selector":"#username"}
(Session info: chrome=122.0.6261.112); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception'
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"css selector","selector":"#username"}
(Session info: chrome=122.0.6261.112); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception'
Below my code:
private void button2_Click(object sender, EventArgs e)
{
driver.Navigate().GoToUrl("https://mywebsiste.com/login");

// Wait for the page to load completely
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10))
{
PollingInterval = TimeSpan.FromMilliseconds(300),
};
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));

wait.Until(d =>
{
// Login
driver.FindElement(By.Id("username")).SendKeys("myusername");
driver.FindElement(By.Id("password")).SendKeys("mypassword");
driver.FindElement(By.ClassName("remember")).Click();
driver.FindElement(By.Id("loginSubmit")).Click();
return true;
});
}
private void button2_Click(object sender, EventArgs e)
{
driver.Navigate().GoToUrl("https://mywebsiste.com/login");

// Wait for the page to load completely
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10))
{
PollingInterval = TimeSpan.FromMilliseconds(300),
};
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));

wait.Until(d =>
{
// Login
driver.FindElement(By.Id("username")).SendKeys("myusername");
driver.FindElement(By.Id("password")).SendKeys("mypassword");
driver.FindElement(By.ClassName("remember")).Click();
driver.FindElement(By.Id("loginSubmit")).Click();
return true;
});
}
What am I doing wrong?
2 replies
CC#
Created by uselessxp on 7/26/2023 in #help
❔ Xamarin.Forms Android App problem using Application.Context.StartActivity(intent)
Hi, in short, I created a super small Xamarin.Forms Android App. All I need is just to press a button, that will launch another application. Then I immedaitely added the button in the myPage.xaml file in the shared Xamarin.Forms project. About the myPage.xaml.cs file this is the code I binded to the button:
private void OnMyButtonClicked(object sender, EventArgs e)
{
DependencyService.Get<IAppLauncher>().LaunchApp("com.android.chrome", "test");
}
private void OnMyButtonClicked(object sender, EventArgs e)
{
DependencyService.Get<IAppLauncher>().LaunchApp("com.android.chrome", "test");
}
I defined the interface into App.xaml.cs (still shared project) using
public interface IAppLauncher
{
void LaunchApp(string packageName, string data);
}
public interface IAppLauncher
{
void LaunchApp(string packageName, string data);
}
Then I implmented it in the Android project by adding some code into MainActivity.cs
namespace AppExample1.Droid
{
public class AppLauncherImplementation : IAppLauncher
{
public void LaunchApp(string packageName, string data)
{
var uri = Android.Net.Uri.Parse($"appexample2://data/{data}");
var intent = new Intent(Intent.ActionView, uri);
intent.SetPackage(packageName);

var context = Android.App.Application.Context;
context.StartActivity(intent);
}
}
}
namespace AppExample1.Droid
{
public class AppLauncherImplementation : IAppLauncher
{
public void LaunchApp(string packageName, string data)
{
var uri = Android.Net.Uri.Parse($"appexample2://data/{data}");
var intent = new Intent(Intent.ActionView, uri);
intent.SetPackage(packageName);

var context = Android.App.Application.Context;
context.StartActivity(intent);
}
}
}
The problem is that every time I click the button, for some reason that I don't know, I always get error System.NullReferenceException: 'Object reference not set to an instance of an object.'
4 replies
CC#
Created by uselessxp on 4/7/2023 in #help
❔ Implement JWT to my WebAPI .NET 7.0 project - First time
guys I'd like to implement JWT into my WebAPI project, theory seems to be simple but I'm unable to implement it in my .NET 7.0 project, someone could help me or link me a reliable guide? I'm reading different but each of theme have differences in some points
10 replies
CC#
Created by uselessxp on 3/31/2023 in #help
❔ WebAPI Cors problem when calling API from Frontend
Hi, I'm having the following code while trying calling my API from Frontend: Access to XMLHttpRequest at 'http://localhost:5222/api/Users' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. For try to solve this I added a code in the Program.cs with an exception, but I'm still having the same problem and I don't know in which other way could I solve. I show you the code of Program.cs
using MyApp.RestAPI.Models.DataLayer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Load configuration from appsettings.json
var configuration = builder.Configuration;

// Configure services.
builder.Services.AddDbContext<DimmiDevContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
});

// Configure the HTTP request pipeline.
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});

app.MapControllers();

app.Run();
using MyApp.RestAPI.Models.DataLayer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Load configuration from appsettings.json
var configuration = builder.Configuration;

// Configure services.
builder.Services.AddDbContext<DimmiDevContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
});

// Configure the HTTP request pipeline.
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});

app.MapControllers();

app.Run();
I also tried to move the app.UseCors between app.UseRouting() and app.UseAuthorization() with no results
9 replies
CC#
Created by uselessxp on 3/28/2023 in #help
❔ WebAPI .NET 7.0 - Encrypt connectionstring in appsettings.json
guys, I'm writing some WebAPI using .NET 7.0, and I'd like to secure the connectionstring with encryption, I found a guide that suggest to do it by using C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe is it a good way or is something old? currently the connectionstring is placed into appsettings.json (not into web.config) and this is its content:
{
"ConnectionStrings": {
"Default": "Server=127.0.0.1;Database=mydb;User Id=testuser;Password=testpwd;TrustServerCertificate=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
{
"ConnectionStrings": {
"Default": "Server=127.0.0.1;Database=mydb;User Id=testuser;Password=testpwd;TrustServerCertificate=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
4 replies
CC#
Created by uselessxp on 3/24/2023 in #help
❔ C# WebAPI - how to make a field 'optional' ?
I'm creating some WebAPI, I'm starting from a get, for the retrieval of users from a DB. I'm using .NET 7.0 and EntityFramework. The form that make the search request can take in input those fields: Database ID User ID FromDate ToDate Username All fields must be optional, obviously at least 1 should be sent. I wrote some code:
[HttpGet("users")]
public IActionResult GetUsers(
[FromQuery] int? dbId,
[FromQuery] int? userId,
[FromQuery] DateTime? fromDate,
[FromQuery] DateTime? toDate,
[FromQuery] string username)
{
var query = _context.Users.AsQueryable();
if (dbId.HasValue)
{
query = query.Where(d => d.dbId == dbId.Value);
}
if (userId.HasValue)
{
query = query.Where(d => d.userId == userId.Value);
}
if (fromDate.HasValue)
{
query = query.Where(d => d.registrationDate >= fromDate.Value);
}
if (toDate.HasValue)
{
query = query.Where(d => d.registrationDate <= toDate.Value);
}
if (!string.IsNullOrEmpty(username))
{
query = query.Where(d => d.username == username);
}
var users = query.ToList();
return Ok(users);
}
[HttpGet("users")]
public IActionResult GetUsers(
[FromQuery] int? dbId,
[FromQuery] int? userId,
[FromQuery] DateTime? fromDate,
[FromQuery] DateTime? toDate,
[FromQuery] string username)
{
var query = _context.Users.AsQueryable();
if (dbId.HasValue)
{
query = query.Where(d => d.dbId == dbId.Value);
}
if (userId.HasValue)
{
query = query.Where(d => d.userId == userId.Value);
}
if (fromDate.HasValue)
{
query = query.Where(d => d.registrationDate >= fromDate.Value);
}
if (toDate.HasValue)
{
query = query.Where(d => d.registrationDate <= toDate.Value);
}
if (!string.IsNullOrEmpty(username))
{
query = query.Where(d => d.username == username);
}
var users = query.ToList();
return Ok(users);
}
As I understood, in that way EF understand how should it works, and the statement should works without bugs. I think I'll only have to add a check at the beginning, for make sure that at least 1 field is sent. Anyway when I test the API and I put only 1 field, for example dbId I get Error 400 as response, The username field is required I suppose that's why I never declared anywhere when the parameter is optional, and when not, since I just defined the code that have to be executed after a correct request is sent. Browsing on the web I found some guides that suggest to add [Required] tag on mandatory fields, inside the model.cs making the rest being optional, but this seems not working. Other guides suggest to set all parameters to null by default, or at least setting the FrontEnd to work in this way.
4 replies
CC#
Created by uselessxp on 2/26/2023 in #help
❔ ✅ send notification on an iPhone
guys is there on C# to send somehow a notification on an iPhone? I found pushbullet but it's not available on iOS :/ an alternative could be to make something with Telegram. what do you think? is there an easier way?
24 replies
CC#
Created by uselessxp on 2/21/2023 in #help
❔ embed and unity app/game and interact with it
guys someone know how could I implement an unity app in a C# app? I mean, I'd like to login to an unity app/game and be able to interact with it through C# for create stats, calculations, and make some automations. in this specific case, there's also a browser version, maybe it could simplify, but I don't have idea on how to make C# able to recognize objects, starting from read values. maybe a bit of reverse engineering will be needed. any hints?
15 replies
CC#
Created by uselessxp on 2/16/2023 in #help
❔ best way to store and handle Settings/Config of an app
I realized a little tool and I'd like to create a Settings/Configuration system for store some info, example I have several
string serverAddress = "127.0.0.1";
string sshUser = "admin2";
string sshPassword = "password123";
bool isSFTP = true;
...
...
...
string serverAddress = "127.0.0.1";
string sshUser = "admin2";
string sshPassword = "password123";
bool isSFTP = true;
...
...
...
and I'd like to put them in a .ini or whatever file, so I can edit them without having to edit the source code I found few packages I think could works for the purpose: Serilog.Settings.Configuration 215.4M downloads Microsoft.Extensions.Configuration.Ini 47.6M downloads I don't know if they are good and if there exist better stuffs
204 replies
CC#
Created by uselessxp on 2/15/2023 in #help
❔ recommended FTP library/nuget?
Well, I need to to a task via FTP: - if exist delete a folder with its content - upload a folder with its files I'm trying to to that using FtpWebRequest Class but it seems that's a bit limited, I'm still reading MSDocs and it seems that I can't delete a folder recursively, so I get the error "folder is not empty" when trying to delete
143 replies
CC#
Created by uselessxp on 1/31/2023 in #help
❔ Dapper - Call stored procedure error
I finished to write my first POST Api, but I get an error when I execute it and it call a stored procedure. -$exception {"OUT or INOUT argument 1 for routine mydb.storedprocedure is not a variable or NEW pseudo-variable in BEFORE trigger"} MySqlConnector.MySqlException ErrorCode StoredProcedureNotVariableArgument MySqlConnector.MySqlErrorCode I checked all parameters, count and names, and they are ok, what am I forgetting?
4 replies
CC#
Created by uselessxp on 1/31/2023 in #help
✅ RestAPI getting an error while testing (TimeSpan related)
I thought to have solved this, but it's not. As title, I'm testing some written RestAPI (still in development) for a service. The project is in .NET 7.0 There are few fields to type plus a field that will put in a DB hours and minutes, example 10:00 Well, in the model definition I have this:
public TimeSpan TestHour { get; set; }
public TimeSpan TestHour { get; set; }
Well, when I launch the debug, and it open Swaggler, I type all fields, and finally I have to write this TestHour. I tried with: - 10:00 - 10:00:00 - 360000000000 - 360000000000, 0, 0 None of those worked, and I get the following error from Swaggler: The JSON value could not be converted to System.TimeSpan Someone knows what could be? Am I doing something wrong, or maybe something doesn't works with this .NET ver?
49 replies
CC#
Created by uselessxp on 1/24/2023 in #help
❔ best way to include and works with images
I'm working on a project, and I'll have to work with several images. Actually the project is working with:
string ImageFile1 = @"C:\Users\xxxxx\Desktop\image1.png";
string ImageFile2 = @"C:\Users\xxxxx\Desktop\image2.png";
string ImageFile3 = @"C:\Users\xxxxx\Desktop\image3.png";
string ImageFile4 = @"C:\Users\xxxxx\Desktop\image4.png";
...
string ImageFile1 = @"C:\Users\xxxxx\Desktop\image1.png";
string ImageFile2 = @"C:\Users\xxxxx\Desktop\image2.png";
string ImageFile3 = @"C:\Users\xxxxx\Desktop\image3.png";
string ImageFile4 = @"C:\Users\xxxxx\Desktop\image4.png";
...
Is there a way to improve this? I'm not referring to the fact I'm using path of my PC, but I'd like to make it more elegant. Regarding the path I could put images on a project subfolder, adding them as resources, changing the extension with a random one, so final users will not know they are simple .png But are there other solutions? I read about the ability to convert an image to a string, using bitmaptostring. What do you think about?
2 replies
CC#
Created by uselessxp on 1/23/2023 in #help
✅ WPF - Detect if screen resolution is resized (ex. 125% or more)
I'm writing a tool in which I need to first set the screen resolution, I currently have a 1920 x 1080, but I noticed that if in Windows screen resolution I enable the automatic resizing to 125% (or more) the tool retrieve false values. Ex. for 125% the software think that my resolution is: 1536 x 864. Is there an easy way to detect if is this enabled, and maybe also detect the % value? I'd like to make something like that.
private void Button_Click(object sender, RoutedEventArgs e)
{
bool isResizing = true;
if (isResizing)
{
MessageBox.Show((SystemParameters.PrimaryScreenWidth * 1.25).ToString());
MessageBox.Show((SystemParameters.PrimaryScreenHeight * 1.25).ToString());
}
else
{
MessageBox.Show((SystemParameters.PrimaryScreenWidth).ToString());
MessageBox.Show((SystemParameters.PrimaryScreenHeight).ToString());
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
bool isResizing = true;
if (isResizing)
{
MessageBox.Show((SystemParameters.PrimaryScreenWidth * 1.25).ToString());
MessageBox.Show((SystemParameters.PrimaryScreenHeight * 1.25).ToString());
}
else
{
MessageBox.Show((SystemParameters.PrimaryScreenWidth).ToString());
MessageBox.Show((SystemParameters.PrimaryScreenHeight).ToString());
}
}
Or better:
int resizingPercent = 25;
int resizingPercent = 25;
If it's possible it will be nice, if it's not possible or too hard to make I'll go to ask to the user those data.
5 replies
CC#
Created by uselessxp on 1/22/2023 in #help
✅ detect image/part of image or pixel/pixel area and click on it
5 replies
CC#
Created by uselessxp on 1/20/2023 in #help
✅ ConsoleApp - run the .exe by cmd and catch given parameters
Well, as a little task I'm trying to code a ConsoleApp that should base64 encrypt an input string and automatically copy it to the clipboard. The ideal result is the following, by cmd: - -base64.exe -e string (for encrypt) - -base64.exe -d string (for decrypt) First of all I played with encoding/decoding and I figured out that I have to convert the input string into a byte (array?), then after I can apply the method that convert to base64. I succesfully "wrote" the encrypt method, now something I don't know how to do, it to catch one or more parameter, I don't know how is technically called this, I'd have googled it. But what I finally understood, is the meaning of:
static void Main(string[] args)
static void Main(string[] args)
I always wondered which is the sense to write string[] args if the program works perfectly without arguments, and now I know that the meaning of this is somehow to accept and handle cmd.exe parameters as arguments.
48 replies
CC#
Created by uselessxp on 1/19/2023 in #help
✅ Clipboard.SetText in a ConsoleApp
34 replies
CC#
Created by uselessxp on 1/17/2023 in #help
✅ mistery -foreach cycle executed three times for no apparently reason
69 replies
CC#
Created by uselessxp on 1/17/2023 in #help
❔ ✅ is it possible to ''lock'' a var after the first assignment?
I'm making some base practice with C# with some exercises. I completed the first one, and it have a second part that ask an additional answer. Here's the code:
/*
Part 1

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.
*/


/*
Part 2

Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on.
*/

using System.Text;

namespace AOC_2015_1
{
internal class DayOnePartTwo
{
static void Main(string[] args)
{
string? input;
Console.WriteLine("Where should I delivery the next gift?");
Console.SetIn(new StreamReader(Console.OpenStandardInput(), Encoding.UTF8, false, 8192));
input = Console.ReadLine();
Console.WriteLine($"Final floor is {GiftDelivery(input)}");
}

static short GiftDelivery(string input)
{
short floor = 0;
const char floorUpChar = '(';
const char floorDownChar = ')';
int i = 0;
int x = 0;

foreach (char c in input)
{
if (floor == -1)
{
x = i;
Console.WriteLine("is " + x);
}
if (c == floorUpChar)
{
floor++;
i++;
}
else if (c == floorDownChar)
{
floor--;
i++;
}
}
return floor;
}
}
}
/*
Part 1

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.
*/


/*
Part 2

Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on.
*/

using System.Text;

namespace AOC_2015_1
{
internal class DayOnePartTwo
{
static void Main(string[] args)
{
string? input;
Console.WriteLine("Where should I delivery the next gift?");
Console.SetIn(new StreamReader(Console.OpenStandardInput(), Encoding.UTF8, false, 8192));
input = Console.ReadLine();
Console.WriteLine($"Final floor is {GiftDelivery(input)}");
}

static short GiftDelivery(string input)
{
short floor = 0;
const char floorUpChar = '(';
const char floorDownChar = ')';
int i = 0;
int x = 0;

foreach (char c in input)
{
if (floor == -1)
{
x = i;
Console.WriteLine("is " + x);
}
if (c == floorUpChar)
{
floor++;
i++;
}
else if (c == floorDownChar)
{
floor--;
i++;
}
}
return floor;
}
}
}
98 replies
CC#
Created by uselessxp on 1/16/2023 in #help
❔ which is the key for write a good code? my 1st exercise of advent of calendar
Problem: https://adventofcode.com/2015/day/1 My code:
namespace AOC_2015_1
{
internal class Program
{
static short floor = 0;
static string? input;

static void Main(string[] args)
{
Console.WriteLine("Where should I delivery the next gift?");
input = Console.ReadLine();
gift_delivery(input);
}

static void gift_delivery(string input)
{
char floorUp = '(';
char floorDown = ')';

foreach (char c in input)
{
if (c == floorUp)
{
floor++;
}
else if (c == floorDown) {
floor--;
}
}
Console.WriteLine($"Final floor is {floor}");
}
}
}
namespace AOC_2015_1
{
internal class Program
{
static short floor = 0;
static string? input;

static void Main(string[] args)
{
Console.WriteLine("Where should I delivery the next gift?");
input = Console.ReadLine();
gift_delivery(input);
}

static void gift_delivery(string input)
{
char floorUp = '(';
char floorDown = ')';

foreach (char c in input)
{
if (c == floorUp)
{
floor++;
}
else if (c == floorDown) {
floor--;
}
}
Console.WriteLine($"Final floor is {floor}");
}
}
}
Do you think I wrote a good code? I could reduce code row number by deleting some var declarations like floorUp and floorDown but maybe it's not the right way.
10 replies