|
Sorry about the other message. But looking at your code again I do not see why the StringWriter , or the HtmlTextWriter , are there, as apart from the following two lines:
Dim stringWriter As StringWriter = New StringWriter()
Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWriter)
You never refer to either object (other than in the line with the error).
|
|
|
|
|
Right, you are correct.
I have actually removed them from there but added them some place else like:
dtExportExcel.RenderControl(htmlWrite)
Response.Write(stringWriter.ToString())
|
|
|
|
|
As a simple fix:
Dim sb As New System.Text.StringBuilder()
sb.Append("<html xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:x=""urn:schemas-microsoft-com:office:xlExcel8"" xmlns=""http://www.w3.org/TR/REC-html40""> <head><style> table { mso-number-format:'0'; } </style></head> <body>")
Dim stringWriter As New StringWriter(sb)
Dim htmlWrite As New HtmlTextWriter(stringWriter)
Dim dtExportExcel As New DataGrid()
dtExportExcel.DataSource = dt
dtExportExcel.DataBind()
dtExportExcel.RenderControl(htmlWrite)
sb.Append("</body></html>")
Response.Write(sb.ToString())
Response.[End]()
However, note that you are not "exporting an Excel file"; you are rendering HTML content, but lying to the browser and claiming that it's an Excel file. Excel will display a warning message, and then do its best to import that HTML into a new spreadsheet, but you'll get extremely limited control over the results.
If you actually want to export an Excel file, with precise control over the formatting and layout, then use a library designed to do that - for example, ClosedXML[^] or the Open XML SDK[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
WOW, knowledge is power.
Thank you very much sir and great to hear from you again
With your advise, I was able to successfully use ClosedXML and it is working great.
I still have this solution you provided here as a back up.
Thank you again.
|
|
|
|
|
I have a new Blazor app with two Pages/Blazor components: index.razor and config.razor. The config.razor page lists the database objects that can be edited, and clicking on an object item in the list calls an async Task called ShowDetails that retrieves the details of the selected object to be displayed in an EditForm on the page.
However, after retrieving the object data Blazor returns to index.razor. There is no code that navigates away from the component. No errors are caught. Is this normal behavior? Is there something I can add to stay on the config.razor page?
There are no solutions, only trade-offs. - Thomas Sowell
A day can really slip by when you're deliberately avoiding what you're supposed to do. - Calvin (Bill Watterson, Calvin & Hobbes)
|
|
|
|
|
I found the answer and solution elsewhere, posted below in case this is useful to anyone else.
The object in the second blazor component being clicked on was an HTML anchor element:
<a href="#" class="nav-link btn-link" @onclick="(()=>ShowDetails(app.Id))">
Because an anchor is a navigation element, it has a default action which is to navigate somewhere, in this case to "#" which means to stay on the current page. Blazor is a single-page application so navigating to itself reloads the default "page" which is Index.razor.
To stop that default action the solution is to add the @onclick:preventDefault directive to the anchor element:
<a href="#" class="nav-link btn-link" @onclick="(()=>ShowDetails(app.Id))" @onclick:preventDefault>
Of course, another solution to consider is using a non-navigation HTML element such as a button.
There are no solutions, only trade-offs. - Thomas Sowell
A day can really slip by when you're deliberately avoiding what you're supposed to do. - Calvin (Bill Watterson, Calvin & Hobbes)
|
|
|
|
|
I have TestDTO.cs file inside this file, i have 5 field added as string and serialized that field. then one method created that method getting the called this DTO values. i have now new requirement is added more three fieled in that TestDTO.cs. But now if i add the fields in my class file. i am getting getting error as below:
<pre>Error in line 1 position 276. 'Element' 'additionalLimitAmountField' from namespace 'http://schemas.datacontract.org/2004/07/ACE.Claims.HFC.ACC.Types.Policy' is not expected. Expecting element '_x003C_ClassTest_x003E_k__BackingField'.</pre>
can someone facing this type of issue in the code. so anyone can provide help, tell me how to get one.
|
|
|
|
|
As a guess.
You are attempting to deserialize objects that are completely mismatched. Has nothing to do with your changes. You could test that by removing ONLY the new fields and see if the error remains.
But if not then you have stored serialized data. Or at least a serialized form that is coming with the old form.
You defined your new form such that the new elements are required. If they are not explicitly optional then they are required. So the receiver is trying to read it and the required fields are missing.
There is an annotation form for the DTO that allows you to specify that the forms are optional. Google for that.
|
|
|
|
|
Hi, I'm having a hard time finding a simple enough (ELI5) direct answer to on here and the interwebz
If I have the following html fragment on a razor page. How does the clicked button bind to the viewmodel Gender property (transfer data to/from viewmodel property and radiobutton input element)? If I understand it correctly, this binding happens server-side after a POST. This fragment below would have been inside a form, so ALL (male, female in this case) the radio button input types will get sent together with the hidden element. The expression parameters is what tells server-side to associate the radio buttons to the viewmodel property. Also, doesn't the expression already tell what to bind the radiobutton to (ie the hiddenfor is not necessary)?
<pre lang="Razor">
@model Student
<div>
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")
@Html.HiddenFor(model => model.Gender)
</div>
|
|
|
|
|
RadioButtonFor renders an <input type="radio"> with the name set to the property name, and the value set to the specified value. If the model property matches the specified value, then the radio button will be checked .
<input type="radio"> - HTML: HyperText Markup Language | MDN[^]
When the form is submitted, the name and value of the checked radio button (if any) will be sent to the server, and the model binder will use it to populate the property.
Adding the extra HiddenFor for the same property should not be necessary.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
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.
|
|
|
|
|