Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

What is the best topic to implement multi-languages in asp.net core 2.1?

$
0
0

Hi

I'm totally new to implement internationalization in asp.net core 2.1 MVC project. I searched in Internet and found some topics to implement it step-by-step.

I want my website to support English and Arabic languages only. I found these topics:

https://www.c-sharpcorner.com/article/internationalization-in-asp-net-core-mvc/

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1

https://www.infragistics.com/community/blogs/b/codefusion/posts/building-simple-multilingual-asp-net-core-website

https://medium.com/swlh/step-by-step-tutorial-to-build-multi-cultural-asp-net-core-web-app-3fac9a960c43

I'm tending to the last topic but afraid it is not suitable or different from core MVC (because the example is implemented for none MVC project).

What is the simplest, most suitable, and less effort and time one for my case? or can you provide me a more suitable topic please?


Core 3.1 First query to db takes a long time

$
0
0

Hi,

I have seen this issue all over the web and I have tried many of the suggested scenarios without a lot of success. Sure, I can shave a little bit off the DB query, but not a significant amount of time.

Here is my setup

1) .Net Core 3.1.3 web API

2) SQL 2019

3) Postman

4) Two huge tables (appx 25  million records)

5) I am using migrations (code first)

The first request will take about 20 second to execute and sometime will timeout. But all subsequent requests will take about 2-3 seconds to return results. I am doing a search with "contain" as part of the condition. So I realize that will add some inefficiency to the query.

I have tried the warming suggestion (https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-1/) and that did little or nothing to solve this issue.

I have also seen the suggestion of running a task on startup, which I do not think is a solution to this issue.

So I am looking for a suggestion on the best way to shave time off the query without recreating the wheel. 

Here is a sample of a query.

await _context.Companies
.AsNoTracking()
.Where(s => s.Zip == postalCode && s.CompanyName.Contains(companyName))
.ToListAsync();

Any suggestions would be very helpful.

Thanks,

Tom

ASPNETCORE on Windows Server 2016 core.

$
0
0

Hi everyone.

  How do I install aspnetcore support on Windows Server 2016 CORE? I have the following web.config from an application:

--

<configuration><system.web><authenticationmode="Windows"/><customErrorsmode="Off"/></system.web><system.webServer><handlers><addname="aspNetCore"path="*"verb="*"modules="AspNetCoreModuleV2"resourceType="Unspecified"/></handlers><aspNetCoreprocessPath="dotnet"arguments=".\SGPWeb.dll"stdoutLogEnabled="true"stdoutLogFile=".\logs\stdout"/><httpErrorserrorMode="Detailed"/></system.webServer></configuration>

  That returns error 500.

Thanks.

Hide html tag when formwarding the mail

$
0
0

Hello all , I am sending mail after execution of particular functionality. mail is also getting sent successfully. what I want is actually I have update password link in mail body which I have make as hidden which works fine. but when I am trying to forward the mail to somebody else I am able to see the update link in mail body. i have used <p style="disply:none;">some content goes here</p> as html element.so how can I hide the update link in mail body on mail forwarding.

I am using outlook to check mail and forward it.

Thanking you.

Wrap API responses in a standarized format

$
0
0

Good evening,

I'm not really up to date with ASP.NET Core 3.x and I would like to get an advice.

I'm trying to standarize resource API output to look like this:

	{"statusCode": 200,"statusMessage": "success","meta":
		{"count": 1,"total": 1,"pagination":
			{"page": 1,"pages": 1,"limit": 20
			},"filters": [],"sorters": []
		},"data":
		{
			[
				{"id": 3,"title": "Test","content": "Content Test","userId": 1,"user": null,"categoryId": null,"category": null,"comments": null,"tags": null,"createdOn": null,"updatedOn": null
				}
			]
		}
	}

As opposed to:

[
    {"id": 3,"title": "Test","content": "Content Test","userId": 1,"user": null,"categoryId": null,"category": null,"comments": null,"tags": null,"createdOn": null,"updatedOn": null
    }
]

The approach I've currently applied and works (but I don't find that good) is:

  • I have 2 classes: Resource and ResourceCollection
  • I use generic T classes in it, where T is basically model I'm trying to return (like Article, Post etc.)
  • Return them in controllers as opposed to returning Post or List<Post>

    The result? It works - but I don't think it should be done that way, here's the code for ResourceCollection as Resource is pretty similar:
namespace NppService.Resources
{
    public class ResourceCollection<T> where T : class
    {
        public List<T> Data { get; set; }

        public int Count => Data.Count;

        public int Total { get; set; }

        public ResourceCollection(List<T> data, DbContext context = null)
        {
            Data = data;

            if (context == null)
                return;

            Total = context.Set<T>().Count();
        }
    }
}

Thank you in advance for any advices.

how does the oidc server know what token type it is

$
0
0

if id_token access_token and refresh_token can all be JWT's how does the sever determine which one is being used?

I am thinking its a scope but i can't seeanything in the docs.

ASPNET Core 3.x - The most popular library for performing complex filtering, sorting and pagination queries from client to server?

$
0
0

I have a very complex model that has over 31 fields.

I'm builiding an app where client should be able to filter the database records by each and every of these 31 fields, then sort and paginate the results.

Not only that, I also want to be able to:

  • specify precise value to search for
  • specify a partial value (starts_with, ends_with, contains)
  • specify a range of values (value between %from and %to)
  • specify whether or not to ignore the casing
  • what to sort results by

Is there anything I could use? Perhaps something that would build a json string describing these filters etc. and when sent builds a LINQ query or something?

Thanks in advance!

asp.net and aspnet core session sharing

$
0
0

hi, 

please suggest a better resource for asp.net and aspnetsession sharing among each other . 

best practices when using two applications full dotnet and aspnet core.

session sharnig among them 


get current page title in .net core

$
0
0

hi

i want get current page title in  controller ? how to access and do it ? 

Route to a specific action explicitly from middleware

$
0
0

I'm still trying to migrate my transparent login router to ASP.NET Core 3 with the new endpoint routing. My current approach is to insert a middleware before the routing happens. When this middleware detects that the user is not logged in, the login action must be invoked instead of whatever the URL requested. When the user has logged in, the same original URL will then serve the requested page. Here's my middleware in the Startup.Configure method:

...
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.Use(async (context, next) =>
{
	if (!context.User.Claims.Any())
	{
		var routeData = context.GetRouteData();
		routeData.Values["controller"] = "Account";
		routeData.Values["action"] = "Login";
	}
	// Call the next delegate/middleware in the pipeline
	await next();
});

