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

Asp.Net Core 2.2 - HTTP Error 500.0 - ANCM In-Process Handler Load Failure

$
0
0

I'm developing an application in Asp.Net 2.2.
I made the application public via FTP.
When I access the service with my application I get the following error.
The hosting service tells me that something is missing for me to do, and that the fault is not from the server.
The application works perfectly on localhost.

I'm waiting

HTTP Error 500.0 - ANCM In-Process Handler Load Failure
Common causes of this issue:
The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
The in process request handler, Microsoft.AspNetCore.Server.IIS, was not referenced in the application.
ANCM could not find dotnet.
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028526


ASP.Net 4.5 to ASP.Net core 2.0.1 migration

$
0
0

Hello All, PLease help to migrate EF 6.2.0 to EF core 2.x version, My current web application is using EF 6 code first approach to create DB, now i would like to migrate the EF framewoek to core with new columns added, my configuration is using DropCreateDatabaseIfModelChanges, i don't want to lose data in the DB for recreation.  What are the options to achieve this migration?

Thanks in Advance,

Geetha

is it possible to access database in an Authorization Filter?

$
0
0

hi,

I take database via constructor in classes and in action filters after the action execution I use resultContext.HttpContext.RequestServices.GetService<T>(); and then via a service I can access the database. does anyone knows how I can use database in Authorization Filter and is it a right approach to do so?

I can create an object from datacontext but I don't know what should the DbContextOptions be.

Thanks in advance

Get child Ids recursively

$
0
0

There are a TON of examples online, yet I can't find one that addresses what I need, and I'm just not really getting the nuances of recursion. I have an application user table that has a "ParentId" column. I have to start with one user's Id and query the database to find all users whose ParentId is that user's Id, then all users whose ParentId is one of the children's Id, and so on, until I have a flat list of all child Ids of a certain user. No nesting objects or keeping track of hierarchy other than getting all descendant users of a given user. I tried this...

private List<int> GetChildIdsRecursive(int parentId)
{
    var childIds = new List<int>();

    return _dbContext.ApplicationUser
        .Where(r => r.ParentId.HasValue && r.ParentId.Value == parentId)
        .Select(r => childIds.AddRange(GetChildIdsRecursive(r.Id)));
}

But I get this error: Error CS0411 The type arguments for method 'Queryable.Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I know how many levels it goes, and so I could brute-force this, but the levels might change in the future. I'd much rather have a scalable solution. I just need to take a single Id, and find all child objects with a matching ParentId, recursively. 

This article seemed to be close to what I need, but I don't need or want to create a child collection for each user object and assign the child objects to that collection - I just need the collection of Ids: 

https://stackoverflow.com/questions/21262391/recursive-linq-query-select-item-and-all-children-with-subchildren

Generating emails programmatically

$
0
0

Hello,
I am using asp.net core 2.2, I have an mvc web application that provides a series of forms and utilities which allow a user to generate data which needs to be rendered in an email.

The resulting email content will include a table which must contain a row of clickable checkboxes. The requirement is that recipients will markup the table in a response and email that back.

Can anyone share a pointer on an approach that I can research, maybe a library that can do this for which I can then read the documentation for?

Thank you.

Multi-language options for dynamic content (from database) in ASP.NET Core MVC

$
0
0

HI guys,

I want to make my project in three languages, so the project will be multi-language. I've read about globalization & localization, but they are useful for static content such as menu names, datetime, and some other cultural things. I want to be able my CRUD operation in three languages, so that Admin will be able to create one post in different languages. And I don't need automatic translation as it doesn't translate well the sentence/paragraph based content. We will create them one-by-one, but I don't want to have different tables for them in database, but to make it so that resource-provider would work dynamically so that if I get content from database in default language by LINQ, it would be able to bind its other language variants. Thus, in click for ex. RU, the content would display the post description in Russian. Any good advice?

By the way, I've found one source (https://github.com/RickStrahl/Westwind.Globalization#installation-netcore )that explains this, but the way is long, I think there must be shorter way (for ex. choosing languanges in action using LINQ in relevant actions). I hope one of you found solution to such issue.

ODBC with ASP.NET Core 2.2

$
0
0

Hi Folks

I'm developing an application ASP.NET Core 2.2 on .NET Framework 4.7.2 that needs access to SQL Server, MySQL, Sap Hana, and DB2 thruODBC.
I have installed the ODBC Driver on Windows, the user fill a form with credentials and send the form to validate the access

The app builds a connection string and opens a connection to validate the access. The problem is that only work with SQL Server when I try with MySQL, Oracle or other I got the error Message "[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified".

The code I use to validate the connections string is in a separate .NET Framework Library and when I use it in a console app it works and when consuming it in ASP.NET CoreProject don't

using (OdbcConnection connection = new OdbcConnection("Driver={MySQL ODBC 5.1 Driver};server=localhost;Port=3306;Database=sakila;Uid=user;pwd=Password;Option=3;"))
{
  try
  {
     connection.Open();
  }
  catch (Exception e)
{
// return error message
} }

Any Ideas how to solve it

