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

The format of value 'api.vericred.com' is invalid API Endpoint in .Net Core --

$
0
0

Hi All.

This is a typical question and would require knowledge of Vericred medicare API to some extent. Calling the API through .NET Core application. Already registered with the developers account and have relevant key stored in json file.

Here's the calling code:

[Route("GetMedicineData/med_name")]
        [HttpGet]
        public async Task<ActionResult<DrugsModel>> GetMedicineData(string med_name)
        {
            APIRequestMaker objAPI = new APIRequestMaker(_config);
            DrugsModel drugsModel = new DrugsModel();
            string apivalue = _config.GetSection("Vericred:API_Key").ToString();

            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("api.vericred.com"));     *** this line
                    client.DefaultRequestHeaders.Add("Authorization", "API Key" + apivalue);

                    var streamTask = client.GetStreamAsync("api.vericred.com/drugs?search_term=" + med_name.ToString());
                    var drugData = await JsonSerializer.DeserializeAsync<DrugsModel>(await streamTask);

                    return (drugData);
                }
            }
            catch(Exception exp)
            {
                throw exp.GetBaseException();
            }
            
        }

Here DrugsModel is the corresponding mapped model 
When you run it, the exception thrown on the line marked is The format of value 'api.vericred.com' is invalid.

Not sure why that pops up. Things look like I did more or less correctly. If you test via Postman, the API endpoint, you need to select API Key as 'Type' and provide Key-Value as Vericred-Api-Key - blablaablablaaawhatever.

Simply put I have tried to replicate that in my code. The official docs at Vericred Developer don't contain relevant instructions/guiline.

Thanks.


Unanle to use MVC6 grid inside my asp.net mvc core. Error "'IHtmlHelper' does not contain a definition for 'Grid' ...

$
0
0

I want to use MVC6 grid from this link https://mvc6-grid.azurewebsites.net/ so i install the

Install-Package NonFactors.Grid.Mvc6

but inside my view when i write the following :-

