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

The entity type 'AllVM' requires a primary key to be defined for VM with EF Core

$
0
0

Hi

I'm trying to return multiple different non related models in one view as aggregate interface page (each one in html tab) with Entity Framework Core (Core 2.1).

Holidays model:

    public class Holidays
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

Actions model:

    public class Actions
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

AllVM model:

    public class AllVM
    {
        public IList<Holidays> Holidays { get; set; }
        public IList<Actions> Actions{ get; set; }
    }

ApplicationDBContext:

public virtual DbSet<Actions> Actions { get; set; }
public virtual DbSet<Holidays> Holidays { get; set; }
public virtual DbSet<AllVM> AllVM { get; set; }

Controller:

    public class MyController : Controller
    {
        private readonly ApplicationDbContext _context;

        public MyController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> AllIndex()
        {
            var all = _context.AllVM.Include(s => s.Holidays).Include(s => s.Actions).AsQueryable();

            return View(await all.ToListAsync());
        }

But this scenario gives me the error:

InvalidOperationException: The entity type 'AllVM' requires a primary key to be defined.

I don't want to define a primary key for the ViewModel, I want only to return 2 or more non-related models in AllIndex view each one of them in a tab.

How please?


.NET Core log un-handled exceptions in the console

$
0
0

Hello,

I'm currently working on a personal project written in ASP.Net core, due to the way logging is set, unhandled exceptions aren't logged into the Console.

When I encounter a problem I usually connect /w the debugger and the resolve/handler the Exception. I don't want to use a huge try/catch in my BackgroundService sub class to log unhandled exceptions. I'm kinda new to the ecosystem and I don't know what's the best way to achieve this.

Is there any settings that that logs un-handled exceptions to the console?  I'm also thinking about using a third-party service like Sentry to track my exceptions.

Thank you very much!

ASP.Net Core architecture and flow explanation

$
0
0

I would like to understand ASP.Net Core in-depth, so I would understand the entire flow and the components involved from the http request to the response in the case of simple rest API.
So not only the middleware pipeline but also the components that control authorization, validation, serialization etc.

Can you show me a good resource to find this kind of information or a good book?

Microsoft's documentation is ok but not thorough. The only idea I have at the moment is to only follow the flow stages by debugging the ASP.Net Core source code, but it's a bit difficult.

How to add a list item to a property of type IEnumerable ?

$
0
0

I want to create an `ActionResult` to add a new record.
I plan to use the  [HttpPost] `ProductEdit(Product model)` method.

Question.
How to add a list item to a property of type IEnumerable <T>?
Or how to make this decision simpler?

Product.cs

public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

    }

MockProduct.cs

public class MockProduct
    {
        List<Product> productList;

        public MockProduct()
        {
            productList = new List<Product> 
            {
                new Product {ID = 1, Name = "Name_1", Description = "Description_1"},
                new Product {ID = 2, Name = "Name_2", Description = "Description_2"},
                new Product {ID = 3, Name = "Name_3", Description = "Description_3"},
            };

        }

        public IEnumerable<Product> ProductList
        {
            get
            {
                return productList;
            }
            set
            {
                productList.Add(value as Product);
            }    
        }
    }



HomeController.cs