alive session while working in asp.net c#

$
0
0

Hi ,

while working , session automattically closed . how to session alive till my work completed.

In web config.

<sessionState mode="InProc" cookieless="true" timeout="30"/>

while login i'm maintaining customer id

Session["c_userid"] = "1";

In Every page & every action

if (Session["c_userid"] == null)
{
Response.Redirect(GetRouteUrl("HomeExpirePage", null));
}

if i m not doing anything in page 30 minutes session closed thats fine. but i m working in page that time Session["c_userid"] is null ? how ?


How to not display a certain number in razor?

$
0
0

Hi, I have an array of ints that i display the content of in razor:

<p> @Html.DisplayFor(t => Model.Numbers[2])</p>

This displays the number at index 2 of the array.

I wonder if there's a way to display an empty value without checking if the value is 0 in the html? 

I don't want to do this because I have alot of numbers and arrays to display and i can't iterate them in a foreach loop. I have huge arrays that needs to be displayed vertically next to each other. So this would be a solution:

@if(Model.Numbers[2] == 0)
{<p></p>
}

checking for null like this would be a very ardous task the way i have made the frontend. I'm hoping there's a way do do this in the displayfor property or something more clever, or else i have to rewrite my arrays to strings and do it in the backend.

Maybe i can do this in javascript, where i remove the content of a tag if it is 0? but that sounds like the same as checking for null with c# on each tag anyway.

I want to migrate into .Net core

$
0
0

I am trying to start migration to .Net core. However, when trying to install the .NET portability analyzer, It always gives me installation failed. I am using VS 2015. Is there another way to make analyzing?

how to store Personal Identification number , without viewing to others directly from database

$
0
0

Hi

In Employee table ,  there is one column Personal Identification number  . It is simple varchar column right now. But I want to change it should be  unreadable format to other people who are going to check the database.  That value only should be read from the Application , outside  the application the value cannot be read. What  is the best way to implement in asp.net core. Please help .

Why xdt:Transform (web.config) has no effect in VS 2017 Community?

$
0
0

Hello 

I migrate my VS 2010 project to VS 2017

In Web.config will be changed SQL-Server-connection String in accordance to live or testsystem.

it achived with following command in Web.Release.config

<addname="myConnectionString"connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True"xdt:Transform="SetAttributes"xdt:Locator="Match(name)"/>

But in VS 2017 it does not work:

- after deployment on live-system is the connection string in Release.Web.Config not overwritten and still reference to development-system.

Why it is so,  and how can achive I this goal?

Thanks

How to show employee Holiday Entiled and Remining holiday on the same row of group header and column

$
0
0

I have a data table to show employee holiday Entitled and Remaining Holiday. On this data table I would like to show the Entitled Holiday and Remaining holiday of each employee , on the group header of Employee . Holiday Entitled, Rem Holiday should not be shown on the detail line. But it should be shown on Employee group header row of the employee and below the corresponding column.

https://jsfiddle.net/931r0vqw/

In details line, Date of holiday , Holiday Hrs, Comment only should be shown.
Please can you help me to make that report. I am kindly looking for the help from you.

Switching between cultures in dropdown redirects to default culture

$
0
0

Hi guys,

I want to provide setting and other relevant details that I used in localization to make multi-language options to work. When I add culture query string to URL, content language changes properly, but making it with dropdown like I want gets me to default culture everytime I switch between cultures (languages).

Startup

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Foroffer.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using System.Resources;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Localization;

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //Add Localization
            services.AddLocalization(opts =>
            {
                opts.ResourcesPath = "Resources";
            });

            services.AddDbContext<OfferDbContext>(x =>
            {
                x.UseSqlServer(Configuration["Database:OfferDb"]);
            });

            services.AddIdentity<AppUser, IdentityRole>(options => {
                // options.SignIn.RequireConfirmedEmail = true;
                options.Lockout.MaxFailedAccessAttempts = 9;
                // options.User.AllowedUserNameCharacters = "qwertyuiopasdfghjklzxcvbnm";
                options.User.RequireUniqueEmail = true;


            })
                                      .AddEntityFrameworkStores<OfferDbContext>()
                                        .AddDefaultTokenProviders();

            services.AddMvc().
                AddViewLocalization(opts =>
                {
                    opts.ResourcesPath = "Resources";
                }).AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix).
                 AddDataAnnotationsLocalization().
                SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAntiforgery(a => a.HeaderName = "XSRF-TOKEN");

            services.Configure<RequestLocalizationOptions>(opts =>
            {
                var supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("az-Latn-AZ"),
                    new CultureInfo("en-US"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("ru-RU")
                };

                opts.DefaultRequestCulture = new RequestCulture("en-US");
                opts.SupportedCultures = supportedCultures;
                opts.SupportedUICultures = supportedCultures;
               // services.AddSingleton(opts);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //Request Localization
            var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(options.Value);
            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                        name: "root",
                        template: "{action}/{id?}",
                        defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Controller /action

         private readonly OfferDbContext _offerDbContext;
        private readonly IStringLocalizer<HomeController> _localizer;

        public HomeController(OfferDbContext offerDbContext, IStringLocalizer<HomeController> localizer)
        {
            _offerDbContext = offerDbContext;
            _localizer = localizer;
        }



[HttpPost]
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );

            return LocalRedirect(returnUrl);
        }