app.UseEndpoints(endpoints =>
...

It correctly determines the logged in state but then can't change the routing. The shown code will serve the Account/Loginview, but the code still executes the Home/Index action. This doesn't match so I probably destroyed the routing data with this.

How can I force the Account/Login action and view to be called here from the middleware, without changing the URL (no redirect allowed)?

Proper way to Layer my Queueing Infrastructure.

$
0
0

Dear All,

I have 2 micro services. One of the Microservice (Application A) has an Api endpoint that recieve messages from a partner Payment service. So my design is that once I recieve message from a payment partner. I would initiate a Queuing and pass message to that my second Micro services Application B. would be the Consumer would get the message and process it for some other background functions.

I decided to go with this design because I want 100 % gauranttee.

I am using RabbitMQ queuing system. In this system you would have to create a Producer and a consumer.

Based on my design Application A is gong to be the Producer and Application B is going to be the Consumer.

My question goes thus: Is it right for me to create the Queueing producer code from within my endpoint. Endpoint in Application A. Or is the Queueing system suppose to be a background service. I would paste what my Controller end point looks like for Application A.

public class Controller : ApiController
{

   [HttpPost]
   public JsonResponse  Recieve(Request model){


        //I process the request sent from payment partners and save to db.
        //Below I now go and create a Queue which I would call


        QueueProducer  queue= new QueueProducer(model);
        queue.ProcessQueue();//This message is going to process the queue.

 
    }

}




.........Main Code snippet from QueueProducer  below. That is what sends the Producer message to the Queue.

....

public void ProcessQueue()
        {
            using (var connection = CreateConnection())
            using (var channel = connection.CreateModel())
            {
                bool isopen = connection.IsOpen;
                channel.ConfirmSelect(); 
                
                Console.WriteLine("Rabbit Queue connection is open "+isopen);

                logger.Log(LogLevel.Information, "Rabbit Queue connection is open " + isopen);

                QueueName = channel.QueueDeclare().QueueName;

                logger.Log(LogLevel.Information, "Rabbit Queue Name " + QueueName);

                Console.WriteLine("Rabbit Queue Name " + QueueName);

                //channel.QueueDeclare(queue: QueueName);

                /*channel.QueueDeclare(queue: QueueName,
                                durable: false,
                                exclusive: true,
                                autoDelete: true,
                                arguments: null);*/

              

                var outstandingConfirms = new ConcurrentDictionary<ulong, string>();

                outstandingConfirms.TryAdd(channel.NextPublishSeqNo, settlementRequest.ToString());

                void cleanOutstandingConfirms(ulong sequenceNumber, bool multiple)
                {
                    logger.Log(LogLevel.Information,"This callback is called when maessages are delivered and  confirmed for clean up");
                    logger.Log(LogLevel.Information, "QueueProducer \n Cleans out outstanding confirmations in the queue based on delivery");

                    if (multiple)
                    {
                        var confirmed = outstandingConfirms.Where(k => k.Key <= sequenceNumber);
                        foreach (var entry in confirmed)
                            outstandingConfirms.TryRemove(entry.Key, out _);
                    }
                    else
                        outstandingConfirms.TryRemove(sequenceNumber, out _);
                }

                channel.BasicAcks += (sender, ea) => cleanOutstandingConfirms(ea.DeliveryTag, ea.Multiple);
                channel.BasicNacks += (sender, ea) =>
                {
                    outstandingConfirms.TryGetValue(ea.DeliveryTag, out string body);
                    Console.WriteLine($"Message with body {body} has been nack-ed. Sequence number: {ea.DeliveryTag}, multiple: {ea.Multiple}");
                    cleanOutstandingConfirms(ea.DeliveryTag, ea.Multiple);
                };

                
                //Convert the message to bytes
                var bytes = ByteUtility.ObjectToByteArray(settlementRequest);
                var body1 = bytes;

                var timer = new Stopwatch();
                timer.Start();
             
                channel.BasicPublish(exchange: "", routingKey: QueueName, basicProperties: null, body: body1);
                channel.WaitForConfirmsOrDie(new TimeSpan(0, 0, 5));
                timer.Stop();


                if (!WaitUntil(60, () => outstandingConfirms.IsEmpty))
                {
                    logger.Log(LogLevel.Information, "QueueProducer \n  All messages could not be confirmed in 60 seconds");
                    throw new Exception("All messages could not be confirmed in 60 seconds");
                }

                //{MESSAGE_COUNT:N0} 
                logger.Log(LogLevel.Information, $"QueueProducer \n  Published messages and handled confirm asynchronously {timer.ElapsedMilliseconds:N0} ms");
                //Console.WriteLine($"Published {MESSAGE_COUNT:N0} messages individually in {timer.ElapsedMilliseconds:N0} ms");
            }
        }

I asked this question becos while I was readding RabbitMQ documentation. I read that this block of code  

channel.ConfirmSelect();

is meant to be called once, it meant for initiating a Publisher confirmation for guarantteed delivery.

So with the approach that I am taking. My producer code is called to action every time a request hits my end point. So that means that I would always be making subsequest connection to the Rabbitmq server and calling  the    channel.ConfirmSelect();   method.

I dont have any other design flow in my head. So am just confused here. is there a better way to implement this.

How To Clean Nginx Cache?

$
0
0

Hello there,

I uploaded the new version of my ASP.NET Core website that I published with Nginx via FTP. But still the old version appears on the air. I updated the files, but the files were not updated on the Nginx side.

How do you know that you can say that it is not updated. I published my site with incorrect database information in appsettings.json file. I entered the correct information and reloaded the appsettings.json file, but no change was made. I misspelled some javascript files I called, I changed them, but they were not updated again.

You can say delete browser history. I deleted it, but the problem persists. I want the features like Cache and gzip to remain active in terms of site speed. But after publishing an update, I want to delete cache and continue with the new version. I would be glad if you could help.

Nginx/sites-available/default 

server {
	listen 80 default_server;
	listen [::]:80 default_server ipv6only=on;

	server_name sansurlu.com www.sansurlu.com;

	root /var/www/sansurlu;
	index index.html;


 gzip  on;
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_proxied any;
    #gzip_types text/plain text/html text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml;
    gzip_buffers 16 8k;
    gzip_disable “MSIE [1-6].(?!.*SV1)”;



	location ~* /(css|js) {
		root /var/www/sansurlu/wwwroot;		
	}

	location ~/assets/images {
		root /var/www/sansurlu/wwwroot;
	}

	location ~/assets/font-awesome{
		root /var/www/sansurlu/wwwroot;
	}

 location / {
 proxy_pass http://localhost:5000;
 proxy_http_version 1.1;
 proxy_set_header Upgrade $http_upgrade;
 proxy_set_header Connection keep-alive;
 proxy_set_header Host $host;
 proxy_cache_bypass $http_upgrade;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 }

}

Creating an Endpoint that can read any json. A generic endpoint API

$
0
0

So I have a requirement to have one endpoint that can read json payload that can hit it from different system. We have several partners that would be posting data to our system.  So we want one endpoint that would handle getting data from any of our partners posting data.

I have something like this already.

[HttpPost]
public string Getdata([FromBody]Object data)
{

  //how do I convert it to the specific class that sooths the  json payload.

  //Or how do I read the data attribute of the object data pasted without knowing the payload structure.
}

I need to be able to create a generic json reader like this system here

https://quicktype.io/csharp/

So when data hits me I can read the data.

Best Regards,

Thanks in Advance

How To Connect MySQL With ASP.NET Core

$
0
0

I need connect .NET CORE Application with MySQL and read data from MySQL, using .NET Core MySQL connector

this is the tutorial

I followed step by step the instructions of the tutorial, but on debug in VS 2019 the error is

System.NullReferenceException:'Object reference not set to an instance of an object.'

ConnectionString is null, why?

On this part

privateMySqlConnectionGetConnection(){returnnewMySqlConnection(ConnectionString);}

Any idea?

I really tried everything I could find on google without success...

SakilaContext.cs

usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespace MvcSakilaCore.Models{publicclassSakilaContext{publicstringConnectionString{get;set;}publicSakilaContext(string connectionString){this.ConnectionString= connectionString;}privateMySqlConnectionGetConnection(){returnnewMySqlConnection(ConnectionString);}publicList<Film>GetAllFilms(){List<Film> list =newList<Film>();using(MySqlConnection conn =GetConnection()){
                conn.Open();MySqlCommand cmd =newMySqlCommand("SELECT * FROM film", conn);using(MySqlDataReader reader = cmd.ExecuteReader()){while(reader.Read()){
                        list.Add(newFilm(){FilmId= reader.GetInt32("film_id"),Title= reader.GetString("title"),Description= reader.GetString("description"),ReleaseYear= reader.GetInt32("release_year"),Length= reader.GetInt32("length"),Rating= reader.GetString("rating")});}}}return list;}}}

FilmsController

publicclassFilmsController:Controller{publicIActionResultIndex(){SakilaContext context =HttpContext.RequestServices.GetService(typeof(RazorPagesMovie.Models.SakilaContext))asSakilaContext;returnView(context.GetAllFilms());}}

Startup.cs

publicvoidConfigureServices(IServiceCollection services){
    services.AddControllersWithViews();
services.AddMvc();
services.AddTransient<MySqlConnection>(_ =>newMySqlConnection(Configuration["ConnectionStrings:DefaultConnection"])); services.Add(newServiceDescriptor(typeof(SakilaContext),newSakilaContext(Configuration.GetConnectionString("DefaultConnection"))));} app.UseEndpoints(endpoints =>{ endpoints.MapControllerRoute( name:"default", pattern:"{controller=Films}/{action=Index}/{id?}");});

appsettings.json

{"ConnectionsStrings":{"DefaultConnection":"server=localhost;port=3306;database=sakila;user=XXX;Password=XXX",
"ProviderName": "MySql.Data.MySqlClient"
},"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"}},"AllowedHosts":"*"}