public class HomeController : Controller
    {
        MockProduct mckProduct;
        public HomeController()
        {
            mckProduct = new MockProduct();
        }

        public IActionResult Index()
        {
            var model = mckProduct.ProductList;

            return View(model);
        }

        public IActionResult ProductEdit()
        {
            Product model = new Product();
            return View(model);
        }

        [HttpPost]
        public IActionResult ProductEdit(Product model)
        {
            // ????? 
            mckProduct.ProductList.Append(model);

            var v = mckProduct.ProductList;

            return View(model);
        }

Edit.cshtml

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@using WebApplCore.Models
@model Product
<head><link href="~/css/bootstrap.min.css" rel="stylesheet" type="text/css" /></head><h3>*** Edit Page ***</h3><body><div><form asp-controller="Home" asp-action="ProductEdit" method="post" ><input type="hidden" asp-for="ID" /><div asp-validation-summary="All"></div><div><label asp-for="Name"></label><input asp-for="Name" /><span asp-validation-for="Name"></span></div><div><label asp-for="Description"></label><textarea asp-for="Description"></textarea><span asp-validation-for="Description"></span></div><input type="submit" value="Сохранить" /></form></div><script src="~/js/bootstrap.min.js"></script><script src="js/jquery-2.1.4.min.js"></script></body>



System.TypeInitializationException: 'The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Data.Database' threw an exception.'

$
0
0

Hi Team,

I am using this namespace using Microsoft.Practices.EnterpriseLibrary.Data; to connect the database.

public static Database CreateDatabase(string connectionString,bool isEncrypted=false)
{
try
{
string decryptedConnectionString;
if (isEncrypted)
{
decryptedConnectionString = DecryptConnectionString(connectionString);
}
else
{
decryptedConnectionString = connectionString;
}
Database database = new SqlDatabase(decryptedConnectionString);
return database;
}
catch(Exception ex)
{
throw new Exception("Error reading database details. Error:" + ex.Message);
}
}

At this line Database database = new SqlDatabase(decryptedConnectionString);, I am getting below exception.

I am using Asp.Net core 3.0 Web API

System.TypeInitializationException: 'The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Data.Database' threw an exception.'

FileNotFoundException: Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

Deploy failed on heroku with asp.net-core webapi dockerized app

$
0
0

Hello everyone,

I've been looking for few days many tutorials to try to find my solution but i just can't get it.

Overview :
Im building an Asp.net Core (3.1) app which i've set up for running on docker. My goal is to deploy it to heroku.

Problem :
I can make it work on local to try with a docker container run but when i deploy it to heroku (the image was created without troubles) i get the error screen message:

"Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command"

Setup

Heroku :

  •  dyno in use : **api** /bin/sh -c ASPNETCORE_URLS\=http://\*:\$PORT\ dotnet\
  • build pack : https://github.com/jincod/dotnetcore-buildpack

Code

Dockerfile

FROM mcr.microsoft.com/dotnet/core/sdk:3.1.100 AS build

WORKDIR /src
COPY *.sln .
COPY Ecomm.UnitTests/*.csproj Ecomm.UnitTests/
COPY Ecomm.Api/*.csproj Ecomm.Api/
RUN dotnet restore
COPY . .

# testing
FROM build AS testing
WORKDIR /src/Ecomm.Api
RUN dotnet build
WORKDIR /src/Ecomm.UnitTests
RUN dotnet test

# publish
FROM build AS publish
WORKDIR /src/Ecomm.Api
RUN dotnet publish -c Release -o /src/publish



FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /src
COPY --from=publish /src/publish .
# heroku uses the following
CMD ASPNETCORE_URLS=http://*:$PORT dotnet Ecomm.Api.dll

Program.cs (default script)

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
    });
}


Startup.cs (default script)

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }


Launchsettings.json

"Ecomm.Api": {"commandName": "Project","launchBrowser": true,"launchUrl": "/weatherforecast","applicationUrl": "https://localhost:5001;http://localhost:5000","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Production"
      }
    }

Comparaison between running a container locally and deploy to heroku

Local interface

Local interface

Heroku interface :
Heroku interface

methods used to push on Heroku container register:

docker login --username=_ --password=$HEROKU_API_KEY registry.heroku.com
heroku container:push api -a $HEROKU_APP_NAME --recursive 
heroku container:release api -a $HEROKU_APP_NAME



Errors logs in heroku :

2020-01-18T14:53:32.255720+00:00 heroku[api.1]: State changed from crashed to starting

2020-01-18T14:53:35.853732+00:00 heroku[api.1]: Starting process with command `/bin/sh -c ASPNETCORE_URLS\=http://\*:\59573\ dotnet\ Ecomm.Api.dll`

2020-01-18T14:53:36.494742+00:00 heroku[api.1]: State changed from starting to up

2020-01-18T14:53:37.754733+00:00 app[api.1]: Hosting environment: Production

2020-01-18T14:53:37.754802+00:00 app[api.1]: Content root path: /src

2020-01-18T14:53:37.754925+00:00 app[api.1]: Now listening on: http://[::]:59573

2020-01-18T14:53:37.754946+00:00 app[api.1]: Application started. Press Ctrl+C to shut down.

2020-01-18T14:53:39.762409+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=dariorega-ecomm-api.herokuapp.com request_id=7538ce41-5d5e-4081-b214-eb1e50fdcc6c fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

2020-01-18T14:53:40.075446+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=dariorega-ecomm-api.herokuapp.com request_id=4f1ff94a-eb45-4301-9c3a-74ece82abe84 fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

2020-01-18T14:53:51.155230+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/api" host=dariorega-ecomm-api.herokuapp.com request_id=1cc3eeac-1ce5-4a67-82e0-ee680beecc90 fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

2020-01-18T14:53:51.440188+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=dariorega-ecomm-api.herokuapp.com request_id=caa51bcd-a153-444b-88b5-c024d1b2ae84 fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

2020-01-18T14:53:56.045125+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/weatherforecast" host=dariorega-ecomm-api.herokuapp.com request_id=bcdc8195-9da6-4258-a48b-4614d885302a fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

2020-01-18T14:53:56.292724+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=dariorega-ecomm-api.herokuapp.com request_id=2329aa44-bdb0-43e3-bbbf-58bd87a09f8c fwd="188.155.40.41" dyno= connect= service= status=503 bytes= protocol=https

Logs i get in local container :
after running a docker container run with that same dockerfile :

info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:5000

info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.

info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production

info: Microsoft.Hosting.Lifetime[0]
Content root path: /src

warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect


Conclusion

I've tried many things in the docker file or to edit the program.cs defining useUrl methods but i still can't make it work. I don't know if somethings is related beceause of the http /https process since the https: isnt setup/working and heroku use https.
Or i should define an url somehwere, well, any help welcome !
Thanks in advance for your time taken reading this

Add items to a list from view model

$
0
0

Hey how's it going,

I'm working on a deck builder for a card game. My rough build is up on https://chronoclashdeckbuilder.azurewebsites.net/DeckBuilder and I have the project on my github https://github.com/Zami77/ChronoClashDeckBuilder

The idea is to click the images that are on the deck builder page and have them be dynamically added to a list. Once the list is complete I could then have it be saved to my SQL database tied to a user account. I'm focusing just on one step at a time, and I'd like to be able to dynamically add and remove cards from the list and have them be displayed to the user. I'll post what I think are the relevant code sections, but if it feels something is missing please check out my github. Thanks in advance for any help!

DeckBuilder View Index.cshtml

@model ChronoClashDeckBuilder.Models.ViewModels.DeckBuilderListViewModel

@{
    ViewData["Title"] = "Deck Builder";
}<h1>Deck Builder!</h1><p>Still have to implement picking a card and adding to deck.</p><p><a class="badge-dark" asp-area="" asp-controller="DeckBuilder" asp-action="Index" asp-route-curDeck="@Model.NewDeck">Display Deck</a></p><tbody>
    @foreach (var item in Model.NewDeck)
    {<tr><td>
                @item.CardName</td></tr>
    }</tbody><tbody>
    @foreach (var item in Model.Cards)
    {<tr><td><input type="image" src="~/Images/Chrono Clash Card Images/Naruto Set 1/@item.CardImage"
                       alt="@item.CardName"
                       style="width:136px;height:185px;" />
                @*How to add from viewlist to razor page, check javascript
                asp-action="@model.newdeck.add(item)"*@</td></tr>
    }</tbody>

DeckBuilderController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChronoClashDeckBuilder.Models;
using Microsoft.AspNetCore.Mvc;

namespace ChronoClashDeckBuilder.Controllers
{
    public class DeckBuilderController : Controller
    {
        private ICardRepository repository;
        public DeckBuilderController(ICardRepository repo)
        {
            repository = repo;
        }
        public IActionResult Index(List<Card> curDeck, Card cardToAdd)
        {
            if (cardToAdd != null)
                curDeck.Add(cardToAdd);

            return View(new Models.ViewModels.DeckBuilderListViewModel
            {
                Cards = repository.Cards,
                NewDeck = curDeck
            });
        }
    }
}

Models Card.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ChronoClashDeckBuilder.Models
{
    public partial class Card
    {
        [Key]
        [StringLength(20)]
        public string CardNumber { get; set; }
        [StringLength(20)]
        public string CardSet { get; set; }
        [StringLength(20)]
        public string CardType { get; set; }
        [StringLength(100)]
        public string CardImage { get; set; }
        [StringLength(10)]
        public string CardColor { get; set; }
        public int? CardCost { get; set; }
        public int? CardStrength { get; set; }
        [StringLength(80)]
        public string CardName { get; set; }
        [StringLength(200)]
        public string CardAbilities { get; set; }
        [StringLength(200)]
        public string CardStackAbilities { get; set; }
    }
}

ViewModels DeckBuilderListViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ChronoClashDeckBuilder.Models.ViewModels
{
    public class DeckBuilderListViewModel
    {
        public IEnumerable<Card> Cards { get; set; }
        public List<Card> NewDeck { get; set; }
    }
}

Required Attribute not working

$
0
0

Hi,

I am working in asp.net 2.2 and i am doing model validation globally. below is code 

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.ComponentModel.DataAnnotations; 

namespace ModelValidataionTest
{

public class UserReqTest
    {
       [Required(ErrorMessage = "Code required")]
        public string Code { get; set; }

        public UserReq userInfo;
    }

    public class UserReq

    {
        [Required(ErrorMessage = "FirstName required", AllowEmptyStrings = false)]
        public string FirstName { get; set; }


        [Required(ErrorMessage = "LastName required", AllowEmptyStrings = false)]
        public string LastName { get; set; }


        [Required(ErrorMessage = "EmailAddess required", AllowEmptyStrings = false)]
        public string EmailAddess { get; set; }


        [Required(ErrorMessage = "UserName required", AllowEmptyStrings = false)]
        public string UserName { get; set; }
}

}

//Global Validation Class 

 public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var problemDetails = new ValidationProblemDetails(context.ModelState)
                {
                    Instance = context.HttpContext.Request.Path,
                    Status = StatusCodes.Status400BadRequest,
                    //Type = "https://asp.net/core",
                    Detail = "Please refer to the errors property for additional details."
                };
                context.Result = new BadRequestObjectResult(problemDetails)
                {
                    ContentTypes = { "application/problem+json", "application/problem+xml" }
                };
            }
            base.OnActionExecuting(context);
        }
    }



startup.cs



  services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateAttribute));
            });


TestController.cs

[HttpPost("UserTest")]
        public IActionResult CreateUser(UserReqTest req)
        {
            return Ok(req);
        }

I was trying to test the validation and if i dont give any value to the Property Code, its validating. sample request body

Request Body : 

{
  "userInfo": {"FirstName": "john","LastName": "Test","EmailAddess": "string","UserName": "string"
  },"Code": ""
}

Response Body :

{
  "errors": {"Code": ["Code required"
    ]
  },"title": "One or more validation errors occurred.","status": 400,"traceId": "0HLV4NQKG80L4:00000001"
}

But if the properties in the UserReq class not getting validated if its empty string. Sample Request below,

{"userInfo": {"FirstName": "","LastName": "","EmailAddess": "string","UserName": "string"
  },"Code": "Test"
}

in this case, i should get error message as first name, last name  required error. but the request gets success. not getting validated. so, basically, properties of object inside calls not getting validated. please let know how to solve this issue.


Moving from ASP.Net Core 2.2 API to ASP.Net Core 3.1 API: decimals stopped showing decimal part

$
0
0

Hi,

I had an ASP.Net Core 2.2 Web API, with several GET operations where decimals always had the decimal part, even when the value of a property as 0.

Now I've changed the target framework to .Net Core 3.1 and some decimals (not all) began output without the separator and the decimal part. This is strange because there are some properties that do this, and others that kept showing the separator and the decimal part.

Practical example:

Before:

{"price": 13.00,"quantity: 0.0
}

After:

{"price": 13.00,"quantity: 0
}

Notice quantity property.

On the 2.2 version, I didn't have any kind of configuration on startup or whatsoever that would treat decimals differently.

This doesn't seem to be critical or error, but it's different. And I'm curious, why some properties it cuts the separator and the decimal part, and others fills decimal part like it was doing before?

'ILoggingBuilder' does not contain a definition for 'AddEventLog'

$
0
0

Hi,

I am trying to use AddEventLog for Worker Service on ASP.NET Core 3.1.3 I have installed NuGet Microsoft.Extensions.Logging.EventLog

Problem is I am getting the error 'ILoggingBuilder' does not contain a definition for 'AddEventLog'

Here is my code:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
    .ConfigureLogging((context, logging) =>
    {
        logging.AddEventLog(new EventLogSettings()
        {
            SourceName = "MySource",
            LogName = "MyLogName"
        });
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddHostedService<Worker>();
    });
}

Asp.net Core 3.1 : Missing EF Functionalities ...

$
0
0

Hi

i've create new asp.net core project with mvc template from my vs 2019 (asp.net core 3.1). now like always, i want to add new entity data model to configure my project from an existing database, but i don't found entity data model template in add new Items!

Also, i've installed this packages :

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

But still i can not found. Can anybody help me ?

Thanks in advance

Unable to locate a local database runtime Installation

$
0
0

I am using container in Docker with asp.net core 3.1.  I have one solution with projects on it and one of those is the library where database models using EF Core resides that is reference to the web app and the other one is the Web App project.

when I run the web app project I got the error that it cannot find my localdb. However, if I will not use docker it will just run fine and able to connect to the database.
My approach is I saw this while I was googling,  I override the  LaunchSettings  with this

"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://+:443;http://+:80",
"ASPNETCORE_HTTPS_PORT": "44330",
"ConnectionStrings:DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=SBEDB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"httpPort": 10000,
"useSSL": true,
"sslPort": 44330
}

but no luck.

Here is my DockerFile

#escape=`
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat
FROM mcr.microsoft.com/powershell:nanoserver-1903 AS downloadnodejs
SHELL ["pwsh", "-Command", "$ErrorActionPreference = 'Stop';$ProgressPreference='silentlyContinue';"]
RUN Invoke-WebRequest -OutFile nodejs.zip -UseBasicParsing "https://nodejs.org/dist/v10.16.3/node-v10.16.3-win-x64.zip"; `
Expand-Archive nodejs.zip -DestinationPath C:\; `
Rename-Item "C:\node-v10.16.3-win-x64" c:\nodejs

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1903 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
COPY --from=downloadnodejs C:\nodejs\ C:\Windows\system32\

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 AS build
COPY --from=downloadnodejs C:\nodejs\ C:\Windows\system32\
WORKDIR /src
COPY ["SBE.Management.Funds/SBE.Management.Funds.csproj", "SBE.Management.Funds/"]
COPY ["SBE.Management.Funds.Services/SBE.Management.Funds.Services.csproj", "SBE.Management.Funds.Services/"]
COPY ["SBE.Management.Funds.Repositories/SBE.Management.Funds.Repositories.csproj", "SBE.Management.Funds.Repositories/"]
COPY ["SBE.Management.Funds.Base/SBE.Management.Funds.Base.csproj", "SBE.Management.Funds.Base/"]
COPY ["SBE.Management.Funds.Core/SBE.Management.Funds.Core.csproj", "SBE.Management.Funds.Core/"]
RUN dotnet restore "SBE.Management.Funds/SBE.Management.Funds.csproj"
COPY . .
WORKDIR "/src/SBE.Management.Funds"
RUN dotnet build "SBE.Management.Funds.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "SBE.Management.Funds.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "SBE.Management.Funds.dll"]




What did I missed? 
Thanks

EventLogSettings not functioning

$
0
0

Hi,

I am trying to set EventLogSettings but the log continues to write to the default Windows Logs -> Application

Using .net 3.1 to build Worker Service

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .UseWindowsService()
        .ConfigureLogging((context, logging) =>
        {
            logging.AddEventLog(new EventLogSettings()
            {
                SourceName = "TestSource",
                LogName = "TestLog"
            });
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<Worker>();
        });

I have also tried to add a log with powershell    New-EventLog -LogName TestLog -Source TestSource

AG

Problem to pass multiple arguments to javascript function inside razor page!

$
0
0

Hi

i have a simple asp.net core project which display persons with orders for each person.

Here is my chtml code :

@model IEnumerable<Persons><table class="table table-bordered"><tr><th>Person ID</th><th>Person Name</th><th>Description</th><th>Commands</th></tr>
    @if (Model != null)
    {
        foreach (var item in Model)
        {<tr onclick="viewItem(@item.PersonId, @item.PersonName)"><td>@item.PersonId</td><td>@item.PersonName</td><td>@item.Description</td><td>                   </td></tr>
        }
    }</table><div id="htmOrders">Orders</div><hr />

@section Scripts{ 
    
    <script>       
        function viewItem(personId, personName) {$('#htmOrders').html('Orders for ' + personName + '(' + personId + ')');
        }</script>

}

As u sess in my above code, i Have a simple javascript function named 'viewItem' which works correctly with single argument! My problem is that when add second argument and pass personName to it, at runTime i've got error in console :

SyntaxError: missing ) after argument list

Where is my probelm & how to solve it?

Thanks in advance

Javascript code not working in partial views!

$
0
0

Hi

in my Index view, i load a partial view with jquery.get method. it works correctly. my problem is that in my partialView i've used some javascript code which not working!

here is my simple partial view javascript code :

@model IEnumerable<Orders><button type="button" id="btnNew" class="btn btn-success btn-sm" onclick="newOrderItem()">Create new</button><br /><table class="table table-bordered"><tr><th>Order ID</th><th>Order Number</th><th>Order Date</th><th>Commands</th></tr>
    @if (Model != null)
    {
        foreach (var item in Model)
        {<tr><td>@item.OrderId</td><td>@item.OrderNumber</td><td>@item.OrderDate.Value.ToShamsiDate()</td><td>                   </td></tr>
        }
    }</table>

@section Scripts {
    
    <script src="~/lib/jquery/dist/jquery.min.js"></script><script>
        function newOrderItem() {
            alert('Hii');
        }</script>

}

As u see in my code, i have a button, in click event call javascript function with simple alert, but at runTime i'm facing this error in console :

ReferenceError: newOrderItem is not defined

I'm also include jquery file in my partial view, but i'm facing the same problem!

Where is my problem & how to solve it?

Thanks in advance


Remote API Access

$
0
0

Hi all, I have a net core 3.1 WebAPI service running on a Linux box on my local LAN as a daemon and it all works as expected.

How can I expose the service so it is available outside my Lan ?

What I've done

Forwarded the listening port on my router to the local ip and port on my Lan where the WebAPI resides.

Result when calling a controller method
404 not found, the API is using Nginx as a reverse proxy

Please let me know if I haven't supplied enough information

remote validation firing for unmodified and valid field and blocking form submit

$
0
0

Hi,

I have a form which I am loading for user edit . One of the fields is an ID field which I want to check is valid.  If I don't modify any of the fields on the form and click submit, the remote validation fires, returns true and blocks the submit. I see in the debug window the remote validation is called and returns true, but the submit action on the controller is never called. 

If I click on the field and then move to another field remote validation fires and then I can submit the form.  It seems like If i don't edit any of my form data and push submit then the remote validation fires and blocks submit even though it is returning true.  Then I have to push submit again for my submit action to be invoked on my controller.

Anyone know a way around this ? 

The entity type 'AllVM' requires a primary key to be defined for VM with EF Core

$
0
0

Hi

I'm trying to return multiple different non related models in one view as aggregate interface page (each one in html tab) with Entity Framework Core (Core 2.1).

Holidays model:

    public class Holidays
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

Actions model:

    public class Actions
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

AllVM model:

    public class AllVM
    {
        public IList<Holidays> Holidays { get; set; }
        public IList<Actions> Actions{ get; set; }
    }

ApplicationDBContext:

public virtual DbSet<Actions> Actions { get; set; }
public virtual DbSet<Holidays> Holidays { get; set; }
public virtual DbSet<AllVM> AllVM { get; set; }

Controller:

    public class MyController : Controller
    {
        private readonly ApplicationDbContext _context;

        public MyController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> AllIndex()
        {
            var all = _context.AllVM.Include(s => s.Holidays).Include(s => s.Actions).AsQueryable();

            return View(await all.ToListAsync());
        }

But this scenario gives me the error:

InvalidOperationException: The entity type 'AllVM' requires a primary key to be defined.

I don't want to define a primary key for the ViewModel, I want only to return 2 or more non-related models in AllIndex view each one of them in a tab.

How please?

Can JObject lead to Memory Leaks in High Usage Envrionment?

$
0
0

I am trying to implement solution in asp.net core 3. I need to make few private properties REDACTED for security purposes while logging into file. As JsonDocument is readonly and I cannot use JsonPath as well, I have shifted to NewtonSoft for this purpose and use JObject.Parse. My concerns are:

  • How much it will affect my performance?

  • Will it lead to memory leaks?

Code:

var requestTokens =JObject.Parse(requestBodyText);// parse request/response foreach(string property inRedactedFields)//for each redacted field in list{JToken token = requestTokens.SelectToken(property);// apply jsonpathif(token !=null){// jsonpath found((Newtonsoft.Json.Linq.JValue)token).Value="******REDACTED******";
        requestTokens.SelectToken(property).Replace(token);}}

pulling a numerical value out of a dropdown box html

$
0
0

Looking for some help on how to pull out a numerical value from a drop down box back into an if statement in a  controller:

Dropdown box:

<div class="form-group"><select class="form-control" name="Role"><option value="">Select your accout type</option><option value="0">optionOne</option><option value="1">otionTwo</option></select></div>
 if (optionOne is chosen)
 {
       set a database field to 2                
 }

 if(optionTwo is chosen)                
 { 
       set a database field to 3
 }

I'm looking at inserting two different integers  into a database depending on which option is selected from the dropdown box.


Viewing all 9386 articles
Browse latest View live


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