_PartialView

@using System.Threading.Tasks
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
}<form asp-controller="Home" asp-action="SetLanguage"
      asp-route-returnUrl="@Context.Request.Path"
      method="post" class="form-horizontal">
    @Localizer["Language:"] <select name="culture" onchange="this.form.submit();"
                                    asp-for="@requestCulture.RequestCulture.UICulture.Name"
                                    asp-items="cultureItems"></select></form>

And part of View (Index)

@using System.Threading
@using Microsoft.AspNetCore.Mvc.Localization
@model Foroffer.Models.ViewModels.SlideViewModel

@inject IViewLocalizer Localizer

<button class="infotool" id="mynews">
<p>@Localizer["Foroffer"]</p>
</button>

I have also resource files that translates given Localizer (Foroffer). Folder structure is like here:https://prnt.sc/n4cuko

Please review attentively, if any further info needed, I'm ready to share with you.

Help needed Image Processing

$
0
0

Hello Team,

I am working in Asp.net core 2.1 webAPI and i have a scenario like i get base64 string as input and i need to convert that to an image(jpeg) and need to store the image in different server (network path). can you please share me a code snippet to achieve this. Thanks in advance. 


Adding Swagger Generation Support in Asp.Net Core 3.0

$
0
0

Swagger is nowadays a standard for API Documentation, especially when we work on microServices or simple API.

At this moment, there's no full support, in .Net/.Net Core for Swagger code generation, neither from swagger's editor because of some problem neither from .Net/.Net Core Framework.

The situation is different in Java, where the support for swagger-code generation via a plugin is a very solid reality.

Could we be able to add native Swagger support in the .net core for better working in this microServices age?

Thank you

Webservice ASMX to .NetCore

$
0
0

Hello community.
I currently have a WebService in SOAP (ASMX) that serves many applications. I want to change this service to the NetCore API. I already did the class to provide this servicesoap-net-core.
But in the applications that consume it, they give me this error.
The client found the response content type 'text/html; charset=utf-8', but 'text/xml ' was expected.

Can you help me solve this problem?

Trying to modify xml file stored in wwwroot - IHostingEnvironmnet it always returns null

$
0
0

I hope you are well.

I am having an issue. I want to be able to update my XML file that is stored in the web root (wwwroot) but whenever I try to use IHostingEnvironmnet it always returns null.

my code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace GWeb.Infrastructure
{
public class SiteMapHelper
{
private readonly IHostingEnvironment _hostingEnvironment;

public SiteMapHelper(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}

public void AddPostToSiteMap(int postID, string postTitle)
{
var fileName = @"sitemap.xml";
var fileLocation = _hostingEnvironment.WebRootPath;
var siteMapFilePath = Path.Combine(fileLocation, fileName);
XElement sitemapdoc = XElement.Load($"{fileName}");
var urlset = sitemapdoc.Element("urlset");
XElement url = new XElement("url",
new XElement("loc", "https://www.griffithswebdesign.com/Blog/Post/" + postID + "/" + postTitle.ToSeoUrl()),
new XElement("lastmod", DateTime.Now),
new XElement("changefreq", "weekly"),
new XElement("priority", "0.5"));
urlset.Add(url);
}


}
}

I am using asp.net core 2.1 Any suggestions that you may have will be appreciated. Thank you.

A few API questions

$
0
0

Hi

I am changing my web app from mvc to core, and I am changing from razor to angular.

I have started building and would prefer to put my API in a seperate project to the angular, whats the best way to achive this, would it be in a better having two solutions and running them both at the same time?

Also when the API is made public over the internet how do i protect it from unauthorised websites or requests accessing it, I know how to authorise users i will be using identity when people need to be logged in, but how do i make sure it is along accessed by the websites i want, is that at server level or something i need to code in?

Any suggestions would be appriciated.

ODBC with ASP.NET Core 2.2

$
0
0

Hi Folks

I'm developing an application ASP.NET Core 2.2 on .NET Framework 4.7.2 that needs access to SQL Server, MySQL, Sap Hana, and DB2 thruODBC.
I have installed the ODBC Driver on Windows, the user fill a form with credentials and send the form to validate the access

The app builds a connection string and opens a connection to validate the access. The problem is that only work with SQL Server when I try with MySQL, Oracle or other I got the error Message "[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified".

The code I use to validate the connections string is in a separate .NET Framework Library and when I use it in a console app it works and when consuming it in ASP.NET CoreProject don't

using (OdbcConnection connection = new OdbcConnection("Driver={MySQL ODBC 5.1 Driver};server=localhost;Port=3306;Database=sakila;Uid=user;pwd=Password;Option=3;"))
{
  try
  {
     connection.Open();
  }
  catch (Exception e)
{
// return error message
} }

Any Ideas how to solve it

Viewing all 9386 articles
Browse latest View live


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