|
Been some years now since I worked with .Net Core 3, been busy with PHP 8, and was surprised at the new stuff in .Net Core 6, and it's insatiable appetite to point out null conditions, so I'm playing along with it for now. But I just can't wrap my head around this one, and I'm starring at it like a deer in the headlights. So I asked VS 2022 for suggestions, and it suggested converting my old code to these new statements. I read the documentation .. Resolve nullable warnings | Microsoft Learn and I didn't see any anything that sort of matched what I'm doing here. I tried ...
Right hand side ?? "_database maybe null" but it said that it can't be applied to operands of type IMongoCollection<account> and strings.
Perhaps someone else has run into this and can give me a pointer or a solid. But I'll keep researching this to see if I can find something.
My old code example from .Net Core 3
<br />
public IMongoCollection<ACCOUNTS> Accounts
{
get { return _database.GetCollection<ACCOUNTS>("Accounts"); }
}<br />
My new code that VS 2022 Suggested
internal class MongoDbContext : IDisposable
{
private IMongoDatabase? _database;
<pre>
public void MongoDBContext()
{
var rootObject = AppSettingsJson.GetSettings();
var dbConnection = rootObject?.Settings?.DbConnection;
var connString = "mongodb://" + dbConnection?.User + ":" + dbConnection?.Pass + "@" + dbConnection?.Host;
var client = new MongoClient(connString);
_database = client.GetDatabase(dbConnection?.Database);
}
public IMongoCollection<ACCOUNTS> Accounts => _database.GetCollection<ACCOUNTS>("Accounts");
public IMongoCollection<SHIPPERS> Shippers => _database.GetCollection<SHIPPERS>("Shippers");
public IMongoCollection<CONTACTS> Contacts => _database.GetCollection<CONTACTS>("Contacts");
public IMongoCollection<PALLETS> Pallets => _database.GetCollection<PALLETS>("Pallets");
public IMongoCollection<CUSTOMERS> Customers => _database.GetCollection<CUSTOMERS>("Customers");
public IMongoCollection<BILLOFLADING> BillOfLading => _database.GetCollection<BILLOFLADING>("BillOfLading");
public IMongoCollection<SHIPPINGADDRESSES> ShippingAddresses => _database.GetCollection<SHIPPINGADDRESSES>("ShippingAddresses");
public IMongoCollection<countries> Countries => _database.GetCollection<countries>("Countries");
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
On the internet, I was looking at another persons code, and noticed he used _database as a property, then I combined that with the help on Resolve nullable warnings | Microsoft Learn, to satisfy cSharp, or the compiler or both. Not sure if it runs yet, haven't gotten that far. But changing the type offered documented solutions for this. It's gonna be a hard week learning this new stuff.
namespace SimpleBol.Context.MongoDb
{
internal class MongoDbContext : IDisposable
{
private IMongoDatabase _database { get; set; } = null!;
private MongoClient _client { get; set; } = null!;
public void MongoDBContext()
{
var rootObject = AppSettingsJson.GetSettings();
var dbConnection = rootObject?.Settings?.DbConnection;
var connString = "mongodb://" + dbConnection?.User + ":" + dbConnection?.Pass + "@" + dbConnection?.Host;
_client = new MongoClient(connString);
_database = _client.GetDatabase(dbConnection?.Database);
}
public IMongoCollection<ACCOUNTS> Accounts => _database.GetCollection<ACCOUNTS>("Accounts");
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Why use private properties and not fields?
Graeme
"I fear not the man who has practiced ten thousand kicks one time, but I fear the man that has practiced one kick ten thousand times!" - Bruce Lee
|
|
|
|
|
I'm willing to learn, what would you have done with fields?
I used the private property because that's what MongoDB sort of suggested in some new sample code to get started.
In 2020, I was just getting started with .Net Core 3 and cSharp, when I picked up a PHP 8 project, and haven't written a line of cSharp in almost 3 years now, so I'm having to sort of start all over again with this project.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
in vb.net windows form:
how can i WebBrowser1.Navigate url with query string in arabic to asp.net
thank's
|
|
|
|
|
Use the System.Net.WebUtility.UrlEncode[^] method.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I searched around the internet, but wasn't able to find much, and I lack the knowledge of using the correct terms to search with.
I'm trying to group a bunch of invoices together by store code, and I want to bring the invoice items over as well. The invoice items are just a List(Of AtdMiniInvoiceItems) , which matches the .FITEMS in the group, so I really don't need to use the With to itemize what I want.
I'm looking for the correct way to do this without writing a ton of code, and a point in the right direction. I can see that perhaps using With and doing this again would be the correct solution, but was looking to just combine it all as is.
Dim gFreightInvoicesGrouped As List(Of AtdFreightInvoiceReport) = gFreightInvoicesAll _
.OrderBy(Function(ob) ob.FSTORECODE) _
.Where(Function(a) a.FSTORECODE = String.Empty Or a.FSTORECODE.ToLower() = "unknown") _
.GroupBy(Function(inv) inv.FSTORECODE).Select(Function(cl) New AtdFreightInvoiceReport() With {
.FINVNO = cl.First().FINVNO,
.FSTORECODE = cl.First().FSTORECODE,
.FLOCATION = cl.First().FLOCATION,
.FAMOUNT = cl.Sum(Function(x) x.FAMOUNT),
.FSHIPCOST = cl.Sum(Function(x) x.FSHIPCOST),
.FSHIPPRICE = cl.Sum(Function(x) x.FSHIPPRICE),
.FMARGINPERCENT = cl.Sum(Function(x) x.FMARGINPERCENT),
.FREDFLAG = False,
.FITEMS = cl.GroupBy(Function(shipItems) shipItems.FITEMS).ToList()
}).ToList()
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Interesting, I didn't know we can run functions inside a Linq GroupBy. Hmm ... This opens up some new possibilities for me.
I'll attack the invoice items again, report almost done now
Dim gFreightInvoicesGrouped As List(Of AtdFreightInvoiceReport) = gFreightInvoicesAll _
.OrderBy(Function(ob) ob.FSTORECODE) _
.Where(Function(a) a.FSTORECODE <> String.Empty Or a.FSTORECODE.ToLower() <> "unknown") _
.GroupBy(Function(inv) inv.FSTORECODE).Select(Function(cl) New AtdFreightInvoiceReport() With {
.FINVNO = cl.First().FINVNO,
.FSTORECODE = cl.First().FSTORECODE,
.FLOCATION = cl.First().FLOCATION,
.FAMOUNT = cl.Sum(Function(x) x.FAMOUNT),
.FSHIPCOST = cl.Sum(Function(x) x.FSHIPCOST),
.FSHIPPRICE = cl.Sum(Function(x) x.FSHIPPRICE),
.FMARGINPERCENT = AmCommon.CalculateShippingPercentageFormattedToString(cl.Sum(Function(x) x.FSHIPCOST), cl.Sum(Function(x) x.FAMOUNT)),
.FREDFLAG = False
}).ToList()
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Im trying to trick my startup to add AddIISUrlRewrite by different domains, I not sure it's possible, any ideas?
I'm Not really sucessfull.
<pre>
var options = new RewriteOptions();
bool blnsiteA = false;
var tempoptions = new RewriteOptions();
tempoptions.Add(rewriteContext =>
{
var request = rewriteContext.HttpContext.Request;
if (request.Host.Host == "siteA.com")
{
blnsiteA = true;
}
});
if (blnsiteA)
{
options.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteA.xml");
}
else
{
options.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteB.xml");
}
options.AddRedirectToNonWww();
app.UseRewriter(options);
app.UseStaticFiles();
|
|
|
|
|
That won't work; the startup code runs when the application first starts, whereas the redirection code executes for each request. Your code will only ever apply the redirections for site B.
Instead, you'll need to add conditions to your rewrite rules base on the {HTTP_HOST} - for example:
<rule name="Redirect site A">
<match url="^(.+)" />
<conditions>
<add input="{HTTP_HOST}" type="Pattern" pattern="^([^.]+)\.siteA\.com$" />
</conditions>
<action type="Rewrite" url="{C:1}/{R:1}" />
</rule> URL Rewrite Module Configuration Reference | Microsoft Learn[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The other option would be to use your own middleware. You can see the source of the RewriteMiddleware class on GitHub:
aspnetcore/RewriteMiddleware.cs at b1dcacabec1aeacef72c9aa2909f1cb49993fa73 · strykerin/aspnetcore · GitHub[^]
And the source of the UseRewriter method:
aspnetcore/RewriteBuilderExtensions.cs at b1dcacabec1aeacef72c9aa2909f1cb49993fa73 · strykerin/aspnetcore · GitHub[^]
It shouldn't be too hard to build your own - something like this (untested):
public static class RewriteBuilderExtensions
{
public static IApplicationBuilder UseMultiRewriter(
this IApplicationBuilder app,
IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)> optionsMap)
{
ArgumentNullException.ThrowIfNull(app);
ArgumentNullException.ThrowIfNull(optionsMap);
return app.UseMiddleware<MultiRewriteMiddleware>(Options.Create(optionsMap));
}
}
public static partial class MultiRewriteMiddlewareLoggingExtensions
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "Request did not match any rewrite rule set. Current url is {CurrentUrl}")]
public static partial void MultiRewriteMiddlewareNoMatchingRules(this ILogger logger, string CurrentUrl);
[LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = "Request is continuing in applying rules. Current url is {CurrentUrl}")]
public static partial void MultiRewriteMiddlewareRequestContinueResults(this ILogger logger, string CurrentUrl);
[LoggerMessage(EventId = 2, Level = LogLevel.Debug, Message = "Request is done processing. Location header '{Location}' with status code '{StatusCode}'.")]
public static partial void MultiRewriteMiddlewareRequestResponseComplete(this ILogger logger, string Location, int StatusCode);
[LoggerMessage(EventId = 3, Level = LogLevel.Debug, Message = "Request is done applying rules. Url was rewritten to {RewrittenUrl}")]
public static partial void MultiRewriteMiddlewareRequestStopRules(this ILogger logger, string RewrittenUrl);
}
public class MultiRewriteMiddleware
{
private readonly RequestDelegate _next;
private readonly IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)> _optionsMap;
private readonly IFileProvider _fileProvider;
private readonly ILogger _logger;
public MultiRewriteMiddleware(
RequestDelegate next,
IWebHostEnvironment hostingEnvironment,
ILoggerFactory loggerFactory,
IOptions<IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)>> optionsMap)
{
ArgumentNullException.ThrowIfNull(next);
ArgumentNullException.ThrowIfNull(optionsMap);
_next = next;
_optionsMap = optionsMap.Value;
_fileProvider = _options.StaticFileProvider ?? hostingEnvironment.WebRootFileProvider;
_logger = loggerFactory.CreateLogger<MultiRewriteMiddleware>();
}
public Task Invoke(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var options = _optionsMap.Where(m => m.predicate(context)).Select(m => m.options).FirstOrDefault();
if (options is null)
{
_logger.MultiRewriteMiddlewareNoMatchingRules(context.Request.GetEncodedUrl());
return _next(context);
}
RewriteContext rewriteContext = new()
{
HttpContext = context,
StaticFileProvider = _fileProvider,
Logger = _logger,
Result = RuleResult.ContinueRules
};
foreach (var rule in options.Rules)
{
rule.ApplyRule(rewriteContext);
switch (rewriteContext.Result)
{
case RuleResult.ContinueRules:
{
_logger.MultiRewriteMiddlewareRequestContinueResults(context.Request.GetEncodedUrl());
break;
}
case RuleResult.EndResponse:
{
_logger.MultiRewriteMiddlewareRequestResponseComplete(
context.Response.Headers[HeaderNames.Location],
context.Response.StatusCode);
return Task.CompletedTask;
}
case RuleResult.SkipRemainingRules:
{
_logger.MultiRewriteMiddlewareRequestStopRules(context.Request.GetEncodedUrl());
return _next(context);
}
default:
{
throw new ArgumentOutOfRangeException($"Invalid rule termination {rewriteContext.Result}");
}
}
}
return _next(context);
}
}
RewriteOptions optionsA = new();
optionsA.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteA.xml");
optionsA.AddRedirectToNonWww();
RewriteOptions optionsB = new();
optionsB.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteB.xml");
optionsB.AddRedirectToNonWww();
List<(Func<HttpContext, bool> predicate, RewriteOptions options)> optionsMap = new()
{
(context => context.Request.Host.Host == "siteA.com", optionsA),
(context => true, optionsB)
};
app.UseMultiRewriter(optionsMap);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have a weird, or probably a simple dumb user error on a simple web application.
The project is created with the wizard. (asp.net core web app with a new controller with EF).
The database has been created and is working.
I have a model (1 string, 2 double values):
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public double Poids { get; set; }
public double Glycemie { get; set; }
}
In the generated Create Page.
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Poids" class="control-label"></label>
<input asp-for="Poids" class="form-control" />
<span asp-validation-for="Poids" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Glycemie" class="control-label"></label>
<input asp-for="Glycemie" class="form-control" />
<span asp-validation-for="Glycemie" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Addition :
in the Create method, the value for the Glycemie is zero, as if it was not entered in the form.
As if the binding did not work ???
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Poids,Glycemie")] Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(person);
}
When I type in the data, name "Max" , poids (weight) "123" and glycemia 4.5 value, I get an error on the glycemia value saying the value is not valid.
See image :
When i just type 4 (instead of 4.5) it works.
I'm not sure where or what validation is done.
Anything stupid or obvious I missed ?
THanks.
CI/CD = Continuous Impediment/Continuous Despair
modified 23-Mar-23 7:42am.
|
|
|
|
|
I suspect the generated HTML will have an <input type="number"> for both number fields.
Unless otherwise specified, the default step for both fields will be 1 , meaning that you can only enter integers:
HTML attribute: step - HTML: HyperText Markup Language | MDN[^]
Try specifying the step for both fields:
<input asp-for="Glycemie" class="form-control" step="0.01" />
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks, I'll look into that.
CI/CD = Continuous Impediment/Continuous Despair
|
|
|
|
|
Message Removed
modified 26-Mar-23 15:27pm.
|
|
|
|
|
Need to Integrate Swipe Machine in my C# Application for billing
|
|
|
|
|
Well, go ahead; you have our permission to do that.
Feel free to come back if you have an actual question to ask. But bear in mind that the only people who can support your "swipe machine" are the people who supplied it.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Credit card?
And you said C# but this is ASP.NET.
In C#
- You define, in general, how this processing will plugin to your application. You need to learn in general how credit cards work. That will include transactions and batching. You probably also need to look at debit cards.
- You must first have a processor (service that processes credit card transactions.) However in practice you probably need two for a real business since one is a backup. A processor is going to end up needing a bank account to which the company has access. That can limit choices (both bank and processor.)
- You get their specs which includes process for verifying your service.
- You implement to the specs.
- You integrate that code into your application.
- You must figure out a viable way to test the code. Basically you need some credit cards (plural) which can be used as actual cards. Usually with a $0.01 transaction. Obviously whoever has these must be trusted but also there are hard and very low limits on the cards.
- You certify with the processor.
Besides the above it is very important that you understand how error handling works. Both errors that the processor specs might document and those that they do not.
There are services out there besides processors which act as a gateway (and usually called that) which, by their claims, make much of the above easier. Sometimes that is true and sometime perhaps not. But with those you are limited to which processors that they support.
|
|
|
|
|
Silly me - I meant WebForms, of course, not WinForms...
My (admittedly limited) understanding of this class, is that it allows you to override the default HTML rendering code for an ASP.NET web control. It shouldn't, AFAIU, affect any of the properties ro events otherwise asociated with the control - only the HTML markup .NET uses to render it on teh page.
OK - so I've tried this for a the radio button adn checkbox controls. It all seems to work, and the controls render with the markup I want. If I set the AutoPostBack property, the HTML includes the usual
onclick="javascript:setTimeout('__doPostBack('[ctrl ID here]','')', 0)" that we all know and love in such controls... and indeed, the controls will post the page back when clicked/changed, and the "correct" changed state of is shown on the posted back page.
BUT... the control's CheckedChanged server-side event is not being fired. Am I operating unders ome basic misunderstanding of this class?
|
|
|
|
|
I have the following code that is sist make the firs leter of a token uppercase, do not know if this is the correct way to do it.
I only run thos on my local machine
The value of slug is the token name on coinmarketcup
At the moment when I open the page it show me the name of the token that I have click on, but they are all lowercase, so I want it to show the first letter in uppercase.
If i using the code that i have giving it shows CoinDetails (it is my page name)
thiss is the code that is not working
<pre>
<?php
$slug = basename(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$slug = preg_replace('/\\.[^.\\s]{3,4}$/', '', $slug);
$slug = ucfirst(strtolower($slug));
?>
Try to use this with this code
<pre><div class="card-header" >
<h5 class="card-title mb-0" ><?php echo $slug; ?></h5>
</div>
|
|
|
|
|
Fix the problem self with this code
<pre><?php echo ucfirst($slug);?>
|
|
|
|
|
how to auto print label in vb to be in the database
|
|
|
|
|
By writing some code.
If you want a better answer, then ask a better question.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I know that in OData, we need to provide an API that gets OData queries as url string. Considering I'm working on Blazor Server App, can I use OData without providing an another API app on the server?
modified 18-Feb-23 3:40am.
|
|
|
|
|
I'm using the following controller to get data from database using EF Core:
public class EquipmentsController : ODataController
{
private readonly SqlServerContext _sqlServerContext;
public EquipmentsController(SqlServerContext sqlServerContext)
{
_sqlServerContext = sqlServerContext;
}
[HttpGet]
[EnableQuery]
public ActionResult<IQueryable<Equipment>> Get()
{
IQueryable<Equipment> eqList = _sqlServerContext.Equipments.AsQueryable()
.Include(x => x.CostCenter)
.Include(x => x.EquipmentCategory)
.Include(x => x.equipmentType);
return Ok(eqList);
}
}
My problem is that I cannot get nested result in the final json while I have included CostCenter, EquipmentCategory, and equipmentType entities. I'm using ASP.NET Core 6 API and OData 8.0.12
My ED model is as follows:
static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new();
builder.EntitySet<Equipment>("Equipments");
return builder.GetEdmModel();
}
How can I fix that?
|
|
|
|
|