@model IEnumerable<LandingPageFinal3.Models.Doctor>
@(Html .Grid(Model) .Build(columns => { columns.Add(model => model.Name).Titled("Name"); columns.Add(model => model.Surname).Titled("Surname"); columns.Add(model => model.Age).Titled("Age"); columns.Add(model => model.Birthday).Titled("Birth date"); columns.Add(model => model.IsWorking).Titled("Employed"); //popup part columns.Add(model => $"<a data-modal='' data-id=\"{model.Id}\" href='PasswordRestUser/{model.Id}' id=\"ss\" asp- action=\"PR\" asp-route-id=\"@item.Id\" class=\"btn btn-info\" '> PR <span class='glyphicon glyphicon-user'> </span> </a>").Encoded(false); }) .Filterable() .Sortable() .Pageable() ) <div id='myModal' class='modal fade in'><div class="modal-dialog"><div class="modal-content"><div id='myModalContent'></div></div></div></div>

i got this error:-

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS1061	'IHtmlHelper<IEnumerable<Doctor>>' does not contain a definition for 'Grid' and no accessible extension method 'Grid' accepting a first argument of type 'IHtmlHelper<IEnumerable<Doctor>>' could be found (are you missing a using directive or an assembly reference?)	

any advice on this?

How to use stored procedure to return a non dbSet object in EF 3.1 ?

$
0
0

Hi

My question is that how can i use stored procedure in ef core 3.1 to return something like anonymous types without creating some viewModel as dbSet in our dbContext ?

Thanks in advance

Net Core 3 Identity

$
0
0

Hey everyone. I'm new to asp net core and i need some help. I scaffolded the Identity into my  web form razor project. The database name is ProiectLicenta where i can see all the Indentity tables. Basically what i am trying to do is if anyone registers i want their usernames and emails from the AspNetUsers table listed in another page called userlist. That table on the userlist has to update everytime a new person registers. Is it posible?

Server-side Paging,Filtering & Sorting using MVC6 grid inside my asp.net mvc core

$
0
0

Inside my Asp.net Core MVC i added the MVC6 grid from this url @ https://mvc6-grid.azurewebsites.net/. but i have noted that the paging and filtering will be done on the client side, so each time we filter,sort or paging the whole records will be retrived. so can i force the MVC6 Grid to do the filter,sort and paging on the server-side instead?

Here is my Action Method:-

public async Task<IActionResult> Index()
        {

            var results = await _context.Doctor.ToListAsync();
            return View(results);

        }

and here is the view:-

@model IEnumerable<LandingPageFinal3.Models.Doctor>

@(Html
    .Grid(Model)
    .Build(columns =>
    {
        columns.Add(model => model.PhysicianFirstName).Titled("Name");
        columns.Add(model => model.PhysicianLastName).Titled("Surname");
        columns.Add(model => model.Phone).Titled("Phone");
    })
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
    .Pageable()
)

any advice on this please?

Thanks

Override settings used in ConfigureServices, in integration tests

$
0
0

During Startup, in ConfigureServices, I need to access a property from appsettings.json.
I'd like to have it typed, so I'm using the Options pattern.
To retrieve the value, I do this;

public void ConfigureServices(IServiceCollection services)
{
...
var jwtOptions = configuration.GetSection("Jwt").Get<JwtOptions>();
// then use jwtOptions.MyProperty
...
}

The option class looks like this:

public class JwtOptions
{
   public string? MyProperty { get; set; }
}

When debugging, all works fine and it gets the correct value from the config file.

Now I want to override the value from the config file during integration tests.
I'm creating my HttpClient like this and overriding the options value in the ConfigureTestServices method.

var client = webAppFactory.WithWebHostBuilder(builder =>
{
   builder.ConfigureTestServices(services =>
   {
      services.Configure<JwtOptions>(opts =>
      {
         opts.MyProperty= "Test value";
      });
   });
})
.CreateClient(new WebApplicationFactoryClientOptions());

Note: I'm using the Startup file from the webproject when creating the webAppFactory, not using any inheritance.

Unfortunately, the value doesn't get overriden when running the test and the configuration value retrieved is the one that's the web project's appsettings.json file.

What am I doing wrong?

Forcing client side evaluation on a predicate builder expression in .net core 3.1

$
0
0

I am using LinqKit's predicate builder expressions for search functions. I build a dynamic expression which is then applied on the entity.

Had this working before, but after migrating to .net core 3.1, I am getting errors due to the restriction on client side valuations.

I understand this can be overcome by forcing AsEnumerable() casting.

However I don't understand exactly how to do this on predicate expressions.

Predicate builder function:

private Expression<Func<A, bool>> BuildDynamicWhereClauseForA(string searchValue)
{
var predicate = PredicateBuilder.New<A>(true);

if (!string.IsNullOrWhiteSpace(searchValue))
{
var searchTerms = searchValue.Split(' ').ToList().ConvertAll(x => x.ToLower());

foreach (var item in searchTerms)
{
predicate = predicate.Or(x => x.col1.ToLower().Contains(item));
predicate = predicate.Or(x => x.col2.ToLower().Contains(item));
predicate = predicate.Or(x => x.col3.ToString().ToLower().Contains(item));
}
}

return predicate;
}

Function which performs actual database call:

private List<AD> GetDataFromDBForA(string searchBy ...)
{
var whereClause = BuildDynamicWhereClauseForA(searchBy);

List<AD> result;

result = db.A.AsExpandable()
.Where(whereClause)
.OrderBy(sortBy)
.Select(m => new AD
{
...
...
})
.Skip(skip)
.Take(take)
.ToList()

return result;
}

This is the error I get:

> The LINQ expression 'DbSet<A>
> .Where(e => e.col1.ToLower().Contains(__item_0) || e.col2.ToLower().Contains(__item_0) ||
> e.Col3.ToString().ToLower().Contains(__item_0))' could not be
> translated. Either rewrite the query in a form that can be translated,
> or switch to client evaluation explicitly by inserting a call to
> either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
> ToListAsync().

I understand why this is happening.

But I don't understand predicates as well and can't seem to cast the result to enumerable or list to force client side evaluation.

What I have tried:

result = db.A.AsEnumerable()
.AsQueryable()
.Where(whereClause)
.OrderBy(sortBy)

I am migrating asp.net project Unittest(UT )to asp.net core 3.1

$
0
0
<div class="body">

HI Team,

I am migrating asp.net project Unittest(UT )to asp.net core 3.1 and observed Fake dll not getting generated there

please suggest

</div>

add static html links inside MVC6 webgrid will make them UN-clickable

$
0
0

I have the following asp.net core MVC6 web grid https://mvc6-grid.azurewebsites.net/ :-

@(Html
    .Grid(Model)
    .Build(columns =>
    {
        columns.Add(model => model.PhysicianFirstName).Titled("Name");
        columns.Add(model => model.PhysicianLastName).Titled("Surname");
        columns.Add(model => model.Phone).Titled("Phone");
        columns.Add(model => $" <a asp-action='Edit' asp-route-id=\"{model.Id}\">Edit</a> |<a asp-action='Details' asp-route-id=\"{model.Id}\">Details</a> |<a asp-action='Delete' asp-route-id=\"{model.Id}\">Delete</a>").Encoded(false);
    })
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
    .Pageable(pager =>
    {

        pager.RowsPerPage = 250;
    })

where inside the last column i specify to add 3 links (Edit,Details & Delete), where the links will be shown but they will be UN-clickable, so not sure why?

here is a screen shot of the results and the markup that got generated:-

alinks

Email Templating API : Merging Multiple Razor Views into Single HTML as String

$
0
0

Hi All 

I am developing email api based on various template , i have multiple razor views which have footer , header and template body cshtml's , any idea how we can merge as single html file before sending to SMTP for sending emails.

Thanks in advance!!

Web API : .Net Framework 4.5 to .Net Core 3.0 Migration

Exception user unhandled

$
0
0

I keep going from appplicationdbcontext file to program files errors.

Below is the error message  I am using aspnet core mvc 3.1

System.TypeLoadException: 'Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.'

Here is the ApplicationDBContext file 

using Bumples15.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Bumples15.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)  //here is the error
{
}
public DbSet<Product> Products { get; set; }

public DbSet<Order> Orders { get; set; }

}
}

Below is the program file;

namespace Bumples15
{
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>();
});

}
}