How to use Reflection in linq queries ?

$
0
0

Hi

I'm looking for a way to use reflection in my linq queries to increase code reusability. for example, i want to change this method :

private Orders GetObjectGraph(MyDbContext dbContext, int orderID)
{
	return dbContext.Orders.Include(o => o.OrderDetails).AsNoTracking().FirstOrDefault(o => o.OrderID == orderID);
}

To something like this :

private object GetObjectGraph(MyDbContext dbContext, string masterEntityName, string detailsEntityName, string masterFieldName, object masterFieldValue)
{
	return dbContext[masterEntityName].Include(o => o[detailsEntityName]).AsNoTracking().FirstOrDefault(o => o.[masterFieldName] == masterFieldValue);
}

Can anybody help me how to accomplish this task ?

Thanks in advance


Core DI injection with user id

$
0
0

I would like to inject a user ID to all my services and utilities.

Here is my current setup:

    public class StructureUtilities : IStructureUtilities
    {
        /// <summary>
        /// The structure service
        /// </summary>
        private readonly IStructureService structureService;
        private readonly IMapper mapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="StructureUtilities" /> class.
        /// </summary>
        /// <param name="structureService">The structure service.</param>
        /// <param name="mapper">The mapper.</param>
        public StructureUtilities(IStructureService structureService, IMapper mapper)
        {
            this.structureService = structureService;
            this.mapper = mapper;
        }

        /// <summary>
        /// Gets the structure tree.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <returns>GetStructureTree</returns>
        public async Task<IEnumerable<StructureTreeViewModel>> GetStructureTree(int userId)
        {
            var test = await structureService.GetStructureTreeByUserId(161).ConfigureAwait(false);
            return mapper.Map<IEnumerable<StructureTreeViewModel>>(test);
        }
    }
}
        public void RegisterDependencyTypes(IServiceCollection services)
        {
            int loggedInuser = 161;

            // Context Model
            services.AddSingleton(x =>
            {
                return new ContextModel(loggedInuser);
            });

            services.AddSingleton<IMapper>(x => new Mapper(mapperConfiguration));

            services.AddSingleton<IStructureUtilities, StructureUtilities>();
            services.AddSingleton<IStructureService, StructureService>();
            services.AddSingleton<IStructureRepository, StructureRepository>();
        }

So how would set this up so I can pass a user id in of the logged-in user?

I would want to do this on the StructureService as well.

Remoing tag from string in c#

$
0
0

Hello All,

I have string with multiple html tags like div,p.

I want to remove the p tag from string how can I do that from c# code?

Please suggest solution

Thanks

Json configuration with polymorphic array

$
0
0

Is it possible to have a polymorphic array setup by json configuration?

E.g. the following code (all in one file only for the demo of course):

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;

namespace PolymorphicConfigurationArray
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.Configure<ApplicationOptions>(hostContext.Configuration.GetSection("Application"));
                    services.AddHostedService<Worker>();
                });
    }
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger, IOptions<ApplicationOptions> options)
        {
            _logger = logger;
            logger.LogInformation($"Configuration Description {options.Value.Description}");
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
    public class ApplicationOptions
    {
        public string Description { get; set; }
        public ConfigItem[] Items { get; set; }
    }
    public class ConfigItem
    {
        public string ItemName { get; set; }
    }
    public class ConfigItemWithValue : ConfigItem
    {
        public double ItemValue { get; set; }
    }
}

The json file below may be used to intantiate the ApplicationOptions class with some ConfigItems in the Items array, however, I cannot see any way to get the derived ConfigItemWithValue class from configuration and thus having the Items array as a polymorphic array.
Is this simply the limitation of json (key/value)?

I know that newtonsoft.json may serialize/deserialize such a graph by some typename options, is this possible to use in any way for configuration (without a lot of custom code of course)

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"Application": {"Description": "Wondering how to achieve polymorphic array with json configuration","Items": [
      { "ItemName": "Name1" },
      { "ItemName": "Name2" }
    ]
  }
}

c# data annotations validade Model, out of context of form binding (upload file)

$
0
0

I’m using asp.net core 3.1 razor pages and wanna validade a model on a upload process using data annotation.

My model is:

public class UserUpload
{
[Key]
public string UserId { get; set; }

[Required(ErrorMessage = "email must be informed"), DataType(DataType.EmailAddress)]
public string Email { get; set; }

[Required, MaxLength(100, ErrorMessage = "Maximum for name is 100 chars")]
public string Name { get; set; }

[Required]
public string Status { get; set; }
}

Processing each line of the file uploaded how can I use data annotations to validade records and get all errors?

I have a crud for the same model and validations are processed by the framework resulting ModelState identifying all errors but I don´t know how to use the same mechanism in the mass upload data.

Tks

CommandLineConfigurationProvider

$
0
0

I am using generic host for a console app (not a daemon style service, just a shortlived app) by .AddHostedService() (I guess I can use a transient or singleton, but I don't know how to instantiate it).

Construction Injection of  IOptions<MyConfigClass>, ILogger<MyServiceClass> etc. works fine for json provider.
however, I would (preferably) like to use CommandLine provider for setting one of the properties of the T object from args array, but don't understand how to do this.

Alternatively I would like to inject one string out of args directly, but don't know how to this either.

Someone hint me?

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>