here is the startup file:

using Bumples15.Data;
using Bumples15.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Bumples15
{
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.AddControllersWithViews();

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();


services.AddScoped<RoleManager<IdentityRole>>();
services.AddScoped<IRepository<Product>, SqlBooksRepository>();
services.AddScoped<IRepository<Order>, SqlOrdersRepository>();

services.AddRazorPages();

services.AddRazorPages();
}

// 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();

}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();


app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}

Some of the programs were files taken from aspnet core mvc 2.1.  But I think that I have upgraded them all.

Is that where my problem is:

Thanks

Jen

How can I return a 404 status code by app.UseStatusCodePages?

$
0
0

These days I am handling 404 Not Found by Asp.Net Core .

As we know, there are several ways to achieve this: app.UseStatusCodePagesWithRedirects/app.UseStatusCodePagesWithReExecute/app.UseStatusCodePages .

I have to choose the app.UseStatusCodePages for I need to localizer the page by URL.

For example:

https://www.microsoft.com/en-us/microsoft-365/

The 'en-us' in URL just for deciding the language of the page.

Here is my code in startup.cs

app.UseStatusCodePages(async context =>
            {
                string currentCulture = "";
                if (context.HttpContext.Request.Path.Value.Split('/').Length < 2)
                {
                    currentCulture = "en";
                }
                else
                {
                    string LanguageGet = context.HttpContext.Request.Path.Value.Split('/')[1];
                    currentCulture = SupportedCultures.Find(X => X.Name == LanguageGet) == null ? "en" : SupportedCultures.Find(X => X.Name == LanguageGet).Name;
                }
                var redirectPath = "/" + currentCulture + "/Error/" + context.HttpContext.Response.StatusCode;
                context.HttpContext.Response.Redirect(redirectPath);
            });

Now it works.

However, after I input a URL which does not exist. The header shows a 302 status code in the Network of Chrome DevTools but not a 404 status code.

Well, when I input the URL(https://www.microsoft.com/en-us/123.html), the header shows a right 404 status code in the Network of Chrome DevTools.

I searched about this on Google. Someone said I should add a ProducesResponseType in the controller, just like this:

public class OthersController : Controller
    {
        [Route("{culture=en}/Error/{code:int}")]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public IActionResult Error(int code)
        {            
            return View(code);
        }
    }

Well, it doesn't work any. I want to solve this because of SEO.

How can I solve this? Thank you.

Display certain records in MVC CRUD application.

$
0
0

Hi All,

I am in the process of creating an Employee Training Records database using SQL and Visual Studio 2019.

So far so good, however at the moment I have one question which I hope you can me out with.

I have a Model, Controller and View for listing employees. There is an option to amend if the employee is current or not.

I would like to create a page which just lists current employees and another which just lists non current employees. 

How do I achieve this? I know I can have a search/filter facility but I want to make this as easy as possible for end users.

Do I use a IF or WHERE statement? If so how and where would this be placed?

Many thanks in advance.

Mick  

  

Hosting ASP.net Core MVC on Raspberry Pi 3b+ Acces denied

$
0
0

Hello people

I am programming in ASP.net normally for MVC but I am making some website for school project and I thaught maybe it is nice when I can run it on a Raspberry Pi. So after searching on the web I made my ASP.net MVC website to a ASP.net Core MVC website and I deployed that to my raspberry pi. That worked but now I updated my code and I want to redeployed it and I have some strange error. 

Have any of you haved that error already?


use jwt token to login identity authentication in web

$
0
0

hi , 

in my web project (asp.net core mvc) i used api from an api project , in my api project i used jwt authentication and in web project use identity  authentication 

i want get authentication  token from api and login with this token in identity and work with identity in web

how to connect jwt to identity (api to web)  with token or another way? 

port 5xxxx is already in use, unable to connect to web server IIS Express

$
0
0

Hi can anyone help? I've been stuck with this issue for the past 2 days. I'm trying to run asp.net application in visual studio 2019 I've tried changing the port numbers, it doesn't work, it still pops up with the error "unable to connect to web server IIS Express'. I've deleted my vs folder with the config like 100 times, restarted visual studio, did a clean and build, restarted my PC. None of this has worked. I've looked into the list of processes and I can see this port is not being used. I've tried using netstat to find what's using that port no luck. I mean it doesn't make any sense, any ports I tried I get the same "unable to connect to web server iis express error. This is happening to multiple projects in a solution but when I create a new project in a fresh solution, I can run new projects fine. I've also tried visual studio 2017, no luck! So the problem is with these web projects. Someone please help I'm a bit frustrated.

could we write word press plugin with asp.net

$
0
0

I want to write an word press plugin whit asp.net in order to add sum special services that are not support by ordinary plugin . 

<div id="skyroom-extension-is-installed"></div>

Core 3.1 React Web App and Web API Security Implementation with Bearer Token

$
0
0

How to implement  Visual Studio Solution with two project Web Client and Web API and pass bearer token to Web API

Ienumerator error - any inputs will be helpful

$
0
0

I am getting the following error. I am learning from the videos/usage code from internet.

Severity Code Description Project File Line Suppression State
Error CS1579 foreach statement cannot operate on variables of type 'HomeDetailsViewModel' because 'HomeDetailsViewModel' does not contain a public instance definition for 'GetEnumerator' EmployeeManagement C:\projects\EmployeeManagement\Views\Home\Details.cshtml 17 Active

Details.cshtml

@model EmployeeManagement.ViewModels.HomeDetailsViewModel

@{ ViewBag.Title = "Employee Details";}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<table><thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
</tr>
</thead>
<tbody>
@foreach(var employee in Model)

<tr>



<td>@employee.Id</td>
<td>@employee.Name</td>
<td>@employee.Department</td>
</tr>
}</tbody> </table></body></html>

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

namespace EmployeeManagement.Models
{
public interface IEmployeeRepository
{
Employee GetEmployee(int Id);
IEnumerable<Employee> GetEmployees();
}
}

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

namespace EmployeeManagement.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }

public string Email { get; set; }

public string Department { get; set; }

}
}

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

namespace EmployeeManagement.ViewModels
{
public class HomeDetailsViewModel
{
public Employee Employee { get; set; }
public string PageTitle { get; set; }
}
}

Viewing all 9386 articles
Browse latest View